[AJAX] PHP and HTML

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
I am in a bit of a pickle...

I have a form with two input fields which gets send to a php file now I want to implement Ajax so that the results can load on the same page without having to refresh.

For the life of me I can't figure out how to achieve this.

I post two variables to the php file ( $url1 & url2 )

The php then does some magic via a bunch of preg_matches.

and then loads the new page with the results echoed

I now want to use Ajax instead to load content and echo the varies results of the php file.

But I am so new to ajax ( started a few hours ago ) that I have no clue how to do this.


----

The rest of the site works beautifully I can load content dynamically no problem, it's just with this submit and php functions part that is breaking my brain a little bit.
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
How are you dynamically loading your other content?
Not really applicable as it's working and not the same, but anyhow:


Code:
Onclick="About"

Then the Ajax part will fetch the new Divs:

Code:
document.getElementById("about").innerHTML = xhttp.responseText;
Code:
 xhttp.open("GET", "about.php", true);

However, what I want is when the human submits the form I want Ajax to load the result of the php file by loading a file that has the results echoed in the html already.


Example

You submit your name and surname

I want ajax to then change the content to

You have entered <?php echo $Fname ?> etc etc

----

What I want is a lot more complicated as the php file will perform varies functions on the submitted data, but the idea is that I want to load the results of that php file using Ajax instead of:

readfile("../results.php"); at the end of the external php file.
 

Necropolis

Executive Member
Joined
Feb 26, 2007
Messages
8,401
Why not have your PHP page return the markup you want displayed?

I'm not seeing how this is any different (aside from the user form submission) to the example you already posted...
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
Why not have your PHP page return the markup you want displayed?

I'm not seeing how this is any different (aside from the user form submission) to the example you already posted...

Because I do not want to reload the entire page I simply want to dynamically change the one DIV.

To reload the page is not ideal
 

rward

Senior Member
Joined
Oct 26, 2007
Messages
865
Thor, it's not different at all.

What you would probably want is to return either markup or a structured response (json, xml, etc) I'd recommend json.

Your 'form page' will do the ajax post and the 'xhttp.responseText' has the response (the Output) from your php page.

If you're using jquery then it would be along the lines of:

$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
$('.results').val('You entered '+data['name']+' and '+data['time']);
});

data would be what is outputted form your test.php page.

I'll write you up something a bit later.

You need to use javascript inside that .done(function(data)) { }) function to update the form page with the information returned from your php page (which is stored inside the data variable).
So you probably need a couple of hidden divs on your form page which you then put the returned data into and then make visible.

That's the 'doing it yourself way' or you use something like angular or backbone, etc to do the 'variable binding'.
 
Last edited:

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
Thor, it's not different at all.

What you would probably want is to return either markup or a structured response (json, xml, etc) I'd recommend json.

Your 'form page' will do the ajax post and the 'xhttp.responseText' has the response (the Output) from your php page.

If you're using jquery then it would be along the lines of:

$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
$('.results').val('You entered '+data['value1']+' and '+data['value2']);
});

data would be what is outputted form your test.php page.

So difficult to explain this without giving away to much of my idea on a public forum.

My output is a little bit more complicated than var1, var2 and var3.

If you are interested then I can pm you a link to my test site and hopefully that will explain it better?
 

_kabal_

Executive Member
Joined
Oct 24, 2005
Messages
5,923
Who cares what the output is.

if you are returning 1 string, or an array with millions of items, or an object with tons of properties, you are still only returning 1 thing.

You do not have a special secret requirement.

I would also say that most of the time, ajaxing in html is a *** idea.
 
Last edited:

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
Who cares what the output is.

if you are returning 1 string, or an array with millions of items, or an object with tons of properties, you are still only returning 1 thing.

You do not have a special secret requirement.

I would also say that most of the time, ajaxing in html is a *** idea.

It probably is.

But I'm learning, so I am really determined to use Ajax for this and I fully believe Ajax in this particular case would be sweet as fck.

It's beautiful!

I just need some guidance.

Really it's beautiful.
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
I am obviously going to share my finished work with all you.

But right now I need to figure this one out first.


( always remember I have zero to no experience other than HTML5 and CSS3 ) this is all new to me.
 

xumwun

Expert Member
Joined
Jul 30, 2006
Messages
3,151
Who cares what the output is.

if you are returning 1 string, or an array with millions of items, or an object with tons of properties, you are still only returning 1 thing.

You do not have a special secret requirement.

I would also say that most of the time, ajaxing in html is a *** idea.

^^ this
Rather encode data as JSON
 

Necropolis

Executive Member
Joined
Feb 26, 2007
Messages
8,401
Because I do not want to reload the entire page I simply want to dynamically change the one DIV.

To reload the page is not ideal

You use JS to post to the PHP page - wait for the response and then load the response data into the div or whatever other element you want it to be in.

...
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
You use JS to post to the PHP page - wait for the response and then load the response data into the div or whatever other element you want it to be in.

...

Progress now guide me please as I looked into this earlier today but couldn't come up with a way.
 

Necropolis

Executive Member
Joined
Feb 26, 2007
Messages
8,401
Progress now guide me please as I looked into this earlier today but couldn't come up with a way.

I've never done it before with PHP - I just understand what the concepts are.

Do a bit of googling - go through some tutorials, it's going to be easier for you in the long run if you get your head around the concepts yourself.
 

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
I've never done it before with PHP - I just understand what the concepts are.

Do a bit of googling - go through some tutorials, it's going to be easier for you in the long run if you get your head around the concepts yourself.

That's the thing could not find a way at all.

And the concept itself is confusing since php is server side and js client side which means the two cannot under no circumstances communicate with each other.

So I need a way to post the form variables to the PHP file using Ajax and then upon completion of that php script let Ajax load the results page with the php results echoed in.
 

Necropolis

Executive Member
Joined
Feb 26, 2007
Messages
8,401
That's the thing could not find a way at all.

And the concept itself is confusing since php is server side and js client side which means the two cannot under no circumstances communicate with each other.

So I need a way to post the form variables to the PHP file using Ajax and then upon completion of that php script let Ajax load the results page with the php results echoed in.

They most definitely can.

That's one of the reasons people developed AJAX concepts.
 

Darko

Senior Member
Joined
Jul 9, 2008
Messages
627
And the concept itself is confusing since php is server side and js client side which means the two cannot under no circumstances communicate with each other.

I am not really sure what this is supposed to mean because you need client side to communicate with the server side.

You use your $.post to post to your php page that references your database etc. The php page will then return your recordset by using the echo json_encode(recordset);

On the .success callback on the $.post in your js, you then loop through the data.
 

SBSP

Senior Member
Joined
Sep 7, 2007
Messages
663
All you want to do is dynamically change content of a div So using AJAX is the whole Idea,
I'm trying to understand what you want to do.

Maybe this will point you into the right direction, below is a GET and POST example.
From a different thread you asked about GET and POST.
GET and POST transfer variables from one page to another (They both serve the same purpose and are simply 2 different methods of doing it) I'm sure you already got that.

Below there are 2 forms and each have a text box, when typing in them and upon the up key it calls its respective java script which then gets data from another PHP file

NOTE!: Its not actually getting a PHP variable as such it gets it as returned data to HTML so its getting text displayed by the web server. (Hope I'm not confusing you)

and the second one does the same but uses POST, the below looks like allot of code but its actually quite simple. if you follow it.

Then when you press the the submit button it will GET and POST to another page called registration.

I made the below example directly googling "PHP AJAX EXAMPLE" and the first hit was

http://www.w3schools.com/php/php_ajax_php.asp

Copy and paste the code into the root of a test directory using wamp or what ever and give it a go.

index.php
PHP:
<!DOCTYPE html>
<html>
<head>
<script>
//GET EXAMPLE check username
function CheckUserName(str) {
     if (str.length == 0) {
         document.getElementById("txtHint").innerHTML = "";
         return;
     } else {
         var xmlhttp = new XMLHttpRequest();
         xmlhttp.onreadystatechange = function() {
             if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                 document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
             }
         }
         xmlhttp.open("GET", "checkinput.php?VAR1="+str, true);
         xmlhttp.send();
     }
}
//GET EXAMPLE Check Passowrd
function CheckPassowrd(str) {
     if (str.length == 0) {
         document.getElementById("txtHint").innerHTML = "";
         return;
     } else {
         var xmlhttp = new XMLHttpRequest();
         xmlhttp.onreadystatechange = function() {
             if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                 document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
             }
         }
         xmlhttp.open("GET", "checkinput.php?VAR2="+str, true);
         xmlhttp.send();
     }
}
//POST EXAMPLE check username
function CheckUserNamewithPOST(str) {
     if (str.length == 0) {
         document.getElementById("txtHintPOST").innerHTML = "";
         return;
     } else {
         var xmlhttp = new XMLHttpRequest();
         xmlhttp.onreadystatechange = function() {
             if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                 document.getElementById("txtHintPOST").innerHTML = xmlhttp.responseText;
             }
         }
         xmlhttp.open("POST", "checkinput.php?VAR3="+str, true);
         xmlhttp.send();
     }
}
//POST EXAMPLE Check Passowrd
function CheckPassowrdwithPOST(str) {
     if (str.length == 0) {
         document.getElementById("txtHintPOST").innerHTML = "";
         return;
     } else {
         var xmlhttp = new XMLHttpRequest();
         xmlhttp.onreadystatechange = function() {
             if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                 document.getElementById("txtHintPOST").innerHTML = xmlhttp.responseText;
             }
         }
         xmlhttp.open("POST", "checkinput.php?VAR4="+str, true);
         xmlhttp.send();
     }
}
</script>
</head>
<body>

<h3>GET Example</h3>
<form  action="registration.php" method="GET">
	Email Address<br>
	<input type="text" name="VAR1" onkeyup="CheckUserName(this.value)"><bf>
	Email address must contain an @ sign.<br><br>
	Password<br><input type="text"  name="VAR2" onkeyup="CheckPassowrd(this.value)"> Password fields must contain an ! sign.<br><br>
	<input type="submit" value="SEND NOW">
</form>
<p>Notification: <span id="txtHint"></span></p>
<br><br>





<h3>POST Example</h3>
<form  action="registration.php" method="POST">
	Email Address<br>
	<input type="text" name="VAR3" onkeyup="CheckUserNamewithPOST(this.value)"><bf>
	Email address must contain an @ sign.<br><br>
	Password<br><input type="text"  name="VAR4" onkeyup="CheckPassowrdwithPOST(this.value)"> Password fields must contain an ! sign.<br><br>
	<input type="submit" value="SEND NOW">
</form>
<p>Notification: <span id="txtHintPOST"></span></p>

</body>
</html>

checkinput.php
PHP:
<?php

if(!empty($_GET["VAR1"])){$VAR1=$_GET["VAR1"];}else{$VAR1='';}
if(!empty($_GET["VAR2"])){$VAR2=$_GET["VAR2"];}else{$VAR2='';}
if(!empty($_GET["VAR3"])){$VAR3=$_GET["VAR3"];}else{$VAR3='';}
if(!empty($_GET["VAR4"])){$VAR4=$_GET["VAR4"];}else{$VAR4='';}


if($VAR1<>''){echo CallCheckUserforExclamation($VAR1);}
if($VAR2<>''){echo CallCheckPassforAt($VAR2);}
if($VAR3<>''){echo CallCheckUserforExclamationWITHPOST($VAR3);}
if($VAR4<>''){echo CallCheckPassforAtWITHPOST($VAR4);}

//GET EXAMPLE check username
function CallCheckUserforExclamation($VAR1)
{
	if (strpos($VAR1, '@') !== false) {echo '<font color="green">Email address is valid (USING GET)</font>';}else{return '<font color="red">Email not valid and must contain an @ sign (USING GET)</font>';}	
}
//GET EXAMPLE Check Passowrd
function CallCheckPassforAt($VAR2)
{
	if (strpos($VAR2, '!') !== false) {echo '<font color="green">Passowrd is strong (USING GET)</font>';}else{return '<font color="red">Password not strong enough and must contain an ! (USING GET)</font>';}	
}
//POST EXAMPLE check username
function CallCheckUserforExclamationWITHPOST($VAR3)
{
	if (strpos($VAR3, '@') !== false) {echo '<font color="green">Email address is valid (USING POST)</font>';}else{return '<font color="red">Email not valid and must contain an @ sign (USING POST) </font>';}	
}
//POST EXAMPLE Check Passowrd
function CallCheckPassforAtWITHPOST($VAR4)
{
	if (strpos($VAR4, '!') !== false) {echo '<font color="green">Passowrd is strong(USING POST)</font>';}else{return '<font color="red">Password not strong enough and must contain an !(USING POST)</font>';}	
}


?>

registration.php (Optional)
PHP:
<?php
if(!empty($_GET["VAR1"])){$VAR1=$_GET["VAR1"];}else{$VAR1='';}
if(!empty($_GET["VAR2"])){$VAR2=$_GET["VAR2"];}else{$VAR2='';}
if(!empty($_POST["VAR3"])){$VAR3=$_POST["VAR3"];}else{$VAR3='';}
if(!empty($_POST["VAR4"])){$VAR4=$_POST["VAR4"];}else{$VAR4='';}
echo $VAR1 . '<br>';
echo $VAR2 . '<br>';
echo $VAR3 . '<br>';
echo $VAR4 . '<br>';

?>

<br><br>
<a href="index.php">GO BACK</a>
 
Last edited:

SBSP

Senior Member
Joined
Sep 7, 2007
Messages
663
That's the thing could not find a way at all.

And the concept itself is confusing since php is server side and js client side which means the two cannot under no circumstances communicate with each other.

Directly sharing Java variables with PHP Variables, cant be done. (I emphasize on directly there are work arounds) If it was then there would have been one massive security hole.

Java script being part of the client (Browser) can fetch data and only update to change part of a page. It litrally goes and fetch data then visually changes the section or rather element you want.
 
Last edited:
Top