JavaScript - Asynchronous AJAX requests with examples. How to display html using AJAX What is AJAX

💖 Like it? Share the link with your friends

jQuery is a javascript library that aims to "write less, do more". jQuery is easy to add to your site and start using. With jQuery, it becomes much easier to use javascript on your site.

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

What is AJAX?

AJAX is asynchronous (i.e., the browser, after sending a request, can do anything, for example, show a message 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 jquery and ajax, you can make a request and get 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 by ajax request in our html page.

jQuery makes the existing browser Ajax API more powerful and easier to use. Creating ajax calls in the normal way using javascript is a little tricky, since you have to keep in mind that different browsers require different approaches to creating an XMLHttpRequest object. Also, submitting data from, for example, forms becomes more difficult if you use normal javascript for the ajax call.

jQuery provides a simple and powerful functionality that extends the javascript 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 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 code above, we get the student's name and number and use jquery and ajax to send 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 code above, we get the student's address using a sequence number and their name.

For this example, you will need to create the school database and the students table. The student table contains fields with names, sequence number, and address.

I hope this article will be useful to you.

In this article, we will talk about the interaction of ajax with php. How to connect the work of ajax script and php code? How to use ajax in web development? If you are interested in such questions, you will find the answers to them in our article. As well as examples of ajax php code.

ajax + php

In order to understand whether we need ajax with php at all, let's see what it can be useful for. The use of ajax + php can be varied, the only thing is that you cannot design page elements using this technology that are relevant to search engines. Because ajax loads page elements after it is loaded when js events are called, but as we know, search engines cannot read javascript code, so you need to carefully choose where you need and where you don’t need to use ajax with php.

Where can I apply ajax + php?

1. Adding a new comment

4. Organization of search on the site (auto-completion)

5. Step-by-step user registration on the site

6. Subscribe to e-mail

7. View photos

And others…

As you can see, there are a lot of options for using ajax + php. That is, it can be applied where reloading the page would not be appropriate, where you just need to exchange data with the server.

Where not to use ajax + php

My opinion is objective, maybe you think otherwise, but based on my experience I will say that ajax + php should not be used:

1. To implement the menu

2. Implementation of tabs on the page (For example: when in an online store on the product page you see a review, information, comments, photos, videos ... you do not need to load data when switching these tabs.)

And other negative examples that can harm the best ranking of your page.

ajax interaction with php

In fact, ajax technology cannot exist without php scripts, since ajax only sends data to the server and receives a return response, without reloading the pages. Therefore, it is more correct to ask a question, how to link the work of ajax and php. But we will talk about this in the next paragraph of the article (ajax php example), and now we will deal with the specifics of ajax.

To send data to the server, you need to create an XMLHTTPRequest object. Using it, open a url (php script), send data to it (POST or GET method), get a response, and use the knowledge of the js language to display the received server response on the monitor (the response can be any fragment or element of the site page).

For clarification, see the diagram below for illustrating ajax interaction with php.


Ajax + php example

For an example of ajax interaction with php, let's create two files:

1.ajax_page.html

2.get_ajax.php

Let's look at the user side of the application first, i.e. the ajax_ page. html :

Ajax + PHP: example | site function XmlHttp() ( 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 ajax(param) ( if (window.XMLHttpRequest) req = new XmlHttp(); method=(!param.method ? "POST" : param.method.toUpperCase()); if(method=="GET") ( send=null; param.url=param.url+"&ajax=true"; ) else ( send=""; for (var i in param.data) send+= i+"="+param.data[i]+"&"; send=send+"ajax=true"; ) req.open(method, param .url, true); if(param.statbox)document.getElementById(param.statbox).innerHTML = " "; req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.send(send); req.onreadystatechange = function() ( if (req.readyState == 4 && req .status == 200) //if the response is positive ( if(param.success)param.success(req.responseText); ) ) ) Here we will receive reports on the operation of the ajax application and the server response.

Input field 1

Enter your text.!

Input field 2

Free text... I love this article, and I want to subscribe to RSS to read such articles more often!!!

ajax_page.html:


Let's analyze the javascript side of this example:

XmlHttp() is a function that creates an XMLHttpRequest() object, it is written as compactly and cross-browser as possible.

ajax(param) - our handler, when raising events (onclick), receives the necessary data in the param array:

url - where to send data, and it can be in this form page. php? parameter= value , that is, information can be transferred using the GET method.

statbox - id of the html block that will receive the results of the ajax + php application.

method - method for sending data, can be POST or GET. In our example, we use the POST method, but at the same time, information can be transmitted via the url using the GET method.

data - array of transferred data. In our example, the data is automatically taken from fields 1 and 2, although you can just write data: (name: "value").

success - the name of the function or the function itself, which will process the received data (text).

The call to the ajax function, as you can see, is made by the onclick=ajax() event.

Now let's analyze the server side of the ajax + php application, that is, the get_ajax. php:

Everything is much simpler here. First, we set the encoding of the output data, using the header. We set a ban on data caching. sleep(2) - pauses the script for 2 seconds, this is to see the waiting animation wait.gif. We display the received data, while reading all the elements of the $_POST array and converting them to the desired encoding (for Cyrillic).

To launch our ajax php application, we load the ajax_page.html page into the browser

This is what I got when I clicked the TEST AJAX button:


This is the response received from the get_ajax.php file:


There are still questions aboutajax +php? Post them in the comments below...

I started this article at the request of beginners who are just starting to learn JS / jQuery and, sooner or later, face the problem of how to use Ajax technology in practice. In this part, I will try in simple language ( don't let this confuse advanced users) explain how to apply this "chip" using the jQuery library in your projects.

So... jQuery has several methods that make requests to the back end of the site without reloading the page. We won't look at each method individually "under the microscope", for the simple reason that they are all truncated/abbreviated functions of the $.ajax() method. First, let's look at the code below, and then we will analyze it in more detail:

html ( index.html file)

Cool page site Click me!

In this file, we have the jQuery library connected, a file with our JS code, a button (id="btn"), by clicking on which an ajax request will be launched, and a block (id="output"), in which we will display the result ajax request work

JS/jQuery ( script.js file)

$(function()( var output = $("#output"); // output block $("#btn").on("click", function()( $.ajax(( url: "path/ to/handler.php", // path to php handler type: "POST", // data transfer method dataType: "json", // type of expected data in response data: (key: 1), // data, which we pass to the server beforeSend: function()( // The function is called before sending the request output.text("Request sent. Please wait for a response."); ), error: function(req, text, error)( // tracking errors during execute an ajax request output.text("Houston, We're in trouble!" + text + " | " + error); ), complete: function()( // function is called when the request ends output.append("

Request completed!

"); ), success: function(json)( // function that will be called in case of successful completion of the request to the server // json is a variable containing the response data from the server. Call it whatever you like;) output.html(json) ; // display the data received from the server on the page ) )); )); ));

I immediately commented this code, so there should not be any special questions. The only thing I want to note for copy-paste lovers is that you need to specify the real path to the handler in the url parameter. And one more thing - in the example we pass the data entered manually (the "key" key with the value "1"), but in real projects, this data is picked up from some sources, but we'll talk about this later.

PHP handler ( handler.php file)



tell friends