Jquery post request does not receive data. Sending POST requests via JavaScript. PHP example of the json_decode function

For quite a long time, many sites have dynamic pages, that is, they are updated without reloading. This is achieved by calling the server via JavaScript, in most cases, POST and GET requests. And almost always such sites use Ajax for this. And not everyone knows (unfortunately) that Ajax is not a separate language, but just a JavaScript library. Conclusion: Ajax is just a convenient way to send POST requests, but all this can be done without its help. That's how to send POST requests via JavaScript without Ajax, I'll cover in this article.

We will now solve a classic problem - the summation of two numbers specified by the user. That is, you and I count 2 numbers from text fields, send them to the server, receive an answer and display them on the page. And all this without reloading the page.

Let's start with something simple: writing PHP code:

Everything here is elementary, so I won’t even comment. Now comes the more difficult part - the client side:


/* This function creates a cross-browser XMLHTTP object */
function getXmlHttp() (
var xmlhttp;
try (
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
) catch (e) (
try (
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
) catch (E) (
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!="undefined") (
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function summa() (
var a = document.getElementById("a").value; // Read the value of a
var b = document.getElementById("b").value; // Read the value of b
var xmlhttp = getXmlHttp(); // Create an XMLHTTP object
xmlhttp.open("POST", "test.php", true); // Open an asynchronous connection
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Send encoding
xmlhttp.send("a=" + encodeURIComponent(a) + "&b=" + encodeURIComponent(b)); // Send a POST request
xmlhttp.onreadystatechange = function() ( // Waiting for a response from the server
if (xmlhttp.readyState == 4) ( // Response arrived
if(xmlhttp.status == 200) ( // Server returned code 200 (which is good)
document.getElementById("summa").innerHTML = xmlhttp.responseText; // Print the server response
}
}
};
}









The amount is:


I will not comment on the HTML code, since it is completely transparent. But I will add a little to JavaScript, despite the detailed comments. First, the getXmlHttp() function is generic. You can safely copy it into your scripts. Its task is to return such XMLHTTP so that it works in any browser. Because the most popular option is new XMLHttpRequest() , however, it doesn't work in IE6 for example. Other options are also not universal, so here we simply select a working option for any browser.

I also wrote in the comments about “asynchronous work”. There is also a synchronous option. The only difference is that in synchronous mode, until a response is received from the server, the browser will not work, it will simply hang. It’s hard for me to come up with a task where this is necessary, so I immediately wrote an asynchronous version. It works like this: we send a request and wait for a response, but the browser does not hang. And when the response arrives (xmlhttp.readyState == 4 ), we immediately process the response. This is the asynchronous version of work, it is a little more complicated, but it is the only one that should be used (except for very rare cases).

This is how POST requests are sent via JavaScript. As you can see, we didn’t need Ajax at all. And I strongly recommend that if you only have a couple of requests for the entire site, then don’t even think about using this heavy-duty library, but use the material in this article.

GET request

A GET or POST request is sent through an XMLHttpRequest object (also called XHR for short).

// execute the code when the response from the GET request arrives // code when the request is successful // Sending a GET request ajax.open("GET" , "/handler.php" ); ajax.setRequestHeader("X-Requested-With" , "XMLHttpRequest" ); ajax.send();

It's worth paying attention to the setRequestHeader() method. This method tells the server that an Ajax request has been sent. Many frameworks, such as jQuery, set this header by default. If you do not set this header, the server may not detect the Ajax request and return an error.

You can only send a GET or POST request on the site's current domain (due to the domain restriction rule, also called the "Same Origin Policy").

The open() method can also take a third parameter, false , which makes requests synchronous (that is, the code stops executing until a response from the server arrives). This method is considered not recommended for use, because may slow down JavaScript. The Chrome browser also displays a warning in the console when this option is used.

POST request

First you need to specify what data you want to send:

// Old browsers var params = "lang=JavaScript&framework=jQuery" ; // Modern browsers var params = new FormData(); params.append("lang" , "JavaScript" ); params.append("framework" , "jQuery" );

The FormData() object is supported by modern browsers (IE support since IE 10).

You can also pass a form element to FormData() whose fields will be passed in the POST request.

var params = new FormData(document .getElementById("form-name" )); // 1st method var params = new FormData(document .forms["form-name" ]); // 2nd method

The created parameters can be passed through the send() method.

var ajax = new XMLHttpRequest(); // execute the code when the response from the POST request arrives ajax.onreadystatechange = function () ( if (ajax.readyState == 4 ) ( if (ajax.status == 200 || ajax.status == 304 ) ( // code for a successful request ajax.response; // server response ) else ( // code for error ) ) ) // Sending a POST request ajax.open("POST " , "/ajax-handler.php" ); ajax.setRequestHeader("X-Requested-With" , "XMLHttpRequest" ); ajax.send(params); Please enable JavaScript to view the jQuery AJAX Definition and Application

The jQuery $.post() function allows you to download data from the server using an HTTP request using the POST method. To download data using HTTP request method GET you can use the jQuery $.get() function.

Please note that the $.post() function is a shortened version of the $.ajax() function with the following parameters:

$.ajax(( type : "POST " // HTTP method used for the request url : "url ", // a string containing the URL to which the request is sent data : data, // data that will be sent to the server success : success , // callback function that is called if the AJAX request is completed successfully dataType : "dataType " // the data type that you expect to receive from the server ) );

Method GET Unlike POST when submitting the form, passes the collected information as part of the URL:

Url?name=value&name=value // GET method uses name = value pairs

When sending data using the method POST the data is transmitted in such a way that the user no longer sees the data sent to the form handler (adds form data in the body of the http request, which is not displayed in the URL).

Pay attention to some nuances when working with HTTP methods GET And POST:

  • Method GET limits the amount of information transmitted in the URL (about 3000 characters), the method POST has no such restrictions.
  • Never use the method GET, if you need to transfer sensitive data (for example, the user's password, since it will be transferred in the URL string - in clear text).
  • The page generated by the method GET, you can mark it with a bookmark (the page address will always be unique), and the page generated by the method POST This is not possible, since the page address does not change (no data is transmitted in the URL).
  • Please note that using the method GET You can transfer data not through a form, but through the page URL.
jQuery syntax: 1.0 syntax: $.post( url, data, success, dataType); url- String data- PlainObject , or String success-Function(PlainObject data,String textStatus,jqXHR jqXHR) dataType- String Syntax 1.12/2.2: $.post(( settings) ); // request parameters are passed in the object settings-PlainObject

Pages loaded by the $.post() function are never cached, which is why the values ​​of the cache (determines whether pages will be cached, defaults to true ) and ifModified (checks the Last-Modified header fields, defaults to false ) parameters of the jQuery .ajaxSetup() function (sets default values ​​for future requests AJAX) will not affect these queries.

Added in jQuery 1.0 Parameter values Parameter Description
url A line containing URL address to which it is sent AJAX request. Required parameter.
data An object or string that will be sent to the server along with AJAX request.
success A callback function that is called if AJAX the request will complete successfully. Optional parameter.
The function accepts the following parameters:
  • data- data returned from the server.
  • textStatus- a string describing the status of the request.
  • jqXHR- jqXHR object (up to version jQuery 1.4.x XMLHttpRequest object).
dataType Defines the type of data you expect to receive from the server. If the data type is not specified, then jQuery will try to determine it based on the MIME type from the response ( XML type MIME will result in XML, as of jQuery 1.4 json will give an object JavaScript, script will execute the script and everything else will be returned as a string). Optional parameter.

Available types (the result is passed as the first argument to the success callback function):

  • "xml" - returns XML document that can be rendered using jQuery.
  • "html" - returns HTML as plain text, tags will be processed and executed once inserted into the document object model ( DOM).
  • "script" - evaluates the response as JavaScript and returns it as plain text. Disables caching by adding the _= parameter to the query string, even if the cache parameter is true . This will turn the method POST V GET for cross-domain requests.
  • "json" - evaluates the response as JSON and returns an object JavaScript. Cross-domain "json" requests are converted to "jsonp", if jsonp is not specified in the request parameters: false . Data JSON are parsed in a strict order and must comply with the generally accepted format, any incorrect JSON is rejected and an error is thrown. As of jQuery 1.9, an empty response is not accepted; the server must return NULL or () as a response.
  • "jsonp" - loads data in the format JSON, using the download format JSONP. Adds an additional parameter "?callback=? " to the end URL addresses for specifying the name of the handler function. Disables caching by adding the _= parameter to URL address, even if the cache parameter is true .
  • "text" is a regular text string.
  • multiple values ​​- values ​​are separated by a space. Since version 1.5, jQuery can convert the data type that is received in the Content-Type of the header to the data type that you require. For example, if you want a text response to be interpreted as XML, use "text XML" for that data type. You can also make a JSONP request, receive it as text and interpret it as XML: "jsonp text XML" . The following line will do the same: "jsonp XML" , jQuery will try to convert from JSONP V XML, after an unsuccessful attempt will try to convert JSONP into the text, and then from the text into XML.
Example of use Example of using jQuery function $.post() $(document).ready(function ()( $("form ").submit(function ()( var formData = $(this ).serialize(); // create a variable that contains an encoded set of form elements as a string $.post("user.php ", formData,function ( data) ( // transfer and download data from the server using an HTTP request using the POST method $("div ").html( data); // insert data received from the server into the element ) ) ) ); ) );

In this example we bind JavaScript"submit" event handler (form submission handler), which is triggered at the moment the form is submitted (in our case, filled out) when an element with the submit type is clicked (a button for submitting the form).

Additionally, we create a variable that contains an encoded set of form elements as a string - the result of running the .serialize() method. After that, using the jQuery $.post() function, we execute an asynchronous AJAX request with the following parameters:

  • url is the file we are accessing ("user.php"), it contains the following PHP code: Result ("a":1,"b":2,"c":3,"d":4,"e ":5) PHP example of the json_decode function $json = "("a":1,"b":2)"; var_dump(json_decode($json, true)); $arr = json_decode($json, true); echo "
    ".$arr["a"]. "
    ".$arr["b"]. "
    "; Result array(5) ( ["a"] => int(1) ["b"] => int(2) ) 1 2 Example of an Ajax request using the POST method

    What do we do:
    We check the correctness of the data sent (via an AJAX POST request) (the data is entered by the user). If the data is correct, we display a message. Otherwise, we add red highlighting to the fields. Everything works asynchronously, that is, without reloading the page. You can use this principle, for example, to create a comment system that inserts comments into a database.


    jQuery $(document).ready(function())( var working = false; /* This flag prevents multiple comments from being submitted: */ $("form").submit(function(e)( e.preventDefault(); if( working) return false; working = true; $("#submit").val("Wait.."); $(".error").removeClass("error"); $.post("submit.php" ,$(this).serialize(),function(msg)( /* Send the form values ​​to submit.php: */ working = false; $("#submit").val("Submit"); if(msg. status) // If the data is correct, add a message ( console.log(msg.status); $(msg.html).hide().insertBefore("form").slideDown(); ) else ( // If there are errors , loop through the object // msg.errors and display them on the page $.each(msg.errors,function(k,v)( $("#"+k).addClass("error"); //alert( k); )); ) ),"json"); )); )); HTML Enter a number Enter email PHP // accept data received via ajax $arr = $_POST; $arr = $_POST; if(filter_var($arr, FILTER_VALIDATE_EMAIL) && filter_var($arr, FILTER_VALIDATE_INT)) ( echo json_encode(array("status"=>1,"html"=>"Thank you, your data is accurate")); // information returned server ) else ( if(filter_var($arr, FILTER_VALIDATE_EMAIL) == false) ( $errors["email"] = "Please enter a name."; ) if(filter_var($arr, FILTER_VALIDATE_INT) == false) ( $ errors["intt"] = "Please enter a name."; ) $arr = $errors; /* Display error messages */ echo "("status":0,"errors":".json_encode($arr) ")"; )

    JQuery is a javascript library whose goal is to "write less, do more." jQuery is easy to connect to your site and start using. jQuery makes it much easier to use javascript on your site.

    jQuery eliminates a whole lot of lines of javascript code, and allows you to implement this whole lot of lines with just one method.

    What is AJAX?

    AJAX is asynchronous (i.e., the browser can do whatever it wants after sending a request, such as showing a message waiting for a response, scrolling the page, etc.) JavaScript and XML. It is used to create dynamic and fast web pages. AJAX allows us to update part of a web page without reloading the entire page.

    What about jQuery and AJAX?

    The combination of jQuery and AJAX provides powerful functionality. With jquery and ajax, you can make a request and receive information in a variety of formats, including XML, HTML, and even plain text. You can use the JSON format to exchange data. We can use the data received via ajax request in our html page.

    jQuery makes the existing browser Ajax API more powerful and easier to use. Making ajax calls the normal way using javascript is a bit tricky: since you have to consider that different browsers require different approaches to creating the XMLHttpRequest object. Additionally, submitting data from forms, for example, becomes more difficult if you use regular javascript for the ajax call.

    jQuery provides simple and powerful functionality that extends javascript's AJAX methods and provides a more flexible approach.

    In this short article I will show you how to use jQuery and AJAX in a simple php form. Let's get started... To use jQuery and AJAX we will need two files, the first file will contain the html/php code through which the ajax request will be made. In the second file we will process the ajax request and return the result to the first page.

    Step 1: Create a school.php file and paste the following code into it:

    In the above code we are getting the student name and number and using jquery and ajax we are sending them to details.php.

    function getdetails())( var name = $("#name").val(); var rno = $("#rno").val(); $.ajax(( type: "POST", url: "details .php", data: (fname:name, id:rno) )).done(function(result) ( $("#msg").html(" Address of Roll no " +rno +" is "+result) ; )); )

    Your Name:
    Roll Number:

    Step 2: Create details.php and place the following code in it:

    In the above code, we get the student's address using the sequence number and his name.

    For this example, you will need to create a school database and a students table. The student table contains fields with names, sequence numbers, and addresses.

    I hope you find this article helpful.