Post request returns the handler page. Sending POST requests via JavaScript

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

jQuery eliminates a whole bunch of javascript lines of code, and lets you implement that bunch of lines with just one method.

What is AJAX?

AJAX is asynchronous (i.e. the browser, having sent a request, can do anything, for example, display a message about waiting for a response, scroll 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 using 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 from the ajax request in our html page.

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

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

In this short article, I will show you how to use jQuery and AJAX in simple php form... Let's get started ... To use jQuery and AJAX we 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 handle the ajax request and return the result to the first page.

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

In the above code, we get the student's name and number and, using jquery and ajax, send them to details.php.

Your Name:
Roll Number:

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

In the above code, we get the student's address using the sequential 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 number and address.

Hope you find this article helpful.

The post () method is usually intended to send data to the server (for example from a form).

In the context of the post method, it's worth mentioning json is a javascript based text format. It can be used by almost any programming language.

jQuery, Ajax POST request

jQuery.post (url ,,,)
  • The first argument (url) is the url of the document to which the request is sent;
  • The second argument (data) is the data sent to the server, usually represented as a js object;
  • The third argument (callback (data, textStatus, jqXHR)) is a function called after the server responds. As arguments this function accepts the data sent by the server in response to the request and the status of how the request was completed.

json_decode () and json_encode ()

V PHP language(from 5.2), JSON support is included in the core in the form of functions json_decode () (decodes a JSON string) and json_encode (), which themselves convert JSON data types to appropriate PHP types and vice versa.

1, "b" => 2); echo json_encode ($ arr); ?>

Result

("a": 1, "b": 2, "c": 3, "d": 4, "e": 5)

PHP example of 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

An example of how an Ajax request works using the POST method

What will we do:
We check the correctness of the sent (POST-request AJAX) data (data is entered by the user). If the data is correct, we display a message. Otherwise, we make a red highlight near the fields. Everything works asynchronously, that is, without reloading the page. you can use this principle, for example, to create a commenting system with the insertion of 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) (/ * Submitting 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 // msg.errors object and display them on the page $ .each (msg.errors, function (k, v) ($ ("#" + k) .addClass ("error"); // alert (k );));)), "json");));));

Html

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 by the 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).") ";)

In this article, the code examples I'm using to send ajax requests to the server via jQuery... Their tasks can be different, so you can use different functions for them, which simplify the writing of code.

Query html data using the Load function

This is the simplest ajax request via jQuery, fetching html data and inserting it into a dom element with id = "result" (the content of the element is replaced):

$ ("# result"). load (" ");

A more advanced use case for load:

$ ("# result"). load (" ", (par1: val1, par2: val2, ...), function (response, status, xhr) (if (status ==" success ") (alert (" Ready ");) else (alert (" Error: "+ xhr.status +" "+ xhr.statusText);)));

In this example, parameters are also passed to the server, and after receiving the response, it is checked whether there was an error (for example, no response was received from the server) and performing various actions.

Ajax requests with GET and POST functions

These functions send an ajax request with the get and post http methods. Here are a couple of examples of their use.

$ .get (" ", // the address of sending the request (par1: val1, par2: val2, ...), // sending some data with a request function (data) (// some actions with the data received from the server data));

The transfer of data is optional, as well as the performance of any actions after receiving a response from the server, i.e. in this case, lines 3 and 4-6 can be deleted if necessary and thus further shorten the code.

The type of data received from the server can be specified by adding dataType (see below) - by default it is determined automatically.

Usage of post is similar, but in the following example I use a function call after receiving a response from the server.

$ .post (" ", (par1: val1, par2: val2, ...), onSuccess); function onSuccess (data) (// some actions with the data received from the server data)

In fact, the get and post functions are shorthand versions of the ajax function, which I will discuss below.

Getting json data using getJSON

getJSON is a shortened version of the ajax request using the GET method and receiving data in the form of json. The method is convenient, for example, to get some kind of array with data and then work with it.

$ .getJSON (" ", (par1: val1, par2: val2, ...)). success (function (data) (// do something with the data, for example, we go through them in a loop and output: for (var i = 0; i

On the server side, the program forms an array and converts it to a json string, for example, like this:

$ arr = array (); $ arr = array ("id" => 10, "text" => "test line 1"); $ arr = array ("id" => 20, "text" => "test line 2"); $ arr = array ("id" => 30, "text" => "test line 3"); echo json_encode ($ arr);

In the same way, you can transfer stdClass objects from the server by converting them to a json string.

Simple ajax request via jQuery with AJAX function

Now I will give an example of a simple get request with the ajax function and getting html data.

$ .ajax ((url: " ", dataType:" html ", success: function (data) (// some actions with the received data data)));

The request to the server is made by the get-method, since the parameter responsible for the type of request, type by default is equal to GET.

More complex example of ajax request via jQuery

An example of making a request by the ajax function with the transfer of data by the post method and event handling. I will describe below Extra options, which are most often used.

$ .ajax ((url: " ", type:" post ", data:"<отправляемые_данные>", // can be a string, but you can, for example, like this: $ (" input, input: checked, input: checked, select, textarea ") dataType:" json ", beforeSend: function () ($ (" # sendajax " ) .button ("loading");), complete: function () ($ ("# sendajax"). button ("reset");), success: function (json) (// some actions with the received data ), error: function (xhr, ajaxOptions, thrownError) (alert (thrownError + "\ r \ n" + xhr.statusText + "\ r \ n" + xhr.responseText);)));

Send data button:

In the above example, when the button is pressed, the state of the button first changes (the text on it changes to "Sending ..." and it becomes inactive), which is done using the beforeSend parameter. Then the request is sent with the transfer of the required data. After receiving a response from the server, the state of the button returns to its previous state (the text changes to "Send", becomes active). The response is received as json data.

I will briefly describe the parameters for sending an ajax request, which most often can be useful:

url Ajax request sending address
type Sending method GET request or POST
data Data sent to the server. It can be a string with parameters and their values ​​in the format par1 = val1 & par2 = val2 & ..., a jQuery object, for example, $ ("input") or other data.
dataType The type of data received from the server. Can be html, json, text, script and xml.
cache Browser caching of the request (false - do not cache).
async Asynchronous execution of the request, i.e. the program continues to execute without waiting for a server response. If you specify false, then the request will be executed synchronously, and the page will not respond to anything until a response is received from the server.
processData Converting the sent data to url format. If you want the data not to be converted, set to false. For example, when sending an image to a server or xml data.
contentType The type of data transferred, by default "application / x-www-form-urlencoded; charset = UTF-8". If you specify false, then the type will not be passed in the header, which may be necessary, for example, when sending an image to the server.
beforeSend A function to execute before sending the ajax request.
complete A function to execute after receiving a response from the server (either successful or not).
success A function to execute when the request succeeds.
error The function to execute on error.

Below are some more examples of using ajax requests.

Submitting a form with all data ajax request via jQuery

Sample html form code:

JavaScript code:

$ ("# myform"). submit (function (e) (e.preventDefault (); $ .ajax ((type: $ (this) .attr ("method"), url: " ", data: $ (this) .serialize (), async: false, dataType:" html ", success: function (result) (alert (" Form sent ");)));));

To prevent the page from reloading when you click on the "submit" button, first cancel the standard browser actions using e.preventDefaults () .

In the data parameter, we pass all the form fields using $ (this) .serialize ()- this function converts all inputs and selections into a string suitable for sending to the server.

Also, the parameter is used here async: false so that until the form is submitted to the server, nothing else can be clicked or done.

Sending an image or file by ajax request via jQuery

The task of sending a file or image to the server without reloading the page occurs quite often. In this example, I will analyze 2 chips at once: file selection by pressing the button, which can be framed as you like, and displaying progress when transferring a file to the server with an ajax request.

html code will be like this:

#addfile (position: relative; overflow: hidden; width: 180px; height: 34px;) #load_file (position: absolute; top: 0; left: 0; width: 180px; height: 34px; font-size: 0px; opacity : 0; filter: alpha (opacity: 0);) #load_file: hover (cursor: pointer;)

The idea is that a standard input is displayed on top of the button to select a file, but it is completely transparent and has the same dimensions as the button. Thus, the user sees the button, but when they hover over it, they actually hover over the input. Accordingly, when he clicks on the button, the file selection input is actually pressed. In order not to blink the cursor after selecting a file, the font size is set to 0px.

Now the javascript code for sending a file to the server showing the progress:

$ (function () ($ ("# load_file"). on ("change", loadfile);)); function loadfile () ($ ("# addfile span"). html ("0% loaded"); files = $ ("# load_file"). files; var form = new FormData (); form.append ("upload" , files); $ .ajax ((url: " ", type:" POST ", data: form, cache: false, processData: false, contentType: false, xhr: function () (var myXhr = $ .ajaxSettings.xhr (); if (myXhr.upload) (myXhr. upload.addEventListener ("progress", ShowProgress, false);) return myXhr;), complete: function (data) ($ ("# addfile span"). html ("Upload image"); $ ("# load_file") .val ("");), success: function (message) (alert (message);), error: function (jqXHR, textStatus, errorThrown) (alert (textStatus + "" + errorThrown);)));) function ShowProgress (e) (if (e.lengthComputable) ($ ("# addfile span"). html ("Loaded" + Math.round (100 * e.loaded / e.total) + "%");))

When uploading a file to the server, the button will show how many% has already been transferred to the server. After the download is complete, the button name is returned as it was, and the value of the file input is set to empty so that you can select a new file again.

An example of the server side in php (at the request of Eugene):

$ message = ""; if (empty ($ _ FILES ["upload"] ["name"]) || $ _FILES ["upload"] == "none") ($ message = "You haven't selected a file";) else if ($ _FILES [ "upload"] ["size"] == 0 || $ _FILES ["upload"] ["size"]> 9437184) ($ message = "The file size does not comply with the norms (maximum 9 MB)";) else if ( ($ _FILES ["upload"] ["type"]! = "Image / jpeg") && ($ _FILES ["upload"] ["type"]! = "Image / pjpeg") && ($ _FILES ["upload "] [" type "]! =" image / gif ") && ($ _FILES [" upload "] [" type "]! =" image / png ")) ($ message =" Only JPG, GIF images can be uploaded and PNG. ";) else if (! is_uploaded_file ($ _ FILES [" upload "] [" tmp_name "])) ($ message =" Something went wrong. Please try uploading the file again. ";) else ($ ftype = $ _FILES ["upload"] ["type"]; $ fname = "newname_image.". ($ ftype == "image / gif"? "gif": ($ ftype == "image / png"? " png ":" jpg ")); if (move_uploaded_file ($ _ FILES [" upload "] [" tmp_name "], $ _SERVER [" DOCUMENT_ROOT "]." / files /".$ fname)) ($ message = "Image successfully loaded. ";) else ($ message =" Something went wrong To. Try uploading the file again. ";)) Exit ($ message);

The information about the uploaded image will be contained in $ _FILES ["upload"], because the file was added by the script like this: form.append ("upload", files); Accordingly, all that is required from the php program is to check that the file corresponds to the expected parameters, transfer the file to desired folder(in the example, to the files folder) under the desired name (in the example, newname_image) and return a response to the browser, which in my example is simply displayed to the user by the alert (message) command;

There are a lot of situations in which it is possible and even necessary to use ajax requests, and all of them cannot be analyzed here. Nevertheless, if you have any suggestions, what other examples it makes sense to add here, write in the comments.

I can't send in any way simplest request to the servlet using jQuery. But at the same time, if I send through the form, then everything works with a bang. Below is the index.html from which I want to send the username. login.js, in which I form the request itself, SerletStore.java the servlet itself. And the structure of the whole project.

login.js The only more or less working url = "http: // localhost: 8080 / testservlet / post", and they "/ testservlet / post", "testservlet / post", "/ post," "post" cause a 404 error.

Function addNewVoting () (var xhr = new XMLHttpRequest (); var body = "name =" + encodeURIComponent ("name") + "& surname =" + encodeURIComponent ("surname"); xhr.open ("POST", "http : // localhost: 8080 / testservlet / post ", true) xhr.setRequestHeader (" Content-Type "," application / x-www-form-urlencoded ") xhr.send (body);); function addNewVoting1 () (var user = ("firstName": "vlad") var JSONString = JSON.stringify (user); var url = "http: // localhost: 8080 / testservlet / post"; $ .ajax ((url : url, method: "post", data: JSONString, contentType: "application / json", error: function (message) (var JSONObject = JSON.parse (message); console.log (JSONObject);), success: function (data) (var JSONObject = JSON.parse (data); console.log (JSONObject);), headers: ("Accept": "application / json", "Accept-Language": "en", "Cache-Control ":" max-age = 3600 "))););

When the second function is called, it outputs this:

index.html

Login Form

ServletStore.java

Import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet (name = "post", urlPatterns = "/ post") public class Servlet extends HttpServlet (@Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException (PrintWriter writer = print ("Hello");) @Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException (super.doPost (req, resp);))

Project structure.

A lesson in which we'll use examples to create simple asynchronous AJAX requests to the server. We will use both the GET method and the POST method as a method for transmitting requests. On the server, we will process requests using PHP scripts.

What is an asynchronous AJAX request?

AJAX technology is mainly used to make asynchronous requests to the server. An asynchronous request is one that runs in the background and does not prevent the user from interacting with the page.

When sending an asynchronous request, the browser (page) is not "frozen", i.e. with her, as before, you can work. But then how do you know when a response will come from the server. To determine this, you need to monitor the browser's readyState property. This property contains a number, by the value of which you can judge at what stage the request is. The following table summarizes the basic values ​​of the readyState property and their corresponding states.

Those. it turns out that we need to track when the value of the readyState property is 4. This will mean that a response from the server came to the sent request. The rest of the values ​​are rarely used in practice, and some browsers may not support them.

To determine at what stage the request is, you need to use the onreadystatechange event of the XMLHttpRequest object. This event occurs whenever the value of the readyState property changes. Therefore, in the handler of this event (of an unnamed or named function), you can write actions that will check whether this property is equal to 4 and if it is, then, for example, display the server response on the page.

Making an asynchronous AJAX request (GET method)

Let's consider creating an asynchronous AJAX request using an example that will greet the user and display his IP address after loading the page.

To do this, you need to create 2 files on the server in one directory:

  1. welcome.html - HTML page that will be displayed to the user. In the same page, we will place a script that will perform all the necessary actions for AJAX to work on the client side.
  2. processing.php - PHP file that will process the request on the server side and form the response. Let's start development by creating the basic structure of the welcome.html file.
An example of AJAX work

An example of AJAX work

Let's look at the sequence of actions that need to be performed on the client side (in JavaScript code):

    Let's prepare the data required to execute the request on the server. If no data is needed to execute the query on the server, then this stage can be skipped.

    Let's create a variable that will contain an instance of the XHR object (XMLHttpRequest).

    Let's set up the request using the open () method.

    The following parameters are specified:

    • The method by which the request will be sent to the server (GET, POST).
    • The URL that will handle the request on the server.
    • Request type: synchronous (false) or asynchronous (true).
    • Username and password if required.
  1. Subscribe to the onreadystatechange event of the XHR object and specify the handler as an anonymous or named function. After that, we will create a code inside this function that will check the status of the response and perform certain actions on the page. The response that comes from the server is always in the responseText property.

    In addition to checking the value of the readyState property with the number 4, you can check the value of the status property. This property determines the status of the request. If it is 200, then everything is OK. Otherwise, an error occurred (for example, 404 - URL not found).

    Let's send a request to the server using the send () method.

    If we use the GET method to send a request, then pass the data into the parameter this method no need. They are passed as part of the URL.

    If we use the POST method to send a request, then the data must be passed as a parameter to the send () method. In addition, before calling this method, you must set the Content-Type header so that the server knows in what encoding the request came to it and can decrypt it.

Content of script element:

// 2. Create a variable request var request = new XMLHttpRequest (); // 3. Setting up the request request.open ("GET", "processing.php", true); // 4. Subscribing to the onreadystatechange event and processing it using the anonymous function request.addEventListener ("readystatechange", function () (// if request states are 4 and request status is 200 (OK) if ((request.readyState == 4) && (request.status == 200)) (// for example, display the XHR object in the browser console console.log (request); // and the response (text) received from the server in the alert console.log (request.responseText) ; // get the element c id = welcome var welcome = document.getElementById ("welcome"); // replace the content of the element with the response from the server welcome.innerHTML = request.responseText;))); // 5. Sending a request to the server request.send ();

As a result, the welcome.html file will have the following code:

An example of AJAX work

An example of AJAX work

On the server (using php):

  1. Let's get the data. If data is sent via the GET method, then from the global array $ _GET ["name"]. And if the data is transferred using the POST method, then from the global array $ _POST ["name"].
  2. Using this data, let's perform some actions on the server. As a result, we will get some answer. Let's echo it.

Making an asynchronous AJAX request (POST method)

Let's modify the above example. Now the AJAX request to the server will be executed after clicking on the button. It will receive the name that the user entered in the input element and send it via the POST method to the server. After receiving the response from the server, replace the content of the div element on the page with it.

An example of AJAX work

An example of AJAX work