[jQuery Tutorial] Posting Server Side

All things website development.

[jQuery Tutorial] Posting Server Side

Postby doddsey_65 » Tue Apr 05, 2011 8:56 pm

In this tutorial i will show you how to post to a sever side script using jquery and print the results depending on what is returned.

start with the no conflict method as shown in the previuos tutorial.

Code: Select all
var $j = jQuery.noConflict();


now lets say we want to post a users username to the serverside script so that can add it to the database.

we start with declaring our username variable

Code: Select all
var user_name = 'doddsey_65';


now we need to actually send it. We use this using jQuerys post method:

Code: Select all
$j.post()


the first parameter we are going to use is the url of the server side script

Code: Select all
$j.post('ss_script.php')


but we also need to send the data along to the script. so we add some more parameters.

Code: Select all
$j.post('ss_script.php'{name:user_name})


here we have told it to send along the username variable.
The name variable is what we will use to access the username in the server side script via the $_POST super global.

so in your server side script just look for the posted variable and add it to the database:

Code: Select all
if(isset($_POST['name']))
{
mysql_query("INSERT INTO table (column) VALUES ('".$_POST['name']."')")or die(mysql_error())
}


And thats it.
But what if we want to echo a success result?

back in the jquery we need to add a function to the stiff we are sending.

Code: Select all
$j.post('ss_script.php'{name:user_name}, function(data){})


data will be the echoed result.

so
Code: Select all
$j.post('ss_script.php'{name:user_name}, function(data){
if(data == 'success')
{
alert('Added Successfully');
}
else
{
alert(data);
}
})


In our server side script we will need to echo a result so it gets sent back to the jquery. If the query was successful then we simply echo 'success'. if not then we echo the error result:

Code: Select all
if(isset($_POST['name']))
{
mysql_query("INSERT INTO table (column) VALUES ('".$_POST['name']."')")or die(mysql_error())
echo 'success';
}
else
{
echo 'No Post Data';
}


And thats it. if you have any questions then please feel free to reply to this post.
Image
User avatar
doddsey_65
Premium Member
Premium Member
 
Posts: 1141
Joined: Tue Jun 30, 2009 10:36 am
Location: North East UK

Return to Web Programming

Who is online

Users browsing this forum: No registered users and 2 guests