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


$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">
city_id = $('#city').val();

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

<title>Simple Jquery Ajax Tutorial by</title>
<script src=""></script>
<script type="text/javascript">
city_id = $('#city').val();

<h3><a href="">Easy jQuery Ajax Call Script -</a></h3>
<select name="city" id="city">
<option value="1">Madurai</option>
<option value="2">Chennai</option>
<option value="3">Bangalore</option>
<div id="result">


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

Download   Demo


Add a Comment

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