6 Simple Steps to Learn AJAX with PHP using JavaScript [VIDEO]

6 Simple Steps to Learn AJAX with PHP using JavaScript [VIDEO]

Learn AJAX with PHP using JavaScript, In this article, you are going to learn AJAX basics. Even if you don’t know anything about AJAX. By end of this article, you will be able to work on your own AJAX projects. I’ve also included three projects at the end. So that you learn more about AJAX with those projects.

I’ve separated this into 6 steps.

  1. In the first step, you are going to learn about creating a simple Ajax Request sending & receiving data with GET/POST methods.
  2. In the second step, you will learn about using the console log to log messages in console log & the ready states.
  3. In the third step, you will learn about using different types data types with Ajax Request.
  4. In the Fourth step, you will learn about using Event Listeners with Ajax Request
  5. In the Fifth step, you will see a real example of Ajax request. That sends Ajax Request with GET & POST methods with input fields.
  6. In the final Sixth step, you will learn how to debug Ajax Request in PHP files.

Let’s get started learning Ajax with PHP.

1. Creating a Simple AJAX Request with JavaScript

In this first step, you are going to learn about creating a simple Ajax Request. So that this can be reused in other Scripts, this step is like basics to entire AJAX. If you understand this step, you can create Ajax functions on your own later after completing this.

Creating a Hello World Alert with Javascript – JS Basics

First of all, we will start with displaying a simple alert message with JavaScript using script tags. Use this code in head section of your HTML page after the title tag.

After adding this code, you should see an alert message in your browser after loading this HTML page.

You can use the same script tag before the closing body tag, you can use it in both the places.

Here we will see one more method, that is executing this alert message on click event of a button. Just add this button code inside the body tag.

After loading this page in the browser, you will see a button. Click on the button to execute this alert message.

We can wrap this alert message code inside JavaScript function. So that we can execute this on click event of the button. Use this JavaScript function in script tags, you can use it in head section or body section.

And Update the button code, with this below code. It works similar to our previous button except that here I’m using a function to execute the alert message.

We are going to use these JavaScript functions until learning about Event Listeners.

Creating Simple AJAX Request

For creating a simple Ajax Request, we need these three. XMLHttp Object, Open function and Send function. These are the most basic elements for forming Ajax Request.

Here is the code for creating XMLHttp Object, Here I’m using xhr as a variable, you can use xmlhttp or any other variable.

Next is open function, Open function serves as configuration to XMLHttpRequest Object. In this function, we should pass three arguments. First argument is the method, that is either GET method or POST method. Here in this case, I’m using the GET method.

Second argument is the file name, it’s either HTML/PHP or text file. Third argument is an asynchronous request, it’s boolean true or false. It will be always true because it is an asynchronous request, that means request will be sent in the background.

Next is the Send function, send functions is to send the request asynchronously to ajax.php with GET or POST method. We will use send function to send the values with POST method, we will see this later.

If you combine all these three statements then you can create simple Ajax Request, we will see it in next step.

Sending Data in AJAX Request with GET Method

By combining all the three statements we can create a simple Ajax Request with GET method. We will also see how to pass values using GET method to PHP file.

We can pass the values using GET method to PHP file, You can see an example in the below code.
Here I’ve created a variable with the name of url, with the URL variable I’m passing the values in URL.

Now you know, how to pass the values in URL with GET method. In next step, we will see how to pass values in POST method.

Sending Data in AJAX Request with POST Method

For creating Ajax Request with POST method, we can just change the method in open function to POST method from GET method. And we will pass the values to PHP file through send function.

While using post method we should change the headers with setRequestHeader function. We will set the content type to “application/x-www-form-urlencoded” only while using POST method.

Here is the code for Ajax Request with POST method.

By using above code, you can send Ajax Request with POST method.

Receiving Response with AJAX

Till now we have seen sending data in Ajax Request. In this step, we will see receiving the response and update it in our HTML file.

We can receive the response using responseText and responseXML. responseText function while working with text, HTML, any string. responseXML function while working with XML.

We will assign the response to a variable, here is an example code.

responseText

responseXML

Next we should update the HTML, for this we should find the element with the id. Create a Div element with id ajax. And now we can find this div element with id ajax using document.getElementById

Updating HTML is simple, we have to use innerHTML on the target element.

By combining all the above lines of code into our ajax JavaScript function, we can create a successful ajax request.

By using above code, we won’t be able to update the HTML because to update the HTML we should check the readystates. We will see it in next step.

Knowing About ReadyStates

For updating the HTML, we should use the readystate. If the readystate is certain level then only we will update the HTML.

These are five ready states :

  • 0 : Connection created but not opened
  • 1 : Connection opened
  • 2 : Request sent, received by server
  • 3 : Response in progress (partial data)
  • 4 : Response complete (success or failure)

With onreadystatechange function, we can check if the readystate is 4 and the server response code is 200 then we will continue to update the HTML.

Here is the code to update the HTML after reaching the correct readystate.

By using this above code in our JavaScript ajax function, we can create a successful ajax request, we will see it in next step.

AJAX Example Code

Till now we have learned all the basics to create a successful ajax request. In this step, we will see working ajax code.

Create a new file and save it as ajax.php, just add any simple line of text. This text will be displayed in HTML file after making the ajax request.

Now after loading the file and clicking the button, you should see the text from the ajax.php file in the div element with id ajax.


Learn AJAX with PHP : 3 Projects


You will Learn Ajax from scratch and able to Build these 3 projects (Country State, Search Suggestion, CRUD Application)

2. Using Console Log

We can use console log to log the messages in the console so that we can see these messages in browser. With these console messages, we will know where we are with the code and what’s happening in the background.

You can use this code to log messages into the console with responseText

We can do one more thing that is logging the ready states in our ajax function. Use this below code to see all the readystates

3. Getting different types of data from PHP file

In this step, you will learn about working with different types of data types in Ajax & PHP.

First of all, we will see how to use HTML & PHP, then we will go into using PHP Arrays. And finally JSON formatted Data.

Using HTML & PHP to return Data

In ajax.php file we can use HTML & PHP. There is no trick here, Just add the HTML code or PHP code.

In the same way, we can use PHP code same as we do it in PHP files. And the most important thing in PHP code is don’t forget to use echo. It’s mandatory to use echo for returning the output.

With the above statements, you should understand how to use HTML & PHP with Ajax Request.

Using Arrays in PHP

In this step, you will learn how to use arrays with Ajax, if you have experience in PHP. It is similar to what you do with PHP.

Here are creating an array of names with the file name as arrays.php, update this file name in the open function.

Then I’ll create an HTML list items using for each loop inside the arrays.php file.

Finally, we should update the div element to unordered list or ordered list, based on your requirement. So that the list items will be displayed in HTML document.

Using JSON Formatted Data

Above two steps are similar, if you know a little bit of PHP. But for using JSON, you should know how to use it.

I’m using this names array to use these names individually. Save this file as json.php

This the same like previous step, but we should convert this array into JSON object using json_encode PHP function.

Finally, don’t forget to use echo for sending the response to ajax function.

Now in ajax function, this response is treated as simple text. I’m updating the HTML div with id ajax-result.

Here in above HTML, I’m going to update the text of id author from the JSON object. For that we should convert the response to JSON object, we will see how you can do that.

By using the above code, you will see that entire response from json.php file is getting updated.

To fix this, we should convert the response to JSON object.

After above code, you should see the response with a name. You can update the pocket name so that you will see the change in names.

4. Adding Event Listener

Instead of executing JavaScript function on click event of the button. We can make it better by adding an Event Listener. First of all, I’ll update the button code by removing onclick event and adding an id with ajax-button.

Here is the button code.

Then we should add Event Listener by just finding the button element with document.getElementById. Here is the code to add Event Listeners, It’s always good to use Event Listeners than the previous code.


Learn AJAX with PHP : 3 Projects


You will Learn Ajax from scratch and able to Build these 3 projects (Country State, Search Suggestion, CRUD Application)

5. Real Examples of AJAX Request

In this step, we will see how to create a Real example of Ajax Request with GET & POST using the input field. We will apply all the techniques learned in the previous steps.

Let’s start it with sending values in URL with GET method.

Submitting AJAX Request with GET Method

Here we will learn to send values in URL with GET and using this values in the PHP file and receiving the response and updating it the HTML document.

We have already created the div element with id ajax, I’m going to use this element to update the content from PHP file.

And I’m going to use the ajax.php file we created in previous sections with name variable assigned with GET superglobal.

Inside JavaScript function Ajax, I’m creating a variable with the name or URL. With this url, I’m passing the name value. And I’ll use this variable url in open function.

Here is the code that it looks like

And the entire function code, you can replace it with the previous code.

In the above code, I’m passing a static value in URL, I’ll convert this into submitting values through form input field.

Using Input Field to Submit AJAX Request with GET Method

In this step, we will see how to use the input field to submit values with GET method.

Our code remains same, but we just need to migrate it to work with the input field.

First of all, I’m going to add the input field before the submit button and your code should look like this.

We should get this input fields value after executing the ajax function. We can get this value with the value attribute of the input field.

First I’m finding the input element with id and assigning it to a variable, then with the variable, I’m going to assign the value to a new variable. Finally, we will use this variable nameVal to pass the values.

This the complete code of the ajax function.

In the above code, I’m using GET method. In the next step, we will see it with POST method.

Using Input Field to Submit AJAX Request with POST Method

In this step we are going to submit a request with the POST method, previously we have seen how to submit POST request with values.

For POST request we should change the content type with setRequestHeader function.

Here is the code

We will pass the values with POST method in Send function.

With above code, you should successfully send POST request and the response should be updated inside HTML if you are following from the previous steps.

Now we should make the change to send the values from the input field instead of the manual value.

And the complete code of the Ajax Function

6. Debugging AJAX Request

To debug any values in PHP code, just use echo with the return. So the rest of the code won’t be processed, you will be able to see the value in the variable.

This is example code in ajax.pho file

I hope you learned a lot about Ajax with PHP, I’ve also created these 3 projects. You can explore them to gain more knowledge in Ajax.

If you have any doubts & queries, feel free to leave comments.

Learn AJAX with PHP : 3 Projects


You will Learn Ajax from scratch and able to Build these 3 projects (Country State, Search Suggestion, CRUD Application)

Related Posts
No related posts for this content
Vivek Vengala
 

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: