Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Jackie Jen
Jackie Jen
2,723 Points

Below are examples of using ajax and json with php. can anyone telling me what the different?

Ajax Example: http://www.w3schools.com/php/php_ajax_database.asp

Json Example: http://www.w3schools.com/json/json_example.asp

I have search and read from google about ajax and json. And most of the answer is using ajax method can send data to, and retrieve data from, a server asynchronously (in the background) without refresh. And i found that it done by using XMLHttpRequest (API) to done it.

While for Json is a format of data file. and above example also using XMLHTTPRequest (API) to done it. since it using the XMLHTTPRequest it does not need to refresh the whole page to get data from server.

This is my problem and question have confused me a week. what situation i use ajax or json? since with XMLHTTPRequest i can use ajax to do the exactly same thing like json example doing.

Really appreciate if someone can solve my problem.

1 Answer

Sean T. Unwin
Sean T. Unwin
28,690 Points

AJAX is a method to send or retrieve data between the server and the client while JSON is a type of formatted data.

JSON is in the format of key/value pairings such as:

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

In the JSON example you linked to, when var response = JSON.parse(response); is used, once the data has been received by the browser, it is essentially putting the values into a javascript object so that each item can be accessed easily by calling the key name to get the value.

In each of the examples you can see within the php files how the script is formatting the output. The AJAX example is formatting the output as HTML so it's easy to deal with and is simply a matter of putting that where you want into the DOM since the browser doesn't have to do anything special to it. In the JSON example the returned data can be used in a more precise fashion by way of separation of that data.

So AJAX can involve JSON as a data type, but not all AJAX involves JSON and since JSON is a way data can be formatted it can be exclusive to AJAX as well. JSON is a tool whereas AJAX is a task.

I hope that helps to clarify some.

Jackie Jen
Jackie Jen
2,723 Points

Thanks Sean, great explanation