How to use jQuery.ajax() api with PHP?

How to use jQuery.ajax() api with PHP?

AJAX, stands for Asynchronous JavaScript and XML. It’s just a way to have the client requested data from the server without having to reload the entire page.

jQuery has a number of built-in AJAX functions and $.ajax() or jQuery.ajax() is one of them.

Most of the time, we’ll use one or two of them, but there is one method that rules them all. It’s the generic version of the call and it’s simply called $.ajax().

$.ajax() is quite powerful ajax function because it enables us to pass parameters too to the PHP file to get the filtered result.

For Example:
HTML Code:
Copy the following code and paste in your .html file.

<button id="homeBtn">HOME</button>
<button id="aboutBtn">ABOUT US</button>
<button id="coursesBtn">COURSES</button>
<span id='loadc'></span>

Paste the following JavaScript link in the head of your .html file.

<script  type="text/javascript" src="https://code.jquery.com/jquery-latest.js"></script>

Put the following code before the closing body of your .html file or create a separate .js file and then link that file to your.html file.

<script type="text/javascript">
$('#homeBtn').click(loadHomeContent('myhome.php'));
$('#aboutBtn').click(loadHomeContent('about.php'));
$('#coursesBtn').click(loadHomeContent('courses.php'));

function loadHomeContent(fileurl){
        $.ajax({
        url:fileurl,
        cache: false,
        success: function(html){
            $("#loadc").html(html);
          }
    });
}
</script>

Create 3 PHP Pages with the name myhome.php, about.php, and courses.php consecutively.

//myhome.php

<?php
    echo "Home page content.";
?>

//about.php

<?
    echo "About us page content.";
?>

//courses.php

<?php
    echo "Our Courses page content.";
?>

Note: keep all the above 3 files in the same folder where your HTML file resides.

Test your file and click on each of buttons. It will show the data coming from all the associated files without refreshing the page.

Summary: Learning Ajax is not a big deal while working in it is like a herculian task. You need to learn JavaScript and jQuery with HTML and CSS perfectly. You can use XML, JSON, MySQL or any other database to fetch the content using Ajax.

Leave a Reply

You must be logged in to post a comment.

Copy link