Code Ajax Php

Today, we’re going lớn explore the concept of AJAX with PHPhường and JavaScript. The AJAX  technique helps you to improve sầu your application"s user interface & enhance the overall end user experience.

Bạn đang xem: Code ajax php

If want to learn JavaScript, kiểm tra out our miễn phí online course on JavaScript fundamentals!

What Is AJAX?

AJAX stands for Asynchronous JavaScript và XML, và it allows you lớn fetch nội dung from the back-end server asynchronously, without a page refresh. Thus, it lets you update the nội dung of a website page without reloading it.

Let’s look at an example lớn understand how you could use AJAX in your day-to-day application development. Say you want to build a page that displays a user"s profile information, with different sections lượt thích personal information, social information, notifications, messages, & so on.

The usual approach would be khổng lồ build different website pages for each section. So for example, users would cliông chồng the social information liên kết khổng lồ reload the browser and display a page with the social information. This makes it slower khổng lồ navigate between sections, though, since the user has to lớn wait for the browser to reload and the page khổng lồ render again each time.

On the other hvà, you could also use AJAX to lớn build an interface that loads all the information without refreshing the page. In this case, you can display different tabs for all sections, & by clicking on the tab it fetches the corresponding content from the back-over server và updates the page without refreshing the browser. This helps you to lớn improve the overall end-user experience.

The overall AJAX gọi works something like this:


Let’s quickly go through the usual AJAX flow:

First, the user opens a website page as usual with a synchronous request. Next, the user clicks on a DOM element—usually a button or link—that initiates an asynchronous request khổng lồ the back-over server. The kết thúc user won’t notice this since the Gọi is made asynchronously và doesn’t refresh the browser. However, you can spot these AJAX calls using a tool like Firebug. In response lớn the AJAX request, the VPS may return XML, JSON, or HTML string data. The response data is parsed using JavaScript. Finally, the parsed data is updated in the website page"s DOM.

So as you can see, the web page is updated with real-time data from the VPS without the browser reloading.

In the next section, we’ll how lớn implement AJAX using vanilla JavaScript.

How AJAX Works Using Vanilla JavaScript

In this section, we’ll see how AJAX works in vanilla JavaScript. Of course, there are JavaScript libraries available that make it easier khổng lồ vì chưng AJAX calls, but it’s always interesting to lớn know what’s happening under the hood.

Let’s have sầu a look at the following vanilla JavaScript, which performs the AJAX Điện thoại tư vấn & fetches a response from the VPS asynchronously.

Let’s go through the above sầu khổng lồ underst& what’s happening behind the scenes.

First, we initialize the XMLHttpRequest object, which is responsible for making AJAX calls. The XMLHttpRequest object has a readyState property, and the value of that property changes during the request lifecycle. It can hold one of four values: OPENED, HEADERS_RECEIVED, LOADING, and DONE. We can mix up a listener function for state changes using the onreadystatechange property. And that’s what we’ve done in the above example: we’ve used a function which will be called every time the state property is changed. In that function, we’ve checked if the readyState value equals 4, which means the request is completed & we’ve sầu got a response from the VPS. Next, we’ve sầu checked if the status equals 200, which means the request was successful. Finally, we fetch the response which is stored in the responseText property of the XMLHttpRequest object. After setting up the listener, we initiate the request by calling the open method of the XMLHttpRequest object. The readyState property value will be phối to lớn 1 after this Hotline. Finally, we’ve called the send method of the XMLHttpRequest object, which actually sends the request khổng lồ the server. The readyState property value will be set khổng lồ 2 after this call. When the VPS responds, it will eventually mix the readyState value to lớn 4, & you should see an alert box displaying the response from the VPS.

So that’s how AJAX works with vanilla JavaScript. The method here, using "callbachồng functions" is the traditional way to AJAX, but a cleaner & more modern way is with Promises.

In the next section, we"ll see how to lớn use the Promise object for AJAX.

How to lớn Use JavaScript Promises for AJAX

Promises in JavaScript provide a better way lớn manage asynchronous operations và callbacks that are dependent on other callbacks. In JavaScript, Promise is an object which may have one of the three states: pending, resolved, or rejected. Initially, the Promise object is in the pending state, but as the asynchronous operation is completed, it may evaluate to lớn the resolved or rejected state.

Let"s quickly revise the previous example with the Promise object.

function AjaxCallWithPromise() else } }"GET", "request_ajax_data.php"); objXMLHttpRequest.send(); }); } AjaxCallWithPromise().then( data => , error => );

When the AjaxCallWithPromise function is called, it returns the promise object, & it"s in the pending state initially. Based on the response, it"ll gọi either the resolve or reject function. 

Next, we use the then method, which is used to lớn schedule callbacks when the promise object is successfully resolved. The then method takes two arguments. The first argument is a callback which will be executed when the promise is resolved, and the second argument is a callbaông chồng for the rejected state.

So that"s how you can use JavaScript Promises for AJAX. In the next section, we’ll see how khổng lồ use the jQuery library lớn perkhung AJAX calls.

How AJAX Works Using the jQuery Library

In the earlier section, we discussed how you could perkhung AJAX calls using vanilla JavaScript. In this section, we’ll use the jQuery library to lớn demonstrate this. I"ll assume that you’re aware of the basics of the jQuery library.

Xem thêm: tải game otaku adventure

The jQuery library provides a few different methods lớn perkhung AJAX calls, although here we’ll look at the standard ajax method, which is the most often used.

Take a look at the following example.

As you already know, the $ sign is used lớn refer khổng lồ a jQuery object.

The first parameter of the ajax method is the URL that will be called in the background lớn fetch content from the server side. The second parameter is in JSON format and lets you specify values for some different options supported by the ajax method.

In most cases, you will need khổng lồ specify the success & error callbacks. The success callbaông chồng will be called after the successful completion of the AJAX hotline. The response returned by the server will be passed along khổng lồ the success callbaông chồng. On the other hand, the failure callbaông chồng will be called if something goes wrong and there was an issue performing the AJAX Call.

So as you can see, it"s easy khổng lồ perkhung AJAX operations using the jQuery library. In fact, the process is more or less the same, irrespective of the JavaScript library with which you choose khổng lồ perkhung AJAX calls.

In the next section, we’ll see a real-world example to understand how this all works with PHPhường.

A Real-World AJAX Example With PHP

In this section, we’ll build an example that fetches JSON content from a PHPhường tệp tin on the server side using AJAX.

For demonstration purposes, we"ll build an example which performs user login using AJAX và jQuery. To start with, let"s make the index.php file, as shown in the following snippet, which renders a basic login khung.

Username: Password: <đầu vào type="submit" name="loginBtn" id="loginBtn" value="Login" />

The index.php tệp tin is a pretty standard HTML size which contains username và password fields. It also contains a jQuery JavaScript snippet, which follows the outline we saw above sầu.

We"ve sầu used the submit sự kiện of the form element, which will be triggered when a user clicks on the submit button. In that event handler, we"ve sầu initiated the AJAX Gọi, which submits the size data to lớn the login.php tệp tin using the POST method asynchronously. Once we receive a response from the hệ thống, we parse it using the parse method of the JSON object. And finally, based on the success or failure, we take the appropriate action.

Let"s also see what login.php looks like.

) && $_POST<"username"> && isset($_POST<"password">) && $_POST<"password">) else

The login.php tệp tin contains the súc tích of authenticating users & returns a JSON response based on the success or failure of login.

Using Promises for AJAX With jQuery

Apart from this, the $.ajax method supports JavaScript Promises as well. It provides different methods like then, done, fail and always that you could use in the context of Promises.

Let"s quickly revise the jQuery snippet which we"ve used in our example to lớn show how to lớn use it with the then method.

... ... $.ajax().then( // resolve/success callbaông chồng function(response) else }, // reject/failure callbachồng function() ); ... ...


In this tutorial, we discussed the basics of AJAX & how it works with a PHPhường ứng dụng. In the first half of the article, we looked at how AJAX works in vanilla JS and in the jQuery library. In the latter half, we built a real-world example which demonstrated how you can use AJAX khổng lồ fetch server-side PHP.. content

Learn PHP With a Free Online Course

If you want lớn learn PHP, check out our không lấy phí online course on PHP fundamentals!

In this course, you"ll learn the fundamentals of PHP. programming. You"ll start with the basics, learning how PHP. works và writing simple PHP loops and functions. Then you"ll build up to lớn coding classes for simple object-oriented programming (OOP). Along the way, you"ll learn all the most important skills for writing apps for the web: you"ll get a chance khổng lồ practice responding lớn GET và POST requests, parsing JSON, authenticating users, and using a MySQL database.