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 scripts too instead of PHP).

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

1. test.php

<?php

$mysqli = new mysqli("localhost","root","","mydb");

// Check connection
if ($mysqli->connect_errno) {
  echo "Failed to connect: " . $mysqli->connect_error;
  exit();
}

//fetch the results and display in a html table
echo "<table border='1'><tr><th>ID</th><th>User Name</th><th>City</th></tr>";
// query a table
$city = $_POST['city'];
if ($city != '') {
    if ($result = $mysqli->query("SELECT * FROM users where city='$city'")) {
        while ($row = $result->fetch_assoc() ){
            echo "<tr><td>$row[user_id]</td><td>$row[fullname]</td><td>$row[city]</td>";
        }
        $result -> free_result();
    }
    echo "</table>";
}
$mysqli->close();

?>

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

Now, let’s 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 the POST method in the above script:

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

look at line no. 4 {city:city_id}, the 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 https://blog.theonlytutorials.com</title>
<script src="https://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="https://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="3">Bangalore</option>
</select>
<div id="result">
</div>
</body>
</html>

 

You can see the demo or can download the above script.

demo

download

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

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

    1. 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
      });

  2. 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!

    1. 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);

      ?>

      1. 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.

        1. 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

          1. 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?

  3. 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

Leave a Reply

Theme: Overlay by Kaira
Agurchand