Json_encode for .post? - php

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.

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.

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.

Related

PHP Unserialize data for use in array - sub standard characters in string

I am using a jQuery plugin of nestable forms and storing the order of these in a database using serialize (achieved through JS). Once I retrieve this data from the database I need to be able to unserialize it so that each piece of data can be used.
An example of the data serialized and stored is
[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]
The number of ID's stored in each serialized data varies and the JS plugin adds the [ and ] brackets around the serialization.
I have used http://www.unserialize.com/ to test an unserialization of the data and it proves successful using print_r. I have tried replicating this with the following code:
<?php
print_r(unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]'));
?>
but I get an error. I am guessing that I need to use something similar to strip_tags to remove the brackets, but am unsure. The error given is as follows
Notice: unserialize(): Error at offset 0 of 70 bytes
Once I have the unserialized data I need to be able to use each ID as a variable and I am assuming to do so I need to do something as:
<?php
$array = unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]');
foreach($array as $key => $val)
{
// Do something here, use each individial ID however
// e.g database insert using $val['id']; to get H592736029375 then K235098273598 and finally B039571208517
}
?>
Is anyone able to offer any help as to how to strip the serialized data correctly to have the ID's ready in an array to then be used in the foreach function?
Much appreciated.
PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.
It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.
Here's a fiddle
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}
Outputs:
0) H592736029375
1) K235098273598
2) B039571208517

json_encode Returning a PHP Array

So I am working with PHP to pass a PHP array over a jQuery Ajax request to another PHP page. This is quite the task. For some reason, my json_encode is returning an array instead of a string, I am not quite sure why. Here is my PHP code:
$new_spreadsheet = nl2br($_POST['spreadsheet']);
$new_spreadsheet = explode('<br />', $new_spreadsheet);
array_shift($new_spreadsheet);
$new_spreadsheet = array_values($new_spreadsheet);
echo json_encode($new_spreadsheet);
I would show you the output, but it is really long. Basically this is outputting a PHP array which consists of each row on the spreadsheet. This is what I want to have, but the problem is that I don't want the quotes and everything in the array. I am pretty sure I need to run json_decode, but when I do that my code returns an error saying that the parameter needs to be a string. I can tell something is not right, but am not quite sure what I need to change. I would appreciate any advice.
Update: At this point, when I try to loop through the array and print each value, the first array index is equal to a double quote like so: ". There are double quotes in random values throughout the area. I am not quite sure about what is causing this.
If I echo the rows from within the json_encoded PHP array onto the console, I get the following output:
"
correct value
correct value
correct value
"
You're using JSON, which means you have to adhere to somewhat more stringent syntax rules than Javascript's. e.g.
<?php
$arr = array('This' => 'is', 'an' => 'array in php');
echo json_encode($array);
?>
output:
{"This":"is","an":"array in PHP"}
There is NO way to avoid getting quotes on the values, as they're a fundamental requirement of JSON (and Javascript). If you don't want quotes, then don't use JSON.
try only br.
$new_spreadsheet = explode("<br>", $new_spreadsheet);
It will work. and json_enode can never return an array. try var_dump and check.Also make sure before you post, use htmlspecialcharacters.

send an Array from Android to PHP Script over HTTP and get the data

I would like to send an integer array with 30 values Integer[] temp = new Integer[30] over HTTP (POST) to PHP an get the data in PHP again. How can I do that? I know how to send a single value, like a string, but not how to send an array.
One way is to serialize the array in the way the php serialize command does it.
After receiving the string value(by the method you currently use), you can use the unserialize command to get the array in your php code.
Here is a litle php example to demonstrate the workflow.
$arr = array(1,2,3,4,5,6);
$stringArr = serialize($arr);
echo $stringArr;
echo "<br/>";
$arr2 = unserialize($stringArr);
if ($arr === $arr2)
{
echo "arrays are equal";
}
The output of the script is:
a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}
arrays are equal
The main difficulty is to construct the resulting string for complex structures (in your case, it is pretty straight forward for an array of integers).
This fact results in the second approach.
One can use a serialization API or another notation than used by the php example.
As stated by the others, JSON is one of the widespread notations.
PHP also provides a possibility to serialize and unserialize json objects.
Simply use json_decode and look at the example in the manual.

json multidimensional array and jquery?

I create this output with PHP:
foreach ($bk as $blink) {
$out["url"][] = $blink->url;
$out["anchor"][] = $blink->anchor;
}
$json = Zend_Json::encode($out);
echo ($json);
I want to receive and process the output with a $.ajax call.
Could you point me to a nice tutorial about multidimensional arrays with javascript/jquery or help me loop* through the json results? I got a bit confused with it.
I am trying to put those on a table, so I will be using <td>url-i</td><td>anchor-i</td> . This part, I figured out how. To put the correct values on url-i and anchor-i is the problem.
I would imagine the JSON output for that will be something like:
{'url': ['url1', 'url2', ... ],
'anchor': ['anchor1', 'anchor2', ... ]}
If that is the case, then they will be of equal length (and importantly equal indexes) and you can loop through one of the two using jQuery.each().
$.getJSON('jsonapp.php', function(data) {
$.each(data.url, function(index, url) {
var anchor = data.anchor[index];
$('#mytable').append('<tr><td>' + url + '</td><td>' + anchor +'</td></tr>');
});
});
I've not run that code, so it might have a few flaws, but that's the gist of it.
PHP can try to cast objects into arrays by itself, and for simple stuff, it usually works fine.
As for multidimensional arrays, Javascript isn't too different from most other higher-level programming/scripting languages when it comes to arrays. Really, any tutorial online on multidimensional arrays will do just fine. A multidimensional array is simply an array of arrays.
When you receive the string client-side, you just want to parse it. jQuery has its own method, but you can use JSON.parse. Afterwards, based on how you've set up your arrays, you'd want to do something like this.
<? $count = count($json_parsed['url']); for($i = 1; $i < $count; $i++) : ?>
<td><?=$json_parsed['url'][$i];?></td>
<td><?=$json_parsed['anchor'][$i];?></td>
<? endfor; ?>
This may be philosophically not the best way to do it though. If you have a whole bunch of objects and you want to make a table out of them, the best way would be to create an array of those objects as represented by associative arrays (sort of like hash tables in other programming languages). PHP natively tries to convert objects into associative arrays. I wouldn't be surprised if Zend_Json::encode does it automatically. If it does, you might want to pull simply:
echo Zend_Json::encode($bk);
If not, let me know, and we'll talk about how to do that.
You could have a look on any template frameworks, but for this exact case it seams useful to check one of those two: pure by beebole or jquery pure html templates.
Doing it by yourself might be tempting but why to reinvent the well - I know from my experience, that frameworks are about 2 times faster, then self made code.

exported json as string (not array)

Some have see that code :
<?php
echo stripslashes(json_encode(glob("photos-".$_GET["folder"].'/*.jpg')));
?>
it echo a really nice perfect string like that :
["photos-animaux/ani-01.jpg","photos-animaux/ani-02.jpg","photos-animaux/ani-02b.jpg","photos-animaux/ani-03.jpg","photos-animaux/ani-04.jpg","photos-animaux/ani-05.jpg","photos-animaux/ani-06.jpg","photos-animaux/ani-07.jpg","photos-animaux/ani-08.jpg","photos-animaux/ani-09.jpg","photos-animaux/ani-10.jpg","photos-animaux/ani-11.jpg","photos-animaux/ani-12.jpg","photos-animaux/ani-13.jpg","photos-animaux/ani-14.jpg"]
With json encode it shoul send a array so variable[0] should = to photos-animaux/ani-01.jpg
NOW it is only the fisrt caracter of the string..
how a array get converted to string, and how in javascipt to convert string to array to be able to get value [0] [1] etc..
the question is WHEN or WHY the perfect array get converted to string anyway ?
Using JSON.parse(), from the library available here, is preferable to using eval() since this only reads JSON strings and hence avoids the inherant security risks associated with eval().
In order to parse a JSON-encoded string into actual javascript objects, you need to eval() the data returned in order for javascript to execute against the data:
var data = eval(json_string)
Keep in mind that you should only ever run eval on a string when you trust the source and are sure that there is no possibility of a script injection attack, since javascript will run everything present in the string.
Use one of the JSON libraries listed at the bottom of http://json.org/
WHEN or WHY
If I understood correctly, the answer to both is json_encode(): check out the documentation. Converting a variable to a string (often called serialization or flattening) is a quite common operation.

Categories