jQuery $.post() method का use Asynchronous HTTP POST Request send करने के लिए किया जाता। POST request के साथ आप GET method की comparison में ज्यादा data submit कर सकते हैं।

Understanding Asynchronous

हालाँकि request complete होने में time लगता है , इसलिए जब तक request complete होती है तब तक rest of code run हो जाता है।

jQuery $.post() Syntax

$.post(url, [data], [callback], [type]);

यह basically 4 parameters accept करता है।

URL : जिस URL पर request send करनी है।

data : जो हमें submit करना है , जो की JavaScript Object (key : value) Form में होता है।

type : इसमें define करते है , कि server किस type का data response कर रहा है। हालाँकि यह Optional होता है।

callback function तब run होता है , जब request complete हो जाती है और response ready होता है। ये request response और status return करता है।

jQuery $.post() Example

File : jquery_pot.html

CopyFullscreenClose Fullscreen
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>jQuery $.post() Method </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>	
  <body>
  	<p class="target_elm">Click bellow buttons button to see result.</p>
    <p>
      <button class="send_request">Send Request</button>
    </p>
    <script type="text/javascript">
      window.onload = function(){
        /*check if jquery working*/
        if(window.jQuery)
        {
          $(".send_request").click(function(event) {
            /*send request with data*/
            let data = {
              name : 'Rahul Kumar Rajput',
              age : 45,
            };
            $.post('handle_request.php', data , function(response, textStatus, xhr)
            {
              $('.target_elm').html(response);
            });
          });
        }
      }
  	</script>
  </body>
</html>

File : handle_request.php

Copy Fullscreen Close Fullscreen
<?php
	echo '<pre>Request Data : ';
	print_r($_POST);
	echo '</pre>';
?>

इसके अलावा आप done() और fail() callback functions भी post method में attach करके code को और efficient बना सकते हैं।

$.post('handle_request.php', {} , function(response, textStatus, xhr)
{
   console.log('Reponse ', response);
})
.done(function(){
   console.log('Request completed');
})
.fail(function(error){
   console.log('Error : ', error);
});

Note
Internally $.post() method , $.ajax() method use करता है , जिसमे कि सिर्फ type POST option set होता है ।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers