Passing Data with AJAX - Coding Cyber

Passing Data with AJAX

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.

Other Articles in Learn AJAX

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.

Vivek Vengala

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