Run Ajax Load Again on Button Click
Read Time: x mins Languages:
Today, we're going to explore the concept of AJAX with PHP and JavaScript. The AJAX technique helps y'all to meliorate your application'due south user interface and enhance the overall end user experience.
What Is AJAX?
AJAX stands for Asynchronous JavaScript and XML, and it allows you lot to fetch content from the back-end server asynchronously, without a page refresh. Thus, it lets y'all update the content of a spider web page without reloading it.
Let's look at an example to understand how you could utilise AJAX in your day-to-day application development. Say y'all want to build a folio that displays a user's contour data, with unlike sections similar personal data, social data, notifications, letters, and then on.
The usual arroyo would be to build dissimilar web pages for each section. Then for instance, users would click the social information link to reload the browser and display a page with the social information. This makes it slower to navigate between sections, though, since the user has to expect for the browser to reload and the page to render once more each time.
On the other hand, you could also use AJAX to build an interface that loads all the information without refreshing the page. In this instance, you can brandish different tabs for all sections, and by clicking on the tab it fetches the corresponding content from the back-cease server and updates the page without refreshing the browser. This helps you to meliorate the overall end-user feel.
The overall AJAX call works something similar this:
Let's quickly go through the usual AJAX period:
- Showtime, the user opens a web page as usual with a synchronous request.
- Adjacent, the user clicks on a DOM element—usually a button or link—that initiates an asynchronous request to the back-end server. The terminate user won't observe this since the call is made asynchronously and doesn't refresh the browser. However, y'all tin can spot these AJAX calls using a tool similar Firebug.
- In response to the AJAX request, the server may return XML, JSON, or HTML string data.
- The response data is parsed using JavaScript.
- Finally, the parsed data is updated in the web page's DOM.
Then as you lot can see, the spider web page is updated with existent-fourth dimension data from the server without the browser reloading.
In the adjacent section, we'll how to implement AJAX using vanilla JavaScript.
How AJAX Works Using Vanilla JavaScript
In this section, we'll come across how AJAX works in vanilla JavaScript. Of course, there are JavaScript libraries available that make information technology easier to do AJAX calls, but it'south e'er interesting to know what'due south happening under the hood.
Let's have a look at the following vanilla JavaScript code, which performs the AJAX phone call and fetches a response from the server asynchronously.
<script> var objXMLHttpRequest = new XMLHttpRequest(); objXMLHttpRequest.onreadystatechange = function() { if(objXMLHttpRequest.readyState === iv) { if(objXMLHttpRequest.status === 200) { alert(objXMLHttpRequest.responseText); } else { alert('Mistake Code: ' + objXMLHttpRequest.status); alert('Error Message: ' + objXMLHttpRequest.statusText); } } } objXMLHttpRequest.open('GET', 'request_ajax_data.php'); objXMLHttpRequest.send(); </script>
Let's go through the above lawmaking to understand what'southward happening behind the scenes.
- Outset, we initialize the
XMLHttpRequest
object, which is responsible for making AJAX calls. - The
XMLHttpRequest
object has areadyState
property, and the value of that property changes during the request lifecycle. It tin hold one of four values:OPENED
,HEADERS_RECEIVED
,LOADING
, andDone
. - Nosotros tin gear up a listener function for state changes using the
onreadystatechange
holding. And that'due south what nosotros've done in the to a higher place example: we've used a office which will exist called every time the state property is inverse. - In that office, nosotros've checked if the
readyState
value equals4
, which means the request is completed and we've got a response from the server. Next, nosotros've checked if the status code equals200
, which means the request was successful. Finally, nosotros fetch the response which is stored in theresponseText
property of theXMLHttpRequest
object. - After setting up the listener, we initiate the asking by calling the
open
method of theXMLHttpRequest
object. ThereadyState
property value will be set to ane later this call. - Finally, we've called the
send
method of theXMLHttpRequest
object, which actually sends the request to the server. ThereadyState
property value will be set to two subsequently this call. - When the server responds, information technology volition eventually ready the
readyState
value to four, and you should meet an alert box displaying the response from the server.
So that's how AJAX works with vanilla JavaScript. The method here, using "callback functions" is the traditional way to code AJAX, but a cleaner and more modern way is with Promises.
In the next section, nosotros'll see how to use thePromise
object for AJAX.
How to Utilize JavaScript Promises for AJAX
Promises in JavaScript provide a better way to manage asynchronous operations and callbacks that are dependent on other callbacks. In JavaScript,Promise
is an object which may have 1 of the three states: pending, resolved, or rejected. Initially, thePromise
object is in the awaiting state, but as the asynchronous operation is completed, it may evaluate to the resolved or rejected state.
Let's quickly revise the previous case with theHope
object.
role AjaxCallWithPromise() { return new Promise(office (resolve, refuse) { const objXMLHttpRequest = new XMLHttpRequest(); objXMLHttpRequest.onreadystatechange = function () { if (objXMLHttpRequest.readyState === 4) { if (objXMLHttpRequest.status == 200) { resolve(objXMLHttpRequest.responseText); } else { pass up('Error Code: ' + objXMLHttpRequest.status + ' Error Bulletin: ' + objXMLHttpRequest.statusText); } } } objXMLHttpRequest.open('Get', 'request_ajax_data.php'); objXMLHttpRequest.ship(); }); } AjaxCallWithPromise().then( data => { console.log('Success Response: ' + data) }, error => { console.log(fault) } );
When theAjaxCallWithPromise
role is called, information technology returns the promise object, and it'south in the pending state initially. Based on the response, it'll call either theresolve
orreject
office.
Next, we use theand then
method, which is used to schedule callbacks when the hope object is successfully resolved. Thethen
method takes two arguments. The first argument is a callback which will be executed when the hope is resolved, and the second argument is a callback for the rejected country.
So that's how y'all can apply JavaScript Promises for AJAX. In the next section, we'll see how to use the jQuery library to perform AJAX calls.
How AJAX Works Using the jQuery Library
In the before section, we discussed how you could perform AJAX calls using vanilla JavaScript. In this department, we'll utilize the jQuery library to demonstrate this. I'll assume that you're aware of the nuts of the jQuery library.
The jQuery library provides a few different methods to perform AJAX calls, although here we'll look at the standardajax
method, which is the nigh ofttimes used.
Take a look at the following example.
<script> $.ajax( 'request_ajax_data.php', { success: function(data) { alert('AJAX call was successful!'); alert('Information from the server' + data); }, error: office() { alert('At that place was some error performing the AJAX phone call!'); } } ); </script>
Equally yous already know, the$
sign is used to refer to a jQuery object.
The first parameter of theajax
method is the URL that volition exist called in the background to fetch content from the server side. The second parameter is in JSON format and lets you specify values for some different options supported by theajax
method.
In well-nigh cases, y'all will need to specify the success and error callbacks. The success callback will exist called after the successful completion of the AJAX call. The response returned by the server will be passed forth to the success callback. On the other hand, the failure callback will exist called if something goes wrong and in that location was an issue performing the AJAX phone call.
And then as yous can see, it'south easy to perform AJAX operations using the jQuery library. In fact, the process is more than or less the same, irrespective of the JavaScript library with which you choose to perform AJAX calls.
In the next section, nosotros'll see a real-globe example to understand how this all works with PHP.
A Real-Globe AJAX Instance With PHP
In this section, we'll build an example that fetches JSON content from a PHP file on the server side using AJAX.
For demonstration purposes, we'll build an example which performs user login using AJAX and jQuery. To get-go with, let'southward make theindex.php file, as shown in the following snippet, which renders a basic login course.
<!doctype html> <html> <head> <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script> </head> <body> <grade id="loginform" method="post"> <div> Username: <input blazon="text" proper name="username" id="username" /> Password: <input type="password" name="password" id="password" /> <input type="submit" name="loginBtn" id="loginBtn" value="Login" /> </div> </course> <script type="text/javascript"> $(certificate).ready(function() { $('#loginform').submit(function(east) { e.preventDefault(); $.ajax({ type: "Postal service", url: 'login.php', data: $(this).serialize(), success: function(response) { var jsonData = JSON.parse(response); // user is logged in successfully in the back-cease // let's redirect if (jsonData.success == "1") { location.href = 'my_profile.php'; } else { alert('Invalid Credentials!'); } } }); }); }); </script> </trunk> </html>
Theindex.php file is a pretty standard HTML course which contains username and password fields. It also contains a jQuery JavaScript snippet, which follows the outline we saw above.
We've used thesubmit
event of the class chemical element, which will be triggered when a user clicks on the submit push button. In that event handler, we've initiated the AJAX call, which submits the form data to thelogin.php file using the Mail method asynchronously. Once we receive a response from the server, nosotros parse it using theparse
method of theJSON
object. And finally, based on the success or failure, nosotros take the appropriate action.
Let's besides meet whatlogin.php looks like.
<?php if (isset($_POST['username']) && $_POST['username'] && isset($_POST['password']) && $_POST['password']) { // do user authentication as per your requirements // ... // ... // based on successful hallmark repeat json_encode(array('success' => 1)); } else { repeat json_encode(array('success' => 0)); }
Thelogin.php file contains the logic of authenticating users and 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 besides. Information technology provides unlike methods likethen
,done
,fail
andalways
that y'all could use in the context of Promises.
Let's quickly revise the jQuery snippet which we've used in our example to show how to utilize it with thethen
method.
... ... $.ajax({ type: "POST", url: 'login.php', data: $(this).serialize() }).then( // resolve/success callback role(response) { var jsonData = JSON.parse(response); // user is logged in successfully in the dorsum-end // let'south redirect if (jsonData.success == "ane") { location.href = 'my_profile.php'; } else { alarm('Invalid Credentials!'); } }, // reject/failure callback role() { alarm('There was some error!'); } ); ... ...
Conclusion
In this tutorial, nosotros discussed the basics of AJAX and how it works with a PHP app. 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 existent-globe example which demonstrated how you lot tin can apply AJAX to fetch server-side PHP content
Larn PHP With a Free Online Course
If you want to learn PHP, check out our costless online course on PHP fundamentals!
In this course, you'll learn the fundamentals of PHP programming. You'll get-go with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the near of import skills for writing apps for the web: you'll get a risk to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.
You can also learn JavaScript for free on Envato Tuts+! JavaScript is the language of the web. If you lot want to code for the web, you lot need to know JavaScript inside and out. From apprehensive beginnings, JavaScript has grown to a powerful and complex language with features such as classes, promises, pointer functions, generators, cord templates, and many others.
In this course, you'll learn all of the essential concepts of the JavaScript language. That's right: all of them!
Did you notice this post useful?
Source: https://code.tutsplus.com/tutorials/how-to-use-ajax-in-php-and-jquery--cms-32494
0 Response to "Run Ajax Load Again on Button Click"
Post a Comment