I have data coming from MySql, answered from this:
How to SQL query parent-child for specific JSON format?. Basically I query it using JSON_OBJECT() which produces the result:
results <-- The column name
{"projects": "project_name": "project 1", [2nd layer stuff]} <-- the row
Awesome. MySql did the json thing for me. I make an ajax call to a PHP function to get this onto the web server.:
myPhpFunction () {
//some usual PDO code
echo json_encode($query_result);
}
On JS, I make a jQuery ajax call:
var ajaxRequest =
$.ajax({
type: 'post',
url: '../includes/ajax.php',
data: 'action' : 'myPhpFunction',
dataType: 'json'
});
ajaxRequest.done(function(data) {
//$.each(data[0].results.projects, function(key, val){
//I want to access each stuff in the object here
//}
$('#ph-projects').append(JSON.stringify(data)); //testing it out
}
The problem I'm having is by this time, my object data outputs like this:
{ "results": "{...}" }
results value is a string because of those double quotes!
This is driving me crazy. Am I missing a step to prevent this from happening?
The json_encode() is working fine as it is providing the result as a JSON object as suggested by your question({ "results": "{...}" }). And JSON_OBJECT() in PDO returning a string is fine as the name JSON suggests, its JavaScript Object Notation in a humanly readable format.
You can do on the server side:
json_encode(['results'=> json_decode($query_result['results'])]);
or on client side,
function(data){
data.results = JSON.parse(data.results);
// Your json data here
}
Related
I have 3 different JSON objects I want to concatenate and send over to a PHP file with jQuery AJAX. I can retrieve the JSON object in the PHP file, but cannot figure out how to loop through the results.
Here's what I have so far:
//my 3 JSON objects:
var json_obj_1{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
}
var json_obj_2{
"test4_key":"test4_val"
}
var json_obj_3{
"json_arr":[
{
"test1":"test2",
"test3":"test4"
}
]
}
//concat these to send over to the PHP file:
var my_json_obj = json_obj_1.concat(json_obj_2);
//I found if I didn't stringify obj_3 they didn't concatenate for some reason
my_json_obj = my_json_obj.concat(JSON.stringify(json_obj_3));
//my_json_obj now looks like this:
{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
}
{
test4_key: test4_val
}
{
"json_obj_3":[
{"test1":"test2","test3":"test4"}
]
}
Based on this question: Sending JSON to PHP using ajax, I don't stringify the final JSON object.
Here's the AJAX call to the PHP file:
$.ajax({
url: 'my_php_file.php',
data: {my_json_data: my_json_obj},
type: 'POST',
async: false,
dataType: 'json',
cache:false,
success:function(data, textStatus, jqXHR){
console.log('AJAX SUCCESS');
},
complete : function(data, textStatus, jqXHR){
console.log('AJAX COMPLETE');
}
});
This is what it looks like when retrieved in my PHP file:
echo $_POST['my_json_data'];
//outputs:
{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
}
{
test4_key: test4_val
}
{
"json_obj_3":[
{"test1":"test2","test3":"test4"}
]
}
Here's where I run in to problems. I want to be able to loop through this in a foreach. From what I have read (php: loop through json array) I have to decode the JSON object. However when I do this and loop through the results I get: " PHP Warning: Invalid argument supplied for foreach() ".
Even if I stringify the JSON object before sending it over to the PHP file I get the same problem. I have been banging my head against a brick wall for hours with this. Any help will be massively appreciated.
Thanks in advance.
Solved:
I was going wrong when concatenating my JSON objects following this question: Merge two json/javascript arrays in to one array. Instead I just put them together like so:
my_json_obj = '['+json_obj_1+','+json_obj_2+', '+JSON.stringify(json_obj_3)+']';
I then use json_decode in my PHP file which works a treat. http://json.parser.online.fr/ was invaluable in debugging my dodgy JSON. A great tool for JSON beginners.
You should be stringifying the whole object, try the following:
var my_json_obj = json_obj_1;
$.each(json_obj_2, function(key,value){
my_json_obj[key]=value;
});
$.each(json_obj_3, function(key,value){
my_json_obj[key]=value;
});
Ajax request:
data: {my_json_data: JSON.stringify(my_json_obj)},
PHP:
print_r(json_decode($_POST['my_json_data']));
As you say you need to decode the JSON, but your JSON is not well formed so I think the decode function is failing which causes the foreach error. There needs to be a , between objects, there's missing quotes around test4_val and it needs to be inside a singular object/array
You can check your JSON is wellformed at:-
http://json.parser.online.fr/
I think you want it to look more like:-
[{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
},
{
"test4_key": "test4_val"
},
{
"json_obj_3":[
{"test1":"test2","test3":"test4"}
]
}]
Hello I have a problem with my ajax request in jquery.
When I use my get request without sending any data the response is as expected, I receive my array and can access the values:
$.get(
loadUrl,
function(data) {
useReturnData(data);
},
"json"
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
This works as expected and I recieve my value of "528" being my leftPlayer[4] value.
But when I change my request to send a piece of data to php in the request like so:
$.get(
loadUrl,
{ type: "left" })
.done(function(data) {
useReturnData(data);
},
"json"
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
My data received seems to be in string format to javascript.
My alert prints "5" (the 4th character if the array was a string)
When alerting leftPlayer. I find that in the first request in which I send no data the variable is printed as: 355,355,355,355,528,etc...
Whereas in the second request in which I DO send data it prints as:
[355,355,355,355,528,etc...]
Notice the []. It isn't recognised as an array.
The php file it accesses has absolutely no changes in each request, as I am testing at the moment. The data sent isn't even used in the php file at the moment.
Any ideas where I'm going wrong?
I've fixed my problem.
Like what "nnnnnn" said in his comment I'm passing my "json" parameter to the .done() function instead of the $.get() function.
I couldn't seem to get it to correctly view it as JSON though so I used the easiest method:
$.getJSON(
loadUrl,
{ type: "left" },
function(data) {
useReturnData(data);
}
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
Using $.getJSON instead does like what it says and expects JSON to be returned as default.
So i have this piece of javascript, it posts to foo.php with value val, gets back data, empties the container and call function graph which will fill the container with a new chart.
$.post("foo.php", {val: val}, function(data){
if(data.length >0) {
$('#container').html('');
graph(data);
}
});
in foo.php, how do I make it pass back an array instead of string? at the moment I just have an echo in foo.php that echos the data delimited by a comma, ie: 1,2,3,4,5. then in the graph function I have a split(',' data) that creates an array for later use.
I mean, all this works fine, I'm just wondering if I can avoid the split step and have foo.php return an array directly.
thanks!
That's what json_encode is for:
echo json_encode( $array );
Just remember to set JSON headers, so that jQuery will know to parse the returned data as JSON. If you don't, you'll have to specify that in your jQuery AJAX call as follows:
$.post("foo.php", {val: val}, function(data){
if (data.length > 0) {
$('#container').html('');
graph(data);
}
}, 'json'); // <-- Here you're specifying that it'll return JSON
json_encode your array in PHP and jquery can easily parse your JSON encoded data.
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);
});
I am using jQuery, AJAX and PHP to update the contents of a drop down box on an event. My code currently triggers the event and uses AJAX to call a PHP function which goes to the database and gets the records associated with each member of the drop down.
I can currently return this 2-dimensional array (an array of records with an array of columns in each one) back to my jQuery function but I am at a loss as to how to convert the array into something which I can use.
jQuery code to call AJAX:
var element= $('select[name=elementName]');
var data = 'inData=' + element.val();
// Call AJAX to get the info we need to fill the drop downs by passing in the new ID
$.ajax(
{
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
success:
function(outData)
{
// WHAT DO I DO HERE TO CONVERT 'outData' INTO A 2-DIMENSIONAL jQUERY ARRAY??
},
error:
function()
{
}
});
PHP code:
$sqlResults= mysql_query("SELECT data FROM table WHERE id='".$_POST['inData']."'");
$outData = array();
// Fill the data array with the results
while ($outData[]= mysql_fetch_array($sqlResults));
// echo the data to return it for use in the jQuery file
echo $outData;
The code posted is working fine - I just don't know how to read 'outData' in jQuery.
Thanks in advance for any help!!
Have you looked at json_encode?
echo json_encode($outData);
This will convert it into a json object that can be read by jQuery.
your looking for json
//php
echo json_encode($outData);
//javascript
$.ajax({
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
dataType: "json",
success: function(outData) {
console.log(outData); //this will be an object just like
//your php associative array
},
error: function() {
}
});
JSON can do the trick, but why not look at it from another angle?
If you're pinging PHP to get updated info, just have PHP output the option values you want in your select box. Then use the HTML return of jQuery AJAX to .html() the result into your select element.
There's a couple of different ways to skin a cat, and I would submit that this much easier approach is going to gain you extra time to do more jQuery wizardry.
jQuery can not read the echo of a PHP array. Use json_encode before you output it:
echo json_encode($outData);
That's a format jQuery actually can parse as the response.