I am new to JSON,ofr a project of my own I need to send array of objects to the server. Basically, I have a Question object, which has a couple of properties, like question, optionA, optionB etc. I have an array of Question objects.
example:
qArray = new Array();
qArray.push(new Question("where do you live?", "England", "ıtaly", "Usa");
I am adding a lot of questions objects to this array and in the end, I need to send this array to the server, like this:
$.post("backend-stuff/aj-save-test.php", { testName : $("#testName").val().toString(), 'questions' : JSON.stringify(qArray)}, function(result){
alert(result);
});
}
In PHP, I use this,
$questions = json_decode($_POST["questions"]);
$testName = $_POST["testName"];
Problem is that I cant read data, either I am sending it in the wrong way or whats wrong is on the php side.
Thank you for answers, I checked Google before sending the question, so please forgive me if this is so easy but for me its not so.
To convert stdClassObject to an array, check out get_object_vars().
Related
I've one working REST API developed using Slim PHP framework.
It's working absolutely fine.
The only issue is when there is no error present i.e. an array $errors is empty it comes as an array in JSON response but when the array $errors contains any error like $errors['user_name'] then it comes as an object in JSON response.
Actually I want to return the array when error is present. How should I do this? Can someone please help me in this regard?
Thanks in advance.
When your $errors is not empty, pass it through json_encode and echo it.
It will give you JSON object in return,
then convert JSON object into JavaScript array. (see the following code.)
var o = {"0":"1","1":"2","2":"3","3":"4"}; // your response object here
var arr = Object.keys(o).map(function(k) { return o[k] });
console.log(arr);
Recently got a close issue with Symfony's JsonResponse::create()
Turns out arrays with index not starting at 0 will be encoded into objects, as well as arrays with "holes", and probably any array with at least one non-int key.
In other word, arrays with anything else than consecutive numeric keys starting from index 0 seem to be encoded as object.
I guess this is designed to avoid sending big empty arrays when you map a handful of datas with big indices like [14334, 839493, 246193], and is probably documented somewhere.
Learning if this is a Symfony of json_encode behavior from comments would be welcomed addition :)
Note : Even if you return an array, it seems necessary to wrap it in an object for GET request to prevent some XSSI and JSON-JavaScript Hijacking.
I am still a beginner in PHP and MySQL and have come across a complicated array I need some help with.
So far the arrays I have worked with are fairly flat, i.e. 1 row of data with multiple fields, say for example a result based on a single address, so line1, line2, line3, town, etc.
I am now dealing with an external api that returns the following results in xml
{"result":
{
group1 [{"fieldname1":"fieldresult1", "fieldname2":"fieldresult2}]
group2 [{"fieldname3":"fieldresult3", "fieldname4":"fieldresult4}]
}
"message":"OK",
"success":true}
My question is how do I access each of the results,
I am planning on using a foreach statement, and will be calling the result $xmlarray.
I then want to define strings such as $field1, $field2, but not sure how to do this when it seems to be quite a deep array, I am guessing something like:
$field1 = $array([0]["field2"];
As I say, I need someones help just to give me a brief overview here, thanks
This content of you posted Data looks like JSON to me...
so you could try some like
$json = json_decode($array);
than you could go for
$field1 = $json['group1']['fieldname1'];
and so on.
source
This is not XML. It is json. Use json_decode() for this.
$data = json_decode($response); //$response is the response you are getting from the api.
var_dump($data);
$data will contain the response. The you can access them easily.json_decode()
I am trying to merge a static data with json encode array data for output. Here is my php code:
$arr = array();
$rs = mysql_query("SELECT id, name, picture, mail, gender, birthday FROM users WHERE id='$logged_id' ");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
Now I want to merge other data with it:
$user_ip = array("user_ip" => $user_ip_address);
I have tried array_merge($arr, $user_ip). But it didn't work. I think this is not correct json array format if I merge with existing data array. Please let me know what to do how to output other data as well as current data coming from mysql with json encode.
I am getting such output with my existing code, which is correct:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11"}]}
But now I want to add other variable e.g $user_ip_address as user's data joining with current output data like this:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11",user_ip:"127.0.0.1"}]}.
I want to get it in this way. How to do it? Please let me know. Thanks in advance.
try this:
echo json_encode(array('users' => $arr, 'user_ip' => $user_ip_address));
on a side note:
you should use PHP PDO class to connect and query the database.
mysql_fetch_object returns an object, not an array. So, what are you doing by $arr[] = $obj; is just adding an object into an array. So, the actual structure of the $arr is something like
$arr => [
[0] => Object(....),
[1] => Object(....),
....
]
In your particular case, I assume you are fetching single row by primary key, so there are only one object.
THe simpliest way to fix this is to add a field to an object. I haven't worked with PHP since 5.3, so can't be sure, but it's as simple as adding
$obj->user_ip = $user_ip_address;
inside the loop.
Btw, a couple of questions for you:
Why do you use loop if it should result in a single row?
Why you are embedding the variable directly into SQL query. It's quite vulnerable, read about sql-injections and how to prevent it (one day I was really tired telling people here on SO to use PDO and prepared statements, so just go read about it),
Have you read the documentation about mysql_fetch_object and array_merge? Why not (because if you have read it you wouldn't be asking the question).
Tried debugging? E.g. attaching a debugger and watching for variables contents? Inserting logging or (God forgive me) debug print with echo?
"Didn't work" is a quite bad error description. This time you was lucky, because the error was obvious. Next time, please, be more specific.
{"email":"test#example.com","timestamp":1346345321,"newsletter":{"newsletter_user_list_id":"3648511","newsletter_id":"613267","newsletter_send_id":"657025"},"category":["EST_TEST","Newsletter"],"event":"open"}
I'm having trouble parsing this string. It's from Sendgrid's Event API, it seems to be "almost" JSON, but json_decode won't work. My goal is to get the data into an array, then into a MySQL table. I'm not asking anyone to write the code for me, just point me toward the correct method. Do I use the explode function, then json_decode?.
(I'm slowly teaching myself PHP, sorry if the question is not clear)
I think you're not using the json_decode function with $assoc = true, so you're getting an object rather than an array
$json =
'{"email":"test#example.com","timestamp":1346345321,"newsletter":{"newsletter_user_list_id":"3648511","newsletter_id":"613267","newsletter_send_id":"657025"},"category":["EST_TEST","Newsletter"],"event":"open"}';
var_dump(json_decode($json, true));
You'll get the result as array;
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.