Thursday, November 19, 2009

Ajax + PHP

How can i turn what I did today into something worth reading....

Well I set out to make a site that would allow users to enter data into a form and send it to a database. Then it refreshes a div tag with the new content (the stuff they entered).

The first way I tried was to put the PHP at the top of the page, then basically call "self" when the submit button was pushed. While this "worked" it refreshed the page, which is not what I wanted, it felt kind of "jerky".

Then I set out to see how I could use AJAX to fix my problem. It turns out, that it is quite simple to call a PHP file, and the only real difference to what i had with my current PHP was 1. it was in my html page, and 2. It outputted too much.

The trick with AJAX and PHP is instead of doing something like this

echo $f_name;
echo $l_name;

You must create a string to add everything together, and then output that string.

Instead of the above code you would type:
$outPutString .= $f_name;
$outPutString .= $l_name;

Then when you are ready to send done with adding to the string, output it.

echo $outPutString;

this Echo (or Print) is what the AJAX will receive and stick in your code.

A major thing to notice is your "Submit" button is not type="submit" any more, you need to change that to type="button".

This will now not clear any data, I did not look too far into this, but I reset everything to "" when the AJAX is called to send the form. Something like this

document.getElementById('var1').value = "";
document.getElementById('var2').value= "";
document.getElementById('var3').value= "";


Helpful Site:

While this helped with this problem, a decent knoweledge of PHP and DOM JavaScript is important.

3 comments:

Jackie said...

thanks for sharing! :) good stuff.

Joey said...

Not one mention of "I'm going to post more." I like what I see ;)

James said...

I have no idea!!!