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

About the Author

agurchand

Software Engineer, Blogger etc., Visit my Youtube channel - <a href="http://www.youtube.com/agurchand">Click Here</a>

12 thoughts on “Very Simple jQuery and PHP Ajax Request – Ready to use code

    • Author gravatar

      thenk u for basic tuttorials. it worked this time

    • Author gravatar

      thank you this is very handy

    • Author gravatar

      hi can you tell me how I might amend this script to work with dependent dropdowns?

      • Author gravatar

        Its simple,
        Lets say, you have another dropdown for state
        <select id="state">
        <option>blah</option>
        </select>

        so you have to write a jquery function like the below

        $('#state').change(function(){
        //similar to city code
        });

    • Author gravatar

      Very nice guide indeed! I’m working on a page that will show different squad in a table, and I want those squads to be selected from a drop down menu on that same page. So if I would select another squad from the drop down menu, the table will automatically change with the members that are in that squad. I didn’t succeed yet, even after reading your tutorial, so if you could help me a bit, that would be amazing!

      I’ll post my code below:

      Html file:

      Test

      $(document).ready(function(){
      $(‘#squad’).change(function(){
      squad_id = $(‘#squad’).val();
      $.post(‘showSquads.php’,{squad:squad_id},function(res){
      $(“#result”).html(res);
      });

      });
      });

      Select a Squad

      Php file:

      <?php
      $id = $_POST['squad'];

      $con = mysql_connect("localhost","username","password");
      if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }

      mysql_select_db("database", $con);

      $sql = "SELECT * FROM squad_names"; WHERE squad_id = $id ";
      $result = mysql_query($sql);

      echo "Select a Squad”;
      while($row = mysql_fetch_array($result))
      {
      echo “” . $row[‘squad_name’] . “”;

      }

      mysql_close($con);

      ?>

      Any help would be greatly appreciated!

      • Author gravatar

        I didn’t get you exactly. what I understood is, you want to show one more dropdown with the values from squad table.. here is the code

        <?php
        $id = $_POST[‘squad’];

        $con = mysql_connect("localhost","username","password");
        if (!$con)
        {
        die(‘Could not connect: ‘ . mysql_error());
        }

        mysql_select_db("database", $con);

        $sql = "SELECT * FROM squad_names WHERE squad_id = $id ";
        $result = mysql_query($sql);

        echo "<select name=’newdropdown’>";
        while($row = mysql_fetch_array($result))
        {
        echo "<option value=’$row[squad_name];’>".$row[‘squad_name’]."</option>";

        }
        echo "</select>";
        mysql_close($con);

        ?>

        • Author gravatar

          Thanks a lot for your help, I really appreciate that. I’m sorry that I wasn’t clear before, so I’ll try explaining it again.

          I want to have 1 drop down menu, with data from a database. This database shows the squad id’s & squad names, which will show up in the drop down menu.

          After selecting one of those squads from the drop down menu, I want to have a table show up on the same page, that will display the members from the squad that has been selected. These members are found in a separate MySql table.

          This should be possible using jQuery and Ajax, but it didn’t work for me so far.

          • Author gravatar

            You’re on the right track, in the first dropdown instead of selecting * in your SQL statement (which would select ALL records) you need to use DISTINCT in your statement:
            $sql = “SELECT DISTINCT FROM squad_names WHERE squad_id = $id “;

            Hope that helps

            • Author gravatar

              Thank you, that did help! I got it all working now, besides one last thing: After the table with members is shown, I have several check boxes, if I check one of those boxes points will be added. However, after pressing the submit button it does not add the points and refreshes the page, showing the first drop down menu again. Is there anything I’m missing here? Or is there any way to “remember” the squad chosen from the drop down menu until a new session starts?

    • Author gravatar
    • Author gravatar

      This is very handy example but my scenario is little bit different.

      I want to retrieve data from my localhost server (java) using Ajax/JQuery to my JavaScript side. I am so confused how to start with it.
      if you can show me some example, that will be really grate..Thank you

    • Author gravatar

      Hi to every one, because I am in fact keen of reading this web site’s post
      to be updated daily. It contains good data.

Leave a Reply

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