Very Simple jQuery and PHP Ajax Request – Ready to use code

Are you wondering how to do an Ajax call through jQuery Script?.

Here I’m going to teach you a very very simple way of writing a jQuery script to fetch the records from the database.

Download the script at the bottom of this post

I’m taking PHP and Jquery here. (you can use other server side script too instead of PHP).

Lets start with the PHP Script. The below code is to fetch the records from a particular table.

1. test.php


<?php

$id = $_POST['city'];
//connect to the database
$con = mysql_connect( 'localhost', 'root', '' );
$db = mysql_select_db( 'testdb' );

//find the record
$sql = " select * from testtable where city_id = $id ";
$query = mysql_query($sql);

//fetch the results and display in a html table
echo "<table border='1'><tr><th>ID</th><th>Name</th><th>City</th></tr>";
while( $row = mysql_fetch_assoc( $query ) ){
echo "<tr><td>$row[id]</td><td>$row[fullname]</td><td>$row[city]</td>";
}
echo "</table>";

?>

The above code will fetch the result from the ‘testtable’ and print the results if we pass the $id.

Now, lets move to the jquery part. Look at the below code, simple isn’t it?


<script type="text/javascript">
$(document).ready(function(){
$('#city').change(function(){
city_id = $('#city').val();
$.post('test.php',{city:city_id},function(res){
$("#result").html(res);
});
});
});
</script>

I have used post method in the above script:

$.post() is the ajax function. ( Instead of post you can use $.get() method also)

look at the line no. 4 {city:city_id} , city is the variable we are going to pass to the php file.
You can use any number of variable likewise {city: city_id, state:state_id, name:fullname}

Here is the entire html file:

1. index.html


<html>
<head>
<title>Simple Jquery Ajax Tutorial by http://blog.theonlytutorials.com</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#city').change(function(){
city_id = $('#city').val();
$.post('test.php',{city:city_id},function(res){
$("#result").html(res);
});

});
});
</script>
</head>
<body>
<h3><a href="http://blog.theonlytutorials.com/very-simple-jquery-and-php-ajax-request-ready-to-use-code/">Easy jQuery Ajax Call Script - Theonlytutorials.com</a></h3>
<select name="city" id="city">
<option value="1">Madurai</option>
<option value="2">Chennai</option>
<option value="3">Bangalore</option>
</select>
<div id="result">
</div>
</body>
</html>

 

You can see the demo or can download the script it use  it on your project!

Download   Demo

12 Comments

Add a Comment

Your email address will not be published. Required fields are marked *