Lawrence
Lawrence

Reputation: 727

Json_encode for .post?

can anyone explain the purpose of json_encode when doing a .post query.

This is what i often see in other's coding.

.post php script

    ...
    ...

    echo json_encode($a);

I mean if i want to do a return from a .post script and returning an array via .post. Wouldn't i just need to do the following?

.post php script

    ...
    ...
    $a = array("foo", "bar", "hallo", "world");
    $string=implode(',',$a) in my php script        

    return $string;

javascript

    $.post('$url',function(data){
        data_arr=data.split(',');
        //After which just get the values in the array
        alert(data_arr[0]); //ALERTS 'foo'
        alert(data_arr[1]); //ALERTS 'bar'
    });

If anyone can just help by clearing this up for me and let me see the light for using json in this purpose, that would be great.

Perhaps its also due to my inept knowledge of JSON as well.

Would greatly appreciate it if anyone can advise me on why is it better to use JSON encode in this case and how am i suppose to use it via a .post request instead of just echoing out the string and split it later.

Thanks.

Upvotes: 2

Views: 3832

Answers (2)

Ignas
Ignas

Reputation: 1965

First of all, in my opinion and practise, JSON syntax is fairly similar to Javascript objects and it's great when dealing with more complex data types that have to be sent/requested and parsed later on.

For example: If you're doing a post request and you're serializing all the form fields which you validate server side (using PHP) you're most likely going to need to use key => value pairs like textbox_name => value. It's more logical to do it that way, than to select values by numeric indexes (what if the form layout changes?)

Example code using commas:

<?php
$array = array('Tom', 'Hanks', 'Football');
$string = join(',',$array);
echo $string; //it's obvious - the output is Tom,Hanks,Football
?>

The javascript that receives the string

$.post(url,{},function(data){
   var values = data.split(',')
   $("#name").text(values[0]);
   $("#surname").text(values[1]);
   $("#interests").text(values[2]);
});

So it makes sense right? But wouldn't it more sense to do this instead:

<?php
header('Content-type: application/json');
$array = array('name' => 'Tom', 'surname' => 'Hanks', 'interests' => 'Football');
echo json_encode($array);
?>

And the javascript:

$.post(url,{},function(data){
   for(index in data) {
      $("#"+index).text(data[index]);
   }
   //or
   $("#name").text(data.name);
   $("#surname").text(data.surname);
   $("#interests").text(data.interests);
});

The same goes with parsing response data with Javascript. Having an object is more logical than having a CSV string.

Obviously it depends on the use case, but in general JSON gives you a logical structure of stringified Objects/Arrays which can be translated back into objects and arrays and looped through or manipulated in any way.

Also JSON is now a standard. Everyone uses it which means that it's not for no reason. In other words - JSON data makes more sense.

Upvotes: 1

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70139

Using json_encode ensures that your data is always valid.

It doesn't really matter for simple data that you have control over, though imagine if someday you have a comma inside one of the values. With JSON encoded strings, you don't have to worry about an arbitrary separator token.

Also, with JSON you can easily encode Objects/Arrays without needing to reinvent the wheel.

Upvotes: 2

Related Questions