Jquery Ajax get() and post()

Uncategorized

Using jquery ajax get() and post() method we can send HTTP request and get the response without loading the page.

get()

This method loads data from server.

syntax:

$(selector).get(url,data,callback);

parameter:

  • url – specifies the URL to which the request is sent.
  • data – object send to server along with the request.Optional field.
  • callback – function execute when the data loads correctly.

Here’s an example of the get() method:


<html>
   
     <head>

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

</head>

    <body>

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

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

       <button>SUBMIT</button>

<script type="text/javascript">

       $(document).ready(function(){

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

               $.get(

                  'result.php',

                  function(data,status){

                        $('#div1').html('data:'+data+'\nstatus:'+status);

                  });

         });
</script>

    </body>

</html>

result.php page contains

<html>
   <head>
   </head>
   <body>
        <p>Jquery Ajax Using GET() method</p>
   </body>
</html>
post()
$.post() method requests data from the server using an HTTP POST request.
syntax:
$.post(url,data,callback)

parameter:

  • url – specifies the URL to which the request is sent.
  • data – object send to server along with the request.
  • callback – function execute when the data loads correctly.
<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(){
             $.post(
                'post_result.php',
                { value: " post() method" },
                  function(data,status){
                     $('#div1').text("data is :"+data+"\t\nstatus is:"+status);
            });
        });
     });
</script>
    </body>
</html>

post_result.php page contains

<?php  echo "Jquery Ajax  ".$_POST['value'];   ?>

Leave a Reply

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