06 April 2010

AJAX post with JQuery

JQuery allows us to pass info to the server and get back results without leaving the page. This comes in handy for example when we want to submit a form, authenticate users against a database, load photos etc. I mostly use it for when I want to communicate with a MySQL database.

Here is an example where I send an id to the server which queries a MySQL database and return back the user's name for me.

I have a div called 'loading' in my HTML form. Before passing information to the server, I want the user to get a message, tell him to wait (the time that the information is being fetched from the server). So, I display a message in the 'loading' div.

$("#loading").html('Please wait...');

I then get the value that I want to pass to the server from my form.

var id = $('#userid').val();

I then create a data string of all the variables that I want to send to the server. In this case I will only send an id to the server.

var dataString = 'id='+ id;

Now, we move on to the AJAX part.

$j.ajax({
type: "POST",
url: "components/com_etudes/assets/ajax/getData.php", data: dataString,
success: function(data) {
//Display a message $j("#messages").html(data).css("color","green"); 
} });

POST : The way we want to submit the data to the server. We can use POST or GET

URL: This is the path to the PHP script that will receive the data, processes it and return a response to the Client browser.

DATA: This is the data that we have (concatenation of all the variables that we have)

success: function(data)
: This means that on success (i.e. if the script has been executed on the server without error). 'data' is a variable that contains the result sent from the server.

You see that I used the variable 'data' and updated the HTML of a div called 'messages'. That is this div 'messages' will get as content whatever was returned from the server.

SERVER PART

The getData.php is simple.

header('Content-Type: text/html; charset=iso-8859-1');

//Database connection
include('db.php');

//POST Variables
$id  = $_POST['id'];
$msg = '';

//Get the user
$SQL = "SELECT * FROM users WHERE id = ".$id; //execute the query $result = mysql_query($SQL,$conn) or die(mysql_error());
$row = mysql_fetch_array($result);
echo $row['name'];


So we basically passed an id to the server which queried a MySQL database and responded back with the name of the user that corresponded to the id passed. Simple!


Stay tuned for some other tips coming soon.


No comments:

Post a Comment