How To Use Ajax in PHP With jQuery

0

In this tutorial, we will learn How to Use Ajax in Php with jQuery. Ajax is a web standard that works in the background to update parts of an HTML page without having to reload the entire page.

This is used for interactive web apps, such as Google Maps and Gmail. With Ajax functionality, you can take advantage of client-side interactivity without refreshing the entire page or adding new pages.

How To Use Ajax in PHP

jQuery is a JavaScript library that makes it easier to use Ajax. It has an Ajax method, .ajax(), that makes it easy to request data from a server and update parts of a page without having to reload the entire page.

To use Ajax in PHP with jQuery, you need to include the jQuery library in your PHP code. Then, you can use the .ajax() method to make Ajax requests.

What is Ajax?

Ajax is a web development technique that allows for the creation of dynamic, responsive web applications. It is a combination of technologies that makes it possible to request data from a server without having to reload the entire page.

Ajax has been around since the early 2000s, but it was not until recently that its potential began to be fully realized. With the release of jQuery, a JavaScript library that makes it easy to use Ajax, developers have been able to create web applications that are more user-friendly and efficient.

How to Use Ajax in PHP with jQuery

Are you looking for a way to add dynamic content to your web pages without having to reload the entire page? If so, then you may want to consider using Ajax.

Ajax is a technology that can be used to load content into a web page without having to refresh the page. In this article, we will show you how to use Ajax in PHP with jQuery.

We will also provide some examples so that you can see how Ajax can be used to improve the user experience on your website. So, what are you waiting for? Let’s get started!

I’ve shared each code that is used inside the project, you will easily understand it step by step.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/fonts.css">
    <title>Ajax Project with Php</title>
</head>
<body class="bg-dark">

<!--Navigation-->
<div class="container-fluid">
    <div class="row">
      <div class="col">
          <div class="card mt-5">
            <div class="card-title ml-5 my-2">
              <!--Registration Button--> 
              <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#Registration">Add New User </button>
            </div>
            <div class="card-body">
            <p id="delete-message" class="text-dark"></p>
              <div id="table"></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!--Registration Modal-->
    <div class="modal" id="Registration">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h3 class="text-dark">Registration Form</h3>
          </div>
          <div class="modal-body">
          <p id="message" class="text-dark"></p>
            <form>
              <input type="text" class="form-control my-2" placeholder="User Name" id="UserName">
              <input type="email" class="form-control my-2" placeholder="User Email" id="UserEmail">
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-success" id="btn_register">Register Now</button>
            <button type="button" class="btn btn-danger" data-dismiss="modal" id="btn_close">Close</button>
          </div>
        </div>
      </div>
    </div> 

    <script src="js/jquery.js"></script>
    <script src="js/bootstrap.js"></script>
    <script src="js/myjs.js"></script>
</body>
</html>

Once you used the above-mentioned code, then you need to add Bootstrap and jQuery files to your project. Once you do that, then you will be able to see the perfect results.

// Insert Record in the Database
function Insert_record()
{
   $(document).on('click','#btn_register',function()
   {
        var User = $('#UserName').val();
        var Email = $('#UserEmail').val();

        if(User == "" || Email=="")
        {
            $('#message').html('Please Fill in the Blanks ');
        }
        else
        {
            $.ajax(
                {
                    url : 'insert.php',
                    method: 'post',
                    data:{UName:User,UEmail:Email},
                    success: function(data)
                    {
                        $('#message').html(data);
                        $('#Registration').modal('show');
                        $('form').trigger('reset');
                        view_record();
                    }
                })
        }
        
   })

   $(document).on('click','#btn_close',function()
   {
       $('form').trigger('reset');
       $('#message').html('');
   })   
}

Once you do that, then you need to use Php to store the record inside the database here is the code of jQuery.

 // Insert Record Function
    function InsertRecord()
    {
        global $con;
        $UserName = $_POST['UName'];
        $UserEmail = $_POST['UEmail'];
        
        $query = " insert into user_record (UserName,UserEmail) values('$UserName','$UserEmail')";
        $result= mysqli_query($con,$query);

        if($result)
        {
            echo ' Your Record Has Been Saved in the Database';
        }
        else
        {
            echo ' Please Check Your Query ';
        }
    }

Above talked about all code representing the design type and inserting data within the database with the assistance of Bootstrap, jQuery, and Additionally Php MyAdmin.

It is best to prepare them as you want, in case you face any downside in arranging them, you want to watch the above video tutorial that lets you perceive the whole lot as needed.

When You complete insert data, then you want to show the information on the page, contained in the index.php. I’ve talked about desk div and assigned the ID, particularly desk.

So, I’ll use this ID to show the Database Report contained in the HTML Desk. It is advisable to comply with on under steps.

First of All, we have to work on a jQuery File to cross the information with the Php Web page, under this, I’ve talked about a jQuery easy code that’s serving to us to ship the request with the Php web page utilizing Ajax.

// Display Record
function view_record()
{
    $.ajax(
        {
            url: 'view.php',
            method: 'post',
            success: function(data)
            {
                data = $.parseJSON(data);
                if(data.status=='success')
                {
                    $('#table').html(data.html);
                }
            }
        })
}

I’ve talked about jQuery code, you must use the identical code to ship the request on the Php Web page, contained in the jQuery Code have a View.php web page.

I’ve used this web page if you wish to change that you are able to do that, however, you must make the identical web page in Php which is entered contained in the jQuery File.

// Display Data Function
    function display_record()
    {
        global $con;
        $value = "";
        $value = '<table class="table table-bordered">
                    <tr>
                        <td> User ID </td>
                        <td> User User </td>
                        <td> User Email</td>
                        <td> Edit </td>
                        <td> Delete </td>
                    </tr>';
        $query = "select * from user_record ";
        $result = mysqli_query($con,$query);
        
        while($row=mysqli_fetch_assoc($result))
        {
            $value.= ' <tr>
                            <td> '.$row['ID'].' </td>
                            <td> '.$row['UserName'].' </td>
                            <td> '.$row['UserEmail'].'</td>
                            <td> <button class="btn btn-success" id="btn_edit" data-id='.$row['ID'].'><span class="fa fa-edit"></span></button> </td>
                            <td> <button class="btn btn-danger" id="btn_delete" data-id1='.$row['ID'].'><span class="fa fa-trash"></span></button> </td>
                        </tr>';
        }
        $value.='</table>';
        echo json_encode(['status'=>'success','html'=>$value]);
    }

When you comply with the above-mentioned codes, then you possibly can insert the report into the database and likewise, you possibly can show the database report on the net web page.

Within the subsequent step, it’s essential to get the actual report from HTML Desk, contained in the HTML Desk I’ve included the Button Tags contained in the Button tag, I’ve talked about attributes, particularly the data-id contained in the data-id I’ve assigned database column worth particularly ID.

The ID is essential to get a specific report. So, it’s essential to use the identical factor to get the report from the desk. I’ve talked about under the jQuery Code that lets you get the actual report contained in the HTML Web page however, it’s essential to make a Modal.

So, The Very first thing it’s essential to embrace under talked code contained in the index.php web page, the under-code helps us to show the Modal, as soon as the modal has appeared, then we will get the Desk report contained in the Modal.

<!--Update Modal-->
     <div class="modal" id="update">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h3 class="text-dark">Update Form</h3>
          </div>
          <div class="modal-body">
          <p id="up-message" class="text-dark"></p>
            <form>
              <input type="hidden" class="form-control my-2" placeholder="User Email" id="Up_User_ID">
              <input type="text" class="form-control my-2" placeholder="User Name" id="Up_UserName">
              <input type="email" class="form-control my-2" placeholder="User Email" id="Up_UserEmail">
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-success" id="btn_update">Update Now</button>
            <button type="button" class="btn btn-danger" data-dismiss="modal" id="btn_close">Close</button>
          </div>
        </div>
      </div>
    </div>

That you must paste the code contained in the index.php web page, when you add that, then it is advisable to embody the below-mentioned jQuery Code.

The jQuery Code helps us to show the Modal and in addition, get a specific document contained in the Modal.

//Get Particular Record
function get_record()
{
    $(document).on('click','#btn_edit',function()
    {
        var ID = $(this).attr('data-id');
        $.ajax(
            {
                url: 'get_data.php',
                method: 'post',
                data:{UserID:ID},
                dataType: 'JSON',
                success: function(data)
                {
                   $('#Up_User_ID').val(data[0]);
                   $('#Up_UserName').val(data[1]);
                   $('#Up_UserEmail').val(data[2]);
                   $('#update').modal('show');
                   
                }
                
            })
    })
}

Lastly, it is advisable to use Php to get the actual file inside Modal, So, it is advisable to use the below-mentioned code. That helps us to show the actual file inside Modal.

// Get Particular Record
    function get_record()
    {
        global $con;
        $UserID = $_POST['UserID'];
        $query = "select * from user_record where ID='$UserID'";
        $result = mysqli_query($con,$query);

        while($row=mysqli_fetch_assoc($result))
        {
            $User_data = "";
            $User_data[0]=$row['ID'];
            $User_data[1]=$row['UserName'];
            $User_data[2]=$row['UserEmail'];
        }
        echo json_encode($User_data);
    }

When you show the actual report contained in the Modal, then it is possible for you to carry out the operation particularly Replace the File.

So, the Very first thing you might want to get is the worth from the Modal Contained in the Modal has entered textual content fields, you might want to use the below-mentioned jQuery code to get the report and ship Ajax request on the Php Web page.

// Update Record 
function update_record()
{
    
    $(document).on('click','#btn_update',function()
    {
        var UpdateID = $('#Up_User_ID').val();
        var UpdateUser = $('#Up_UserName').val();
        var UpdateEmail = $('#Up_UserEmail').val();

        if(UpdateUser=="" || UpdateEmail=="")
        {
            $('#up-message').html('please Fill in the Blanks');
            $('#update').modal('show');
        }
        else
        {
            $.ajax(
                {
                    url: 'update.php',
                    method: 'post',
                    data:{U_ID:UpdateID,U_User:UpdateUser,U_Email:UpdateEmail},
                    success: function(data)
                    {
                        $('#up-message').html(data);
                        $('#update').modal('show');
                        view_record();
                    }
                })
        }
        
    })
}

Then you might want to use Php to carry out the operation reminiscent of Replace report, under this, I’ve talked about the code that helps us to replace a report without refreshing a web page.

// Update Function
    function update_value()
    {
        global $con;
        $Update_ID = $_POST['U_ID'];
        $Update_User =$_POST['U_User'];
        $Update_Email = $_POST['U_Email'];

        $query = "update user_record set UserName='$Update_User', UserEmail='$Update_Email' where ID='$Update_ID '";
        $result = mysqli_query($con,$query);
        if($result)
        {
            echo ' Your Record Has Been Updated ';
        }
        else
        {
            echo ' Please Check Your Query ';
        }
    }

Lastly, we have to carry out the final operation similar to Delete the report, So, we have to work on that. First of All, you must embrace beneath point out HTML-based code in Index.php that assists us to show the Modal You want.

<!--Delete Modal-->
    <div class="modal" id="delete">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h3 class="text-dark">Delete Record</h3>
          </div>
          <div class="modal-body">
            <p> Do You Want to Delete the Record ?</p>
            <button type="button" class="btn btn-success" id="btn_delete_record">Delete Now</button>
            <button type="button" class="btn btn-danger" data-dismiss="modal" id="btn_close">Close</button>
          </div>
        </div>
      </div>
    </div>

Then we have to use jQuery to ship the request on the Php Web page and we have to get Id, I’ve talked about the ID inside the view.php web page.

You’ll be able to try Now, We have to goal the data-id1 attribute to get the actual report ID. As soon as we bought the actual report ID, then we will carry out the operation.

// Delete Function
function delete_record()
{
    $(document).on('click','#btn_delete',function()
    {
        var Delete_ID = $(this).attr('data-id1');
        $('#delete').modal('show');

        $(document).on('click','#btn_delete_record',function()
        {
            $.ajax(
                {
                    url: 'delete.php',
                    method: 'post',
                    data:{Del_ID:Delete_ID},
                    success: function(data)
                    {
                        $('#delete-message').html(data).hide(5000);
                        view_record();
                    }
                })
        })
    })
}

Lastly, We have to use Php to Delete data, I’ve talked about the Php code, it’s essential to paste it along with your PHP file.

function delete_record()
    {
        global $con;
        $Del_Id = $_POST['Del_ID'];
        $query = "delete from user_record where ID='$Del_Id' ";
        $result = mysqli_query($con,$query);

        if($result)
        {
            echo ' Your Record Has Been Delete ';
        }
        else
        {
            echo ' Please Check Your Query ';
        }
    }

So, We’ve seen the usage of Ajax to perform operations such as insert, update, delete, and view records hope you’ve learned it. However, I’ve made another project using Php ajax, you can also watch the tutorial below.

Letter Counter Application in Php with Ajax

Letter Counter Application in Php with Ajax, in this project you will learn How to use Ajax in Php to count the letters inside the page without refreshing a page.

Autocomplete Search Box in Php MySQL Using Ajax

Here is another very helpful and useful project that is developed in Php MySQL and also Ajax. In this project, you will learn How to use Php to get data from a database and display it on the page. When you will search the data from the database you will see auto-complete data. So, hope this project is helpful and beneficial for you.

COVID 19 Tracking Application in Php with Ajax

COVID 19 Tracking Application in Php with Ajax, inside the project, you will learn How to use Php and Ajax to get the data from another website and display the data inside your website without refreshing a page. So, in this project, you will a lot of new things that are helpful and beneficial for you.

Why would I need to use Ajax?

If you need to communicate with a server without reloading the page, Ajax is your best bet. It allows you to send and receive data asynchronously, meaning that you can do other things while the server is processing your request.

Ajax is especially useful for web applications that need to be interactive and responsive. For example, if you were creating a chat application, you would want to use Ajax so that new messages would appear in real time without the user having to refresh the page.

You May Also Like:

jQuery makes working with Ajax very simple. In this tutorial, we’ll show you how to use jQuery to make Ajax requests in PHP.

Conclusion

So, We have discussed How to Use Ajax in Php with jQuery with a couple of examples. Ajax is a powerful tool that can make your PHP applications more responsive and interactive. By using jQuery to handle the Ajax requests, you can keep your code clean and organized.

In this article, we’ve shown you how to use Ajax in PHP with jQuery. We hope you find this information helpful and that it makes working with Ajax easier for you.

Previous articleSimple Website Using HTML and CSS with Source code
Next articleVehicle Booking System in PHP With Source Code
I'm Programmer, Digital Marketer, and Blogger, I have been working on the web for 04 years. Basically, I have been sharing personal expertise on my website.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.