Web Design Ohio | Web Development Ohio | Website Design Ohio | Graphic Design Ohio | Custom CRM | Joomla Web Design

Web Design and Development

We deliver the cutest, fastest, and most optimized website development in Ohio. All our customers are enthusiastic about what we've achieved so far. Find out why!

Read More
A simple jQuery and PHP Ajax Request Comment Icon
Blog - Web Design Ohio Journal
Written by Daniel Gheorghe
Saturday, 04 February 2012

Ajax is a very nice tool for web developers that helps you interact with the visitor without reloading the page. Searching the internet you will find various Ajax code samples that are simply to complicated and to specific. Today I will show you a simple Ajax script that can be very easily customized and adapted to your needs. Also, I will post comments that will better explain what the code does and how it can be tweaked.

jQuery(document).ready(function() {
//you should replace submit with any selector that you use
jQuery('#submit').click( function() {
//then we build the data that will be submitted through the form ... I will call these variables X and Y
var x = jQuery('input[name="the name of the input"]').val();
var y = jQuery('input[name="the name of the other input"]').val();
//let's concatenate the data:
var data = 'x=' + x + '&y=' + y;
jQuery.ajax({
//the path to the php file that handles the data
url: "dir/dir/file.php",
//I always use post, but get also works
type: "POST",
// the data that we built earlier
data: data,
// no caching thanks but this is a simple form
cache: false,
//this means that if everything goes well, the PHP file will send back the html it echoes. and if the html is '0' it means that something is wrong and i like to give codes to differentiate between error messages. for example: 0-wrong email address 1-another error etc
success: function (html) {
if (html!=='0') {
//we say thank you because it's polite and the we can append the html... or do whatever we like with the returned html
alert('Thank you!');
}
else {
alert('An error has occured');
}
}
});
//this is important if you don't use this the form will be submitted using normal POST:
return false;
});
});

I hope this is very clear for all you guys. Now all you have to do is create a php file that will handle the data sent by this jQuery script. This can be anything from form validation to database queries and so on. Thank you again for reading this and I hope this will help all Ohio web developers out there build a better web.

 
Share on Myspace