Jquery Ajax-load()

Codeigniter PHP YII2

Ajax technique is used to load data from server without loading the page. Jquery is a javascript library which designed to simplify the client-side scripting of HTML

Load data

use load() method to load data from  server and insert into an element of a static or dynamic page using Jquery ajax technique.

Syntax:

$(selector).load(URL,data,callback);

parameters:-

  • URL -represents the URL you wish to load
  • data – represents key/value pair send along with the request
  • callback – represents the name of the function

data and callback fields are optional.

Example:

Create a new php page called jq_load.php and write following code,

<html>   

   <head>

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

   </head>

   <body>

      <p id="para">Jquery</p>

      <div id="div1"></div>

      <button>SUBMIT</button>

<script type="text/javascript">

   $(document).ready(function(){

       $('button').click(function(){

            $('#para').load("index.php");

       });

   });

</script>

  </body>

</html>

Create an index.php page as follows,

<!DOCTYPE html><html lang="en">

   <head>

      <meta charset="utf-8">

      <title>Jquery Ajax</title>

   </head>

   <body>

      <div id="container">

        <h1>Jquery Ajax load()</h1>

        <div id="body">

              <p>Paragraph</p>

              <p>Paragraph</p>

        </div>

</div>

   </body>

</html>

load() method loads all the contents from index.html to jq_load.php without refreshing the page.

We can load contents from specific elements inside index.html. So load content from index.html page with element having id=body.

$('#para').load("index.html #body");

the above code retrieves the content of index.html, with an element having id=body and all other contents are discarded.

callback represents the function, which runs after the load() method works.

Example

$('#para').load("index.html",function(response,status,xhr){ });
parameters :
  • response – specifies the result when the jquery ajax call succeeds.
  • status – specifies the status of the call.
  • xhr – specifies the XmlHttpResponse object.
$('#para').load("index.html",function(response,status,xhr){

alert('Data:'+response+'\nStatus:'+status);

});

Leave a Reply

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