Basic Ajax call with jquery

After i have learnt HTML and css i understood that i must learn also javascript. Well, i hated every minute and did whatever i could to not use it. Since i new flash and actionscript i preferred it on JS, and when i had no choice i preferred to make Dreanweaver write JS for me. I guess you can tell how much i disliked JS.

At some point i discovered Jquery which is a javascript library that facilitate the writing of javascript. The thing with Jquery is that if you know css and HTML you can get it really fast.

In this shot tutorial we will use jquery to make an Ajax call. In short terms, ajax is the ability to make an action without refreshing the web page so the user have a more immediate experience of the web page.

In our example is a login form that when the user click on the submit button data is sent Asynchronous to a PHP file that process it and send the results. All that with no page refresh.

Since i imagine that you can write a form we will go strait to the jquery code:

$("#loginform input#submit").click(function() {



	var username = $("input#username").val();

	var password = $("input#password").val();

	//alert (username);







        return false;



The above code say: on click store the username and password variables. Then there is an if statement: if there are no errors send the variables to a function that makes the Ajax call.

Lest see this function:

function sendLoginInfo(username,password)






		"username" : username,

		"password" : password




			if(result != true){

				//display errors;



				//display success







The code above is fairly simple:

set the path to the PHP file that will process the information
the result is what will come back from the PHP file
if there are errors display them and if no errors  display the success
the last element tell that we are expecting that our parameters will be in Json format.
And that is it. From the point of view of jquery we have finished.

One thing to take notice: we are using POST and not GET. Jquery has a GET version and there is the most flexible option: $.ajax.

Since we are dealing here with jquery i do not give the code for the php file, but in principle this is very simple:

store the post values that were sent
create a query to the database
whatever the result will be we will output  a message. that messages or content will be in the result of the jquery we saw
That is it. Hope it was clear and helpful.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.