PHP & # 8594; JS over AJAX - data types

I need to get array

from PHP

to JS

with help AJAX

.

I am using a standard ajax call and the data is returned as an object.

I can loop easily with Jquery

.

After reading many posts on the internet, it is common practice to send back JSON

.

My question is why use JSON

. If I were to use it, I would need to convert the array to JSON

PHP side (server side) and then parse it in JS (client side) to be able to loop through it.

Why use JSON

it if it requires additional steps, why not just parse the object from PHP

.

Am I missing something obvious here?

+3


source to share


3 answers


I am using a standard ajax call and the data is returned as an object.

No, it is not. The data is sent in some (possibly) text format (such as JSON).

Then some code converts it to an object. jQuery (for example) will do this automatically if the server sends back a header Content-Type: application/json

or if you specify dataType: "json"

in the parameters.

My question is why use JSON.

It:



  • based on JavaScript's native data model (which includes what programmers care about most: ordered arrays, collections of named objects, numbers, booleans, and strings)
  • just
  • well supported by libraries in many languages

Why use JSON when it takes extra steps, why not just parse the object with PHP.

You cannot pass an "object" back from PHP, because an object is simply a program that understands how a bunch of chunks of data in a computer's RAM are linked to each other.

Sending it to another computer will be akin to sending a thought to another brain's head.

You must first translate them into a common language that is transmitted.

+9


source


JSON - you're right - the way to go.

JSON is easy and fast to parse with JavaScript. JSON: JavaScript Object Notation.

Easier and faster to parse than xml, the old way back.



Json or XML, the reason why php object cannot be passed to JS ... But you can convert easily: json_encode (phparray)

Like this: json is so common for php and JS ...

0


source


The answer is pretty simple:

PHP is a server-side language that is interpreted by the PHP zend engine, where javascript is a client-side language that is interpreted by the javascript engine .

So the javascript engine cannot understand PHP objects , so we convert the PHP object to JSON objects which are understood by the PHP zend engine as well as the javascript engine .

0


source







All Articles