Multidimensional array via ajax to php turns into null via json_decode - php

I have gathered data with jQuery, putten it into a multidimensional array, used JSON.stringify on it and passed it to PHP by use of AJAX, for some reason json_decode keeps on giving me a Syntax error, malformed JSON error.
Heres the JSON that gets passed on to the PHP
[\"foo\",\"foobar did the baz\",[[\"bar\",\"kg\",\"200\"],[\"baz\",\"l\",\"1337\"]]]
The weird thing is that i use JSON.stringify on the multidimensional array in JS. Heres how i put it together
var dataz = [];
var arrayContainingAll = [];
$("li", "#ingredientlist").each(function() {
var tempArray = [];
tempArray.push($(".ingredientname", this).text());
tempArray.push($(".unittext", this).text());
tempArray.push($(".amounttext", this).text());
arrayContainingAll.push(tempArray);
});
dataz.push($("h1").text());
dataz.push($("#method").val());
dataz.push(arrayContainingAll);
var json = JSON.stringify(dataz);
How can i make PHP parse the multidimensional array correctly?
I have fixed it by passing on 3 different stringified arrays, but its more the curiosity of why a multidimensional array fails
The PHP to show what happens is: var_dump(json_decode($_POST['ingredients']));
because it appearantly is important to show how i post the data, heres the JS to do the ajax request
$.ajax({
url: '/api/savenewrecipe.php',
type: 'POST',
data: 'ingredients=' + json + "&name=" + $("h1").text() + "&method=" + $("#method").val(),
success: function(result) {
if (result.ok == true) {
// #todo remove this for debugging purposes
//document.location.href = '/recipe/' + result.id;
}
else {
showError("Noget gik galt!", 2000);
}
}
});

If your server uses magic quotes, you'll need to remove them:
if (get_magic_quotes_gpc()) {
$_POST['ingredients'] = stripslashes($_POST['ingredients']);
}

Related

how to receive ajax response as array in php [duplicate]

I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.
1) How can I return the JSON encoded string to the javascript?
2) How will the javascript loop through the rows and access their fields?
To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.
To loop through an array, I usually use jQuery.each():
var recordList = yourMethodToGetRecordListWithAjax();
jQuery.each(recordList, function()
{
alert(this.Name); // For example
});
1) in the php script:
$return["foo"] = "bar";
$return["blah"] = "bleg";
print json_encode($return);
2) in the javascript:
$.ajax({
type: "POST",
url: URL,
cache: false,
data: values,
dataType: 'json',
success: function(json) {
var foo = json.foo;
if (json.blah == "bleg") {
// do stuff
}
} // end success function
}); // end ajax call
You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.
See above answer for the rest.

How to access entry in the javascript object array

I assigned a JSON result from php to a javascript variable.
The result returned looks like below but it gives me undefined undefined
[{"a":"2","u":"jamesoduro","l":"Oduro","f":"James"},{"a":"5","u":"deary.grace","l":"Grace","f":"Dear"}]
I simple know this look like a javascript array with two objects.
I am trying to access the data inside the objects but to no avail.
Below is script:
PHP
<?php
//fetch online users
$array = array();
$sql = "SELECT id as a,username as u, lastname as l,firstname as f FROM users WHERE active =1 limit 2";
$q = mysqli_query($dbc_conn,$sql);
while($row = mysqli_fetch_assoc($q)){
$array[] = $row;
}
$json = json_encode($array);
echo $json;
?>
JQUERY
$(document).ready(function(){
//checking online users
setTimeout(function(){
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = response;
console.log(array[0].f +" "+ array[0].l);
}
});
},200);
});
Please what could be the problem?? Thank you
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = JSON.parse(response);
console.log(array[0].f +" "+ array[0].l);
}
});
You get a string from php , need turn the string into a json object .
You have to learn to debug your code to find what is going wrong I guess .
Try deserializing the response:
var array = JSON.parse(response);
EXPLANATION
The response you get from the ajax call is of type string, so you have to convert it to an object. That's what JSON.parse() method do: it parses the JSON string and creates the object that this string represent, following specific rules (The parsed string must be in a valid JSON format).
Keep your server side PHP script code neat and clean
Start PHP block from first character of first line.
Do not close php block if there is no output in HTML format.
Use ob_clean() function before echo output in is your are in developer mode and display error is enabled.
for example
ob_clean();
echo json_encode($array);
In client side, if you are getting JSON response in ajax, pass dataType:'json' in ajax option
$.ajax({
url:"testing.php",
type:"post",
dataType:"json",
success:function(response){
console.log(response[0].f +" "+ response[0].l);
}
});

PHP json_encode to Javascript undefined/null

I'm having an issue returning a JSON from PHP to Javascript. Below is my PHP to create the JSON:
$environment[] = array('id' => $env, 'adjacencies' => $hostnames);
foreach($hostnames as $hostname) {
$environment[] = array('id' => $hostname, 'name' => $hostname, 'data' => array());
}
return json_encode($environment);;
When I print the json_encode environment to a text file, it comes back as:
[{"id":"Dev","adjacencies":["tb23","tbwag","tbvg","tbut"]},{"id":"tb23","name":"tb23","data":[]},{"id":"tbwag","name":"tbwag","data":[]},{"id":"tbvg","name":"tbvg","data":[]},{"id":"tbut","name":"tbut","data":[]}]
It seems that this is printing out properly but when I return it to the Javascript its coming back as undefined/null. Below is the javascript with the ajax call:
var ajax = new AJAX();
var args = "id=" + $("#apps").val() + "&env=" + node.id + "&nocache=" + (new Date()).valueOf();
ajax.connect("POST", "http://" + window.location.hostname + "/project/graph/host", args, function(json) {
var output = '';
for (property in json) {
output += property + ': ' + json[property]+'; ';
}
alert(output);
});
I've obviously tried a lot of different things to get it to print out but haven't had any luck. In PHP, I've tried json_last_error and it came back as '0', which means that there isn't an issue with the JSON structure.
In the end, I'd like to use the following command in Javascript to continue building my graph:
var hostNodes = eval('(' + json + ')');
Any help is appreciated as to why I can't get this to come back!
Keep your PHP code in an unique file that receives one post parameters, then construct the json array if it set, and at the bottom you can do
echo json_encode($json);
flush();
I'm not a professional with pure javascript and I'm not familar with your approach, but you should consider using jQuery, at least I'm going to suggest one way to receive an json array so that you can easily work with it (you also make sure that the data is json):
$.ajax(
{
// Post select to url.
type : 'post',
url : 'myPHPAjaxHandler.php',
dataType : 'json',
data :
{
'select' : true
},
success : function(data)
{
// PHP has returned a json array.
var id, hostname;
for(var i = 0; i < data.length; i++)
{
id = data[i].id;
hostname = hostname[i].id;
// Construct a string or an object using the data.
}
},
complete : function(data)
{
// Optional.
}
});
Like I say, It's there for you to decide whether you pick it up or not. It can become handy for complex projects.
It looks like you're assuming that the data passed to the callback function will be your JSON already parsed into JS objects, but I don't see any indication that that would be the case; it's most likely the raw JSON data that must be parsed into JS objects using JSON.parse (NOT eval() - eval() is very dangerous, you should always prefer JSON.parse when working with true JSON data, as it will not permit XSS-style attacks as they are generally not "pure" JSON.)

Pass array from php back to javascript and loop over it

Hi I'm working on passing back an array from php to javascript. I learned online that I should use json_encode on the array when passing it back but now that i have it in the ajax i'm unsure how i can loop over it because doing things like response[0] gives me [ and response[1] gives me " although when writing the entire thing to the document using innerHTML i can see it looks like an array but using a for loop gives me each letter like i stated above with the response[0] equaling [ rather than the first entry. What am i doing wrong? Any help is greatly appreciated!
PHP
<?PHP
$link = mysql_connect('localhost', 'root', 'root');
mysql_select_db("Colleges");
$result = mysql_query("SELECT * FROM `Colleges` ORDER BY School");
$schools = array();
while ($row = mysql_fetch_array($result)) {
array_push($schools, $row['School']);
}
mysql_close();
die(json_encode($schools));
?>
Ajax
<script type="text/javascript">
function schools(){
$.ajax({
url: "Schools.php",
type: "POST",
success: function (response) {
//Loop over response
}
});
}
</script>
You should decode your JSON response (which is a string actually) to be able to work with it as with an object:
var respObj = JSON.parse(response);
The other way around is noticing jQuery that JSON will be supplied by the server (with either dataType: 'json' ajax parameter or Content-Type: application/json response header).
In the object you pass to the ajax method, you should try to add dataType: 'json' in order to specify that the result is json, or you could specify it in your php script calling header('Content-type: application/json'); before the call to die();
Doing so will result in your response being the object you expect instead of a string.
Finally, you could leave it as is, and call in your success callback response = $.parseJSON(response); which will take the response string and turn it into an object, see http://api.jquery.com/jQuery.parseJSON/
Use Following if it helps
res=jQuery.parseJSON(response);
for(i=0;i<res.length;i++)
{
alert(res[i].propertyname);
}
here property name implies to the keys on json .In your case it can be 'School' or just a number i or value can also be just res[i]
Javascript
for ( variable in response ) {
alert(results[variable]);
}
JQuery
$.each(response, function(ind, val){
alert("index:" + ind + ". value:" + val);
});

json object usage with ajax returned array

I have a problem with the returned array from ajax call.
the array is encrypted using json. it is as below
while ($found_course = mysql_fetch_assoc($sql)) {
$info[] = array(
'code' => $found_course['course_code'],
'name' => $found_course['course_name'] );
}
echo json_encode($info); //this is returned to javascript
then the problem is that I am unable to use the above array returned in javascript. I tried using the $.each method but to no avail. the eval() also do not work as it give output as [object object]. Can someone please help me with this.
All I want is to be able to acces the code and the name of the course saperately
Thanks.
Just loop through it with for()
for (var c in myAjaxArray){
myAjaxArray[c].code; // contains the code
myAjaxArray[c].name // contains the name
}
Make sure you set the dataType in the jQuery ajax call to "JSON" to make sure you have a json Object. Or use the $.getJSON() function.
<script>
var data = <?= json_encode($info); ?>;
for (var i = 0; i < data.length; i++) {
var item = data[i];
alert(item["code"] + " / " + item["name"]);
}
<script>
This should get you the data you need. Not sure how you tried using $.each but it should be in your success function on your ajax call. Also make sure the datatype is set to json.
success: function(data){
$(data).each(function(idx,val){
alert(val.code + " " + val.name);
})
}

Categories