JSON object properties are undefined - php

I'm getting a JSON object back from an AJAX call and logging the result like this:
console.log(response);
And this is the response logged in the console:
{"filename":"new.jpg","orientation":"vertical"}
However, when I
console.log(response.orientation);
I get a response that it is undefined.
Most of the answers I've read indicate that an array was returned instead of an object and that response[0].orientation should work, but that is not the case here. When I assign the same array to another variable in the console:
var obj = {"filename":"new.jpg","orientation":"vertical"}
Then obj.orientation returns the correct value.
I'm creating the JSON object in PHP:
$response=array('filename' => $newfilename, 'orientation' => $orientation);
$response=json_encode($response);
echo $response;
Is it apparent why the properties are showing undefined?

Either put:
header("Content-type: application/jason");
in the PHP, specify dataType: "json" in the AJAX call in the JavaScript, or call JSON.parse.

You will need to parse your string to get a proper JSON object.
JSON.parse(response);
will provide you with a JSON object from which you can read the properties

Can you try the following example in jsfiddle.
This is not the better way you can use JSON.parse(); or $.parseJSON(); (jquery version)
But if this is your problem, json being returned as a string this fix it and you can alter your code
http://jsfiddle.net/dadviegas/gf8Yq/

I think the ajax / php part should look like
Ajax
$.ajax({
type: "POST",
url: "link.php",
dataType: "json",
success: function(result){
alert(result.orientation);
}
});
PHP
$response=array("filename" => "$newfilename", "orientation" => "$orientation");
$response=json_encode($response);
echo $response;
Make sure that use at least 5.2 php version

Related

Echo a single variable returned in data object via AJAX Success

I realize this is close to other questions. I simply can;t find the answer.
I have an onclick event that successfully fires an AJAX POST to PHP.
The Data are returned successfully in an encoded_json array.
function upvote(str,str2) {
---do a bunch of stuff
}
jQuery.ajax({
type: 'POST',
url: MyAjax.ajaxurl,
data: {"action": "post_my func", "voted_item":theItemid,"vote_value":currentvote, "vote_type":"upvote"},
success: function(data){
var result = JSON.parse(data);
console.log(data)
//console.log(result[2])
//alert(result[2]);
jQuery('#newtexthere').html(data);
}
});
}
I can echo it. I know it's there. The console.log(data) and console.log(result) look like this:
{"rowcount":"18","result":"6"}
All I want to do is echo a part of this array in #newtexthere as in
<p id="newtexthere">
*18*
</p>
Any and all help would be most appreciated!
You're extremely close. You need to access the individual properties of the result object. You can do so by placing a period after the object name and then specifying a property.
jQuery('#newtexthere').html(result.rowcount);
Note: this only works after you parse the JSON.
In your sample, you try to access the data with array syntax (result[2]) which won't work here because the result variable is an "object" which for now is essentially a group of variables. Accessing object properties is typically done with a period in JS, though you could also get to it with result['rowcount'], though most people will typically use the dot syntax.

Embedding JSON in responseText

I am using jquery iframetransport (for blob uploading) and am forced to access my responses via data.responseText. I am able to embed simple JSON from my PHP such as
echo json_encode(array("response"=>"hello"));
And my console log will return
{"response" : "hello"}
But I need divs and to concat data from my PHP requests. I fail right away if I try to embed this:
echo json_encode(array("response"=>"<div>hello</div>"));
I end up with
{"response":"hello<\/div>"}
What can I do to have this kind of json data in a resposneText?
Alternatively you could cast htmlentities() to the response array. Like this:
echo json_encode(array('response' => htmlentities('<div>hello</div>')));
// {"response":"<div>hello<\/div>"}
exit;
On retrieving responses, since you're expecting JSON, add the dataType: property:
$.ajax({
url: 'blahblah.php',
dataType: 'JSON', // this one
});

Jquery variables in JSON to PHP

I'm using Jquery and PHP together to make some Ajax calls. This is similar to something I'm doing:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://example/ajax",
data: { test: test },
cache: false,
async: true,
success: function( json ){
$.each( json.rows, function( i, object ){
//Example: object.date
<?php date('g:ia', $objectDate ) ?>;
});
}
});
What I need is to pass some JSON objects to PHP, for example object.date to $objectDate and then do something with them. Is this possible?
PHP is executed on the server, JS on the client. Once the server has processed the AJAX call that's it, it doesn't know anything anymore about what happens on the client.
You are already passing data from JS to PHP with your AJAX call. If you need to process that data in PHP do it before you return the call, it makes no sense to return a JSON object only to re-process it in PHP.
In summary what you should do is:
Pass some data from client to server with an AJAX call
PHP processes these data and returns a JSON object
JS processes the JSON object and, for instance, modifies the HTML of the page.
If you need to further process newly generated data with PHP do other AJAX calls.
Also, if you need JS to use any variable generated in point 2, just return it in the JSON object, that is what it is for.
Here's a basic rundown of going from JS to PHP, and PHP to JS:
To transfer an object from Javascript to PHP (and perserve it), you need to encode your data using JSON.stringify:
var data = { message: "Hello" };
$.ajax({
data: { data: JSON.stringify(data) },
// ...
});
Then, in PHP, you can use json_decode to convert the the posted JSON string into a PHP array that's really easy to work with:
$data = json_decode($_POST['data'], true);
echo $data['message'];
// prints "Hello"
To send JSON back as the response to the browser (for your success callback), use json_encode like so:
header('Content-type: application/json');
echo json_encode(array(
'message' => 'Hello, back'
));

Why is this ajax post giving me an error? Does an ajax post require "true" or "false" to be returned?

$.ajax({
url:"http://www.xxxxxxxxxxxxxx.com/cc/validate",
type:"POST",
dataType:"json",
data: JSON.encode($parts),
complete: function(){
},
success: function(n)
{
console.log(n);
console.log(n.object);
console.log("ajax complete");
},
error: function(){
console.log("error");
}
});
This gets an array defined above the ajax post call and posts an encoded json array to a php file. The problem is determining why the post will only let me return "true" or "false". If i try to return any string, i get the error in the ajax. I want to be able to return a string created in the php and not only "true" or "false".
are you on a local host? well if so you might have to change your mime headers (application/json) ... your javascript is expecting json but your php is echoing html.
header('Content-type: application/json');
if you want to be able to return something else then json you have to delete or change the content type in your ajax call. the content type is for giving jquery a hint of what to expect from the server. if you tell it will receive json data you need to give it json or you'll have a parse error.
your code is alright
just make sure your php file return an echo json_encode($arrayOFdata)
dataType:"json",
means the data recived from php will be parsed as a json object
it doesn't mean you will send a json object

PHP: how to extract ajax array response

I am getting ajax response in array format from php url. How to extract array response values in jQuery?
FYI:
PHP array is:
$response = array('msg' => 'Hello', 'html' => '<b>Good bye</b>');
I am getting $response array in my ajax response. i.e.
var promo = "promo=45fdf4684sfd";
$.ajax({
type: "POST",
url: baseJsUrl + "/users/calc_discount",
data: promo,
success: function (msg) { // I am getting $response here as ajax response.
//alert(msg);
// Here I want to check whether response is in array format or not. if it is in array format, I want to extract msg here and want to use response array values.
}
});
Let me know answer pls.
Thanks.
You should echo that $response with json_encode().
You should probably set dataType: 'json' too inside the object literal you send to $.ajax().
Then you can access it natively with JavaScript using the dot operator inside your success callback...
function(msg) {
alert(msg.html);
}
BTW, this line...
$response = array(['msg'] => 'Hello', 'html' => '<b>Good bye</b>');
... isn't valid PHP. Remove the brackets from the first key.
My favorite solution for this is to encode array with PHP's function json_encode() so jquery will be happy to parse it.
I presume that you mean a JSON response, like this:
{"msg":"Hello","html":"<b>Good bye<\/b>"}
This is actually a native JS object, so you can use it right away like this:
success: function(msg){
alert(msg.msg);
alert(msg.html);
}
You can also use the jQuery.each() function to loop over all properties of the JSON object if you need to:
jQuery.each(msg, function(key, val) {
alert(key + "=" + val);
});
and If you do not have control over the PHP output then you can use another method to get the result.
Another solution is using http://phpjs.org/ library. Here you can find many functions available in JS as available in php. Usage is also same as that of PHP. So I feel if you get the json_encode/json_decode from there and use that then it can solve your problem easily.
Remember you can compile your needed functions only. In your case, it is json_encode and json_decode. No need to download whole library. Url to compile your library: http://phpjs.org/packages/configure

Categories