SlideShare a Scribd company logo
1 of 20
Download to read offline
7 days of WordPress plugins, themes & templates - for free!*
 Start 7-Day Free Trial 
Advertisement
Code  
PHP
How to Use AJAX in PHP and
jQuery
Sajal Soni Sep 28, 2020 (Updated Nov 27, 2021)
 
23
likes  
Read Time:
10 mins  
 English
PHP REST API Ajax JavaScript jQuery
Today, we’re going to explore the concept of AJAX with PHP and JavaScript.
The AJAX  technique helps you to improve your application's user interface and
enhance the overall end user experience.
| |


What Is AJAX?
AJAX stands for Asynchronous JavaScript and XML, and it allows you to fetch
content from the back-end server asynchronously, without a page refresh.
Thus, it lets you update the content of a web page without reloading it.
Let’s look at an example to 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 like personal information,
social information, notifications, messages, and so on.
The usual approach would be to build different web pages for each section. So
How to Use AJAX in PHP and jQuery

The usual approach would be to build different web pages for each section. So
for example, 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 wait for the browser to reload
and the page to render again 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 case, you can display
different tabs for all sections, and by clicking on the tab it fetches the
corresponding content from the back-end server and updates the page
without refreshing the browser. This helps you to improve the overall end-user
experience.
The overall AJAX call works something like this:

Let’s quickly go through the usual AJAX flow:
1. First, the user opens a web page as usual with a synchronous request.
2. Next, the user clicks on a DOM element—usually a button or link—that
initiates an asynchronous request to the back-end server. The end user
won’t notice this since the call is made asynchronously and doesn’t refresh
the browser. However, you can spot these AJAX calls using a tool like
Firebug.
3. In response to the AJAX request, the server may return XML, JSON, or
HTML string data.
4. The response data is parsed using JavaScript.
5. Finally, the parsed data is updated in the web page's DOM.
So as you can see, the web page is updated with real-time data from the server
without the browser reloading.
In the next section, we’ll how to 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 to do AJAX calls, but it’s
always interesting to know what’s happening under the hood. 
Let’s have a look at the following vanilla JavaScript code, which performs the
AJAX call and fetches a response from the server asynchronously.
<script>

var objXMLHttpRequest = new XMLHttpRequest();

objXMLHttpRequest.onreadystatechange = function() {

if(objXMLHttpRequest.readyState === 4) {

if(objXMLHttpRequest.status === 200) {

alert(objXMLHttpRequest.responseText);

} else {

alert('Error Code: ' + objXMLHttpRequest.status);

alert('Error Message: ' + objXMLHttpRequest.statusText);

}

}
}
objXMLHttpRequest.open('GET', 'request_ajax_data.php');

objXMLHttpRequest.send();

</script>
Let’s go through the above code to understand what’s happening behind the
scenes.
1. First, we initialize the  XMLHttpRequest  object, which is responsible for
making AJAX calls.
2. 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 .
3. We can set 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.
4. In that function, we’ve checked if the  readyState  value equals  4 , which
means the request is completed and we’ve got a response from the
server. Next, we’ve checked if the status code equals  200 , which means
the request was successful. Finally, we fetch the response which is stored
in the  responseText  property of the  XMLHttpRequest  object.
5. After setting up the listener, we initiate the request by calling
the  open  method of the  XMLHttpRequest  object. The  readyState  property
value will be set to 1 after this call.
6. Finally, we’ve called the  send  method of the  XMLHttpRequest  object, which
actually sends the request to the server. The  readyState  property value will
be set to 2 after this call.
7. When the server responds, it will eventually set the  readyState  value to 4,
and you should see 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, we'll see how to use the  Promise  object for AJAX.
How to Use 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 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 the
resolved or rejected state.
Let's quickly revise the previous example with the  Promise  object.
function AjaxCallWithPromise() {

return new Promise(function (resolve, reject) {

const objXMLHttpRequest = new XMLHttpRequest();

objXMLHttpRequest.onreadystatechange = function () {

if (objXMLHttpRequest.readyState === 4) {

if (objXMLHttpRequest.status == 200) {

resolve(objXMLHttpRequest.responseText);

} else {

reject('Error Code: ' + objXMLHttpRequest.status + ' Error Messag
}

}

}

objXMLHttpRequest.open('GET', 'request_ajax_data.php');

objXMLHttpRequest.send();

});
}
AjaxCallWithPromise().then(


data => { console.log( Success Response: + data) },

error => { console.log(error) }

);
When the  AjaxCallWithPromise  function is called, it returns the promise object,
and it's in the pending state initially. Based on the response, it'll call either
the  resolve  or  reject  function. 
Next, we use the  then  method, which is used to 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 callback for the rejected state.
So that's how you can use 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 earlier section, we discussed how you could perform AJAX calls using
vanilla JavaScript. In this section, we’ll use the jQuery library to demonstrate
this. I'll assume that you’re aware of the basics of the jQuery library.
The jQuery library provides a few different methods to perform 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.
<script>

$.ajax(

'request_ajax_data.php',

{
success: function(data) {

alert('AJAX call was successful!');

alert('Data from the server' + data);

},

error: function() {

alert('There was some error performing the AJAX call!');

}

}
);

</script>
As you already know, the  $  sign is used to refer to a jQuery object.
The first parameter of the  ajax  method is the URL that will be 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 the  ajax  method.
In most cases, you will need to specify the success and error callbacks. The
success callback will be called after the successful completion of the AJAX call.

The response returned by the server will be passed along to the success
callback. On the other hand, the failure callback will be called if something
goes wrong and there was an issue performing the AJAX call.
So as you can see, it's easy to perform 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 to perform AJAX calls.
In the next section, we’ll see a real-world example to understand how this all
works with PHP.
A Real-World AJAX Example 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 start with, let's make the index.php file, as shown in
the following snippet, which renders a basic login form.
<!doctype html>

<html>

<head>

<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7Mb
</head>

<body>


<form id="loginform" method="post">

<div>

Username:

<input type="text" name="username" id="username" />

Password:

<input type="password" name="password" id="password" /> 

<input type="submit" name="loginBtn" id="loginBtn" value="Login" />

</div>

</form>

<script type="text/javascript">

$(document).ready(function() {

$('#loginform').submit(function(e) {

e.preventDefault();

$.ajax({

type: "POST",

url: 'login.php',

data: $(this).serialize(),

success: function(response)

{

var jsonData = JSON.parse(response);

// user is logged in successfully in the back-end

// let's redirect

if (jsonData.success == "1")

{

location.href = 'my_profile.php';

}

else


{

alert('Invalid Credentials!');

}

}

});
});
});
</script>

</body>

</html>
The index.php file is a pretty standard HTML form which contains username
and password fields. It also contains a jQuery JavaScript snippet, which follows
the outline we saw above.
We've used the  submit  event of the form element, which will be triggered when
a user clicks on the submit button. In that event handler, we've initiated the
AJAX call, which submits the form data to the login.php file using the POST
method asynchronously. Once we receive a response from the server, 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.
<?php

if (isset($_POST['username']) && $_POST['username'] && isset($_POST['passw
// do user authentication as per your requirements


// ...
// ...
// based on successful authentication

echo json_encode(array('success' => 1));

} else {

echo json_encode(array('success' => 0));

}
The login.php file contains the logic of authenticating users and returns
a JSON response based on the success or failure of login.
Advertisement
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
show how to use it with the  then  method.
...
...
$.ajax({

type: "POST",

url: 'login.php',

data: $(this).serialize()

}).then(

// resolve/success callback

function(response)

{

var jsonData = JSON.parse(response);

// user is logged in successfully in the back-end

// let's redirect

if (jsonData.success == "1")

{

location.href = 'my_profile.php';

}

else

{

alert('Invalid Credentials!');

}


},

// reject/failure callback

function()

{

alert('There was some error!');

}

);

...
...
Conclusion
In this tutorial, we 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 real-world example which
demonstrated how you can use AJAX to fetch server-side PHP content
Learn PHP With a Free Online Course
If you want to learn PHP, check out our free 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 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 most important skills
for writing apps for the web: you'll get a chance to practice responding to GET
and POST requests, parsing JSON, authenticating users, and using a MySQL

database.
PHP Fundamentals
Jeremy McPeak
29 Oct 2021
You can also learn JavaScript for free on Envato Tuts+! JavaScript is the
language of the web. If you want to code for the web, you need to know
JavaScript inside and out. From humble beginnings, JavaScript has grown to a
powerful and complex language with features such as classes, promises, arrow
functions, generators, string 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!
Modern JavaScript
Fundamentals
Dan Wellman
12 Dec 2019
Did you find this post useful?
 
Yes  
No

Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new
Code tutorials. Never miss out on learning about the next big thing.
Sign up
Sajal Soni
Software Engineer, FSPL, India
I'm a software engineer by profession, and I've done my engineering in
computer science. It's been around 14 years I've been working in the
field of website development and open-source technologies. 

Primarily, I work on PHP and MySQL-based projects and frameworks.
Among them, I've worked on web frameworks like CodeIgnitor,
Symfony, and Laravel. Apart from that, I've also had the chance to work
on different CMS systems like Joomla, Drupal, and WordPress, and e-
commerce systems like Magento, OpenCart, WooCommerce, and
Drupal Commerce.

I also like to attend community tech conferences, and as a part of that, I

LOOKING FOR SOMETHING TO HELP KICK START YOUR NEXT PROJECT?
Advertisement
attended the 2016 Joomla World Conference held in Bangalore (India)
and 2018 DrupalCon which was held in Mumbai (India). Apart from this,
I like to travel, explore new places, and listen to music!
sajalsoni
 FEED  LIKE  FOLLOW

Envato Market has a range of items for sale to help get you started.
WordPress Plugins
From $5
PHP Scripts
From $5
Unlimited Downloads

From $16.50/month
Get access to over one million creative
assets on Envato Elements.
Over 9 Million Digital Assets
Everything you need for your next
creative project.

QUICK LINKS
ENVATO TUTS+
About Envato Tuts+
Terms of Use
Advertise
JOIN OUR COMMUNITY
Teach at Envato Tuts+
Translate for Envato Tuts+
Forums
HELP
FAQ
Help Center
- Explore popular categories
30,703
Tutorials
1,316
Courses
50,290
Translations
Envato Envato Elements Envato Market Placeit by Envato Milkshake All
products Careers Sitemap
© 2022 Envato Pty Ltd. Trademarks and brands are the property of their respective owners.


More Related Content

Similar to How to Use AJAX in PHP and jQuery.pdf (20)

Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
RicoAjaxEngine
RicoAjaxEngineRicoAjaxEngine
RicoAjaxEngine
 
RicoAjaxEngine
RicoAjaxEngineRicoAjaxEngine
RicoAjaxEngine
 
Ajax part i
Ajax part iAjax part i
Ajax part i
 
Copy of ajax tutorial
Copy of ajax tutorialCopy of ajax tutorial
Copy of ajax tutorial
 
M Ramya
M RamyaM Ramya
M Ramya
 
Ajax3
Ajax3Ajax3
Ajax3
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Html web workers
Html web workersHtml web workers
Html web workers
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
Extending Ajax Events for all mankind
Extending Ajax Events for all mankindExtending Ajax Events for all mankind
Extending Ajax Events for all mankind
 

Recently uploaded

HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 

Recently uploaded (20)

🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 

How to Use AJAX in PHP and jQuery.pdf

  • 1. 7 days of WordPress plugins, themes & templates - for free!* Start 7-Day Free Trial  Advertisement Code  PHP How to Use AJAX in PHP and jQuery Sajal Soni Sep 28, 2020 (Updated Nov 27, 2021)  23 likes  Read Time: 10 mins  English PHP REST API Ajax JavaScript jQuery Today, we’re going to explore the concept of AJAX with PHP and JavaScript. The AJAX  technique helps you to improve your application's user interface and enhance the overall end user experience. | |  
  • 2. What Is AJAX? AJAX stands for Asynchronous JavaScript and XML, and it allows you to fetch content from the back-end server asynchronously, without a page refresh. Thus, it lets you update the content of a web page without reloading it. Let’s look at an example to 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 like personal information, social information, notifications, messages, and so on. The usual approach would be to build different web pages for each section. So How to Use AJAX in PHP and jQuery 
  • 3. The usual approach would be to build different web pages for each section. So for example, 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 wait for the browser to reload and the page to render again 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 case, you can display different tabs for all sections, and by clicking on the tab it fetches the corresponding content from the back-end server and updates the page without refreshing the browser. This helps you to improve the overall end-user experience. The overall AJAX call works something like this: 
  • 4. Let’s quickly go through the usual AJAX flow: 1. First, the user opens a web page as usual with a synchronous request. 2. Next, the user clicks on a DOM element—usually a button or link—that initiates an asynchronous request to the back-end server. The end user won’t notice this since the call is made asynchronously and doesn’t refresh the browser. However, you can spot these AJAX calls using a tool like Firebug. 3. In response to the AJAX request, the server may return XML, JSON, or HTML string data. 4. The response data is parsed using JavaScript. 5. Finally, the parsed data is updated in the web page's DOM. So as you can see, the web page is updated with real-time data from the server without the browser reloading. In the next section, we’ll how to 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 to do AJAX calls, but it’s always interesting to know what’s happening under the hood. 
  • 5. Let’s have a look at the following vanilla JavaScript code, which performs the AJAX call and fetches a response from the server asynchronously. <script> var objXMLHttpRequest = new XMLHttpRequest(); objXMLHttpRequest.onreadystatechange = function() { if(objXMLHttpRequest.readyState === 4) { if(objXMLHttpRequest.status === 200) { alert(objXMLHttpRequest.responseText); } else { alert('Error Code: ' + objXMLHttpRequest.status); alert('Error Message: ' + objXMLHttpRequest.statusText); } } } objXMLHttpRequest.open('GET', 'request_ajax_data.php'); objXMLHttpRequest.send(); </script> Let’s go through the above code to understand what’s happening behind the scenes. 1. First, we initialize the  XMLHttpRequest  object, which is responsible for making AJAX calls. 2. 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 . 3. We can set up a listener function for state changes using 
  • 6. 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. 4. In that function, we’ve checked if the  readyState  value equals  4 , which means the request is completed and we’ve got a response from the server. Next, we’ve checked if the status code equals  200 , which means the request was successful. Finally, we fetch the response which is stored in the  responseText  property of the  XMLHttpRequest  object. 5. After setting up the listener, we initiate the request by calling the  open  method of the  XMLHttpRequest  object. The  readyState  property value will be set to 1 after this call. 6. Finally, we’ve called the  send  method of the  XMLHttpRequest  object, which actually sends the request to the server. The  readyState  property value will be set to 2 after this call. 7. When the server responds, it will eventually set the  readyState  value to 4, and you should see 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, we'll see how to use the  Promise  object for AJAX. How to Use JavaScript Promises for AJAX Promises in JavaScript provide a better way to manage asynchronous 
  • 7. operations and 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 the resolved or rejected state. Let's quickly revise the previous example with the  Promise  object. function AjaxCallWithPromise() { return new Promise(function (resolve, reject) { const objXMLHttpRequest = new XMLHttpRequest(); objXMLHttpRequest.onreadystatechange = function () { if (objXMLHttpRequest.readyState === 4) { if (objXMLHttpRequest.status == 200) { resolve(objXMLHttpRequest.responseText); } else { reject('Error Code: ' + objXMLHttpRequest.status + ' Error Messag } } } objXMLHttpRequest.open('GET', 'request_ajax_data.php'); objXMLHttpRequest.send(); }); } AjaxCallWithPromise().then( 
  • 8. data => { console.log( Success Response: + data) }, error => { console.log(error) } ); When the  AjaxCallWithPromise  function is called, it returns the promise object, and it's in the pending state initially. Based on the response, it'll call either the  resolve  or  reject  function.  Next, we use the  then  method, which is used to 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 callback for the rejected state. So that's how you can use 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 earlier section, we discussed how you could perform AJAX calls using vanilla JavaScript. In this section, we’ll use the jQuery library to demonstrate this. I'll assume that you’re aware of the basics of the jQuery library. The jQuery library provides a few different methods to perform AJAX calls, although here we’ll look at the standard  ajax  method, which is the most often used. 
  • 9. Take a look at the following example. <script> $.ajax( 'request_ajax_data.php', { success: function(data) { alert('AJAX call was successful!'); alert('Data from the server' + data); }, error: function() { alert('There was some error performing the AJAX call!'); } } ); </script> As you already know, the  $  sign is used to refer to a jQuery object. The first parameter of the  ajax  method is the URL that will be 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 the  ajax  method. In most cases, you will need to specify the success and error callbacks. The success callback will be called after the successful completion of the AJAX call. 
  • 10. The response returned by the server will be passed along to the success callback. On the other hand, the failure callback will be called if something goes wrong and there was an issue performing the AJAX call. So as you can see, it's easy to perform 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 to perform AJAX calls. In the next section, we’ll see a real-world example to understand how this all works with PHP. A Real-World AJAX Example 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 start with, let's make the index.php file, as shown in the following snippet, which renders a basic login form. <!doctype html> <html> <head> <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7Mb </head> <body> 
  • 11. <form id="loginform" method="post"> <div> Username: <input type="text" name="username" id="username" /> Password: <input type="password" name="password" id="password" /> <input type="submit" name="loginBtn" id="loginBtn" value="Login" /> </div> </form> <script type="text/javascript"> $(document).ready(function() { $('#loginform').submit(function(e) { e.preventDefault(); $.ajax({ type: "POST", url: 'login.php', data: $(this).serialize(), success: function(response) { var jsonData = JSON.parse(response); // user is logged in successfully in the back-end // let's redirect if (jsonData.success == "1") { location.href = 'my_profile.php'; } else 
  • 12. { alert('Invalid Credentials!'); } } }); }); }); </script> </body> </html> The index.php file is a pretty standard HTML form which contains username and password fields. It also contains a jQuery JavaScript snippet, which follows the outline we saw above. We've used the  submit  event of the form element, which will be triggered when a user clicks on the submit button. In that event handler, we've initiated the AJAX call, which submits the form data to the login.php file using the POST method asynchronously. Once we receive a response from the server, 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. <?php if (isset($_POST['username']) && $_POST['username'] && isset($_POST['passw // do user authentication as per your requirements 
  • 13. // ... // ... // based on successful authentication echo json_encode(array('success' => 1)); } else { echo json_encode(array('success' => 0)); } The login.php file contains the logic of authenticating users and returns a JSON response based on the success or failure of login. Advertisement Using Promises for AJAX With jQuery Apart from this, the  $.ajax  method supports JavaScript Promises as well. It 
  • 14. 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 show how to use it with the  then  method. ... ... $.ajax({ type: "POST", url: 'login.php', data: $(this).serialize() }).then( // resolve/success callback function(response) { var jsonData = JSON.parse(response); // user is logged in successfully in the back-end // let's redirect if (jsonData.success == "1") { location.href = 'my_profile.php'; } else { alert('Invalid Credentials!'); } 
  • 15. }, // reject/failure callback function() { alert('There was some error!'); } ); ... ... Conclusion In this tutorial, we 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 real-world example which demonstrated how you can use AJAX to fetch server-side PHP content Learn PHP With a Free Online Course If you want to learn PHP, check out our free 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 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 most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL 
  • 16. database. PHP Fundamentals Jeremy McPeak 29 Oct 2021 You can also learn JavaScript for free on Envato Tuts+! JavaScript is the language of the web. If you want to code for the web, you need to know JavaScript inside and out. From humble beginnings, JavaScript has grown to a powerful and complex language with features such as classes, promises, arrow functions, generators, string 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! Modern JavaScript Fundamentals Dan Wellman 12 Dec 2019 Did you find this post useful?  Yes  No 
  • 17. Want a weekly email summary? Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing. Sign up Sajal Soni Software Engineer, FSPL, India I'm a software engineer by profession, and I've done my engineering in computer science. It's been around 14 years I've been working in the field of website development and open-source technologies. Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I've worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I've also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e- commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce. I also like to attend community tech conferences, and as a part of that, I 
  • 18. LOOKING FOR SOMETHING TO HELP KICK START YOUR NEXT PROJECT? Advertisement attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music! sajalsoni  FEED  LIKE  FOLLOW 
  • 19. Envato Market has a range of items for sale to help get you started. WordPress Plugins From $5 PHP Scripts From $5 Unlimited Downloads From $16.50/month Get access to over one million creative assets on Envato Elements. Over 9 Million Digital Assets Everything you need for your next creative project. 
  • 20. QUICK LINKS ENVATO TUTS+ About Envato Tuts+ Terms of Use Advertise JOIN OUR COMMUNITY Teach at Envato Tuts+ Translate for Envato Tuts+ Forums HELP FAQ Help Center - Explore popular categories 30,703 Tutorials 1,316 Courses 50,290 Translations Envato Envato Elements Envato Market Placeit by Envato Milkshake All products Careers Sitemap © 2022 Envato Pty Ltd. Trademarks and brands are the property of their respective owners. 