PHP's json_encode and jQuery - php

I'm making an AJAX call to a page /person/steve:
$.ajax({
url: '/person/steve',
method: 'POST',
dataType: 'json',
success: function(response){
console.log(JSON.stringify(response));
}
});
/person/steve consists of this code:
$person = array(
'name' => 'Steve',
'twitter' => '#stevelindstrom'
);
echo json_encode(array('data' => $person));
die;
Now, in my php, when I log the result of that json_encode using the PEAR Log class, I get:
{"data":{"name":"Steve","twitter":"#stevelindstrom"}}
Which is what I would expect, but if I look at the response in the Chrome dev tools, it shows:
[{"data":{"name":"Steve","twitter":"#stevelindstrom"}}]
Any idea why my object is getting stuck into an array? I have other pages that are nearly identical (just different data), and they show up as I would expect them to...
EDIT: I tried using JSON_FORCE_OBJECT and I'm getting the same result.

Try adding to json_encode as second argument JSON_FORCE_OBJECT
And do You return JSON or a string, I mean the Content-type header, is it text/html or (which should be in this case) application/json ?
Or maybe just JSON.stringify method wraps it into an array, try using dragonfly or other tool to see source of the server's raw response.

According to your question, the response is a json string. Which would make the JSON.Stringify call redundant. Remove that and see what happens.

Related

Ajax get shopping cart on page load

I want to load the shopping cart whenever the page is loaded but nothing happens. The console log is not telling me anything either. I have a post to cart system that works fine, so I cant figure out why this doesnt work.
I am using Laravel with a shopping cart plugin.
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'get',
url: '{{route("getCart")}}',
error: function(data) {
var errors = data.responseJSON;
console.log(errors);
},
dataType: 'json',
success: function(data) {
$('#cartResult').html(data.cartCount)
},
});
});
public function cartGet()
{
$cartCount = Cart::content() - > count();
$data = array('cartCount' => $cartCount);
echo json_encode($data);
}
Try return json_encode($data); instead of echo.
You can also avoid json_encode and just use return $data;.
Simply return $data, laravel will place the correct header in response.
if you return json_endode($data) a Content-type: text/plain header will be placed,
if you return $data (which is a structure) laravel will json_encode under the hood and place a Content-type: application/json header.
your code should look like this:
public function cartGet()
{
return ['cartCount' => Cart::content()->count()];
}
It might be because in your $.ajax call you've set dataType: 'json'
From the docs:
As of jQuery 1.5, jQuery can convert a dataType from what it received
in the Content-Type header to what you require. For example, if you
want a text response to be treated as XML, use "text xml" for the
dataType. You can also make a JSONP request, have it received as text,
and interpreted by jQuery as XML: "jsonp text xml". Similarly, a
shorthand string such as "jsonp xml" will first attempt to convert
from jsonp to xml, and, failing that, convert from jsonp to text, and
then from text to xml.
When you echo json_encode(), it sends the data straight to the php output stream buffer and Laravel doesn't know that it needs to add a Content-Type: application/json header to its response. Without it, maybe jQuery needs the dataType to be "text json"?
As others have mentioned, you can return $data from your controller. Laravel will automatically cast your array to json, and it will also set the appropriate Content-Type headers. Maybe try that first?

Send POST data via raw JSON with Postman

I've got Postman (the one that doesn't open in Chrome) and I'm trying to do a POST request using raw JSON.
In the Body tab I have "raw" selected and "JSON (application/json)" with this body:
{
"foo": "bar"
}
For the header I have 1, Content-Type: application/json
On the PHP side I'm just doing print_r($_POST); for now, and I'm getting an empty array.
If I use jQuery and do:
$.ajax({
"type": "POST",
"url": "/rest/index.php",
"data": {
"foo": "bar"
}
}).done(function (d) {
console.log(d);
});
I'm getting as expected:
Array
(
[foo] => bar
)
So why isn't it working with Postman?
Postman screenshots:
and header:
Just check JSON option from the drop down next to binary; when you click raw. This should do
Unlike jQuery in order to read raw JSON you will need to decode it in PHP.
print_r(json_decode(file_get_contents("php://input"), true));
php://input is a read-only stream that allows you to read raw data from the request body.
$_POST is form variables, you will need to switch to form radiobutton in postman then use:
foo=bar&foo2=bar2
To post raw json with jquery:
$.ajax({
"url": "/rest/index.php",
'data': JSON.stringify({foo:'bar'}),
'type': 'POST',
'contentType': 'application/json'
});
meda's answer is completely legit, but when I copied the code I got an error!
Somewhere in the "php://input" there's an invalid character (maybe one of the quotes?).
When I typed the "php://input" code manually, it worked.
Took me a while to figure out!
I was facing the same problem, following code worked for me:
$params = (array) json_decode(file_get_contents('php://input'), TRUE);
print_r($params);
Solution 1
Solution 2
Both solutions are working perfectly.
Thanks
Install Postman native app, Chrome extension has been deprecated.
(Mine was opening in own window but still ran as Chrome app)

JSON Response not parsing, using Wordpress and AJAX

I have a front end editor set up using AJAX to edit posts in Wordpress. Everything was going good, my form submits to a php file which successully updates the database and then uses the following function to create a response:
function generate_response($action, $message = '', $details = '' ){
$response = array(
"action" => $action,
"message" => $message,
"details" => $details
);
echo json_encode($response, JSON_FORCE_OBJECT);
}
However, the response does not appear to be encoded properly, When I log my jsonResponse return in JS I'm getting this:
Object {action: "updated", message: "Succes (no changes detected).", details: ""}
Which I'm pretty sure is malforemd JSON because action, message, and details are not double-quoted, right?
I try to parse the response and all I get is null:
response = jQuery.parseJSON(jsonResponse);
console.log(response); //returns null
What am I doing wrong here? Am I correct and the response is not fomratted properly and if so, how would I fix it?
When you log the result from ajax, you get:
Object {action: "updated", message: "Succes (no changes detected).", details: ""}
That's already an object, not a JSON string, which means you probably set dataType: 'JSON' in your ajax call, and JSON is parsed automagically by jQuery, parsing it again just causes errors.
All you need to do is use response, no parsing needed :
var action = response.action;
#adeneo So when I am running a query to load top 5 posts and then whaterver results I am getting they would be encoded to json.The output I am getting would be a object and not a JSON string right?
Yesterday spent few hours doing stringify- just to convert it to json assuming myoutput was a json string.

Having trouble POSTing nested JSON using PHP

I'm trying to send some form data as a JSON object to a sample app on Force.com. I get the form data using jQuery and POST it to a PHP file on my server which then sends it to the sample app linked above. The response I get from the sample app however tells me that I'm making some mistakes along the way.
The PHP file that talks to the sample Force.com app:
<?php
$url = 'https://cmsamp.secure.force.com/GenericApp/services/apexrest/GenericApp';
$data = $_POST[ 'data'];
$options = array('http' => array('method' => 'POST','content' => http_build_query($data)));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
?>
Client-side jQuery code that posts form data to the PHP file:
var sample_form_data = {"attributes":{"type":"Generic_App__c"},"Application_Type__c":"iPay","Return_Email__c":"lsmith#cmsrep.com","Name":"Bus Test","ACHRejectFee__c":"123456789","ApplicationDate__c":"2000-01-01","BusinessPhone__c":"(555) 123-4567","Email__c":"thetest#testemail.com","InternetPercentage2__c":"0","MailingState__c":"CA","MOTO7__c":"true","NumOfLocations__c":"15"};
$.post( url, { data: JSON.stringify( sample_form_data ) }, function( result ) {
console.log( result );
});
The response from I get from the Force.com app:
"No content to map to Object due to end of inputInsert failed.
First exception on row 0;
first error: REQUIRED_FIELD_MISSING,
Required fields are missing: [Name]: [Name]"
Desired "success" response:
"Success:
Generic App Object: Bus Test; was successfully created and inserted"
This is the output of var_dump($data) in the php code (line breaks added for readability:
string(405)
"{\"attributes\":
{\"type\":\"Generic_App__c\"},
\"Application_Type__c\":\"iPay\",
\"‌​Return_Email__c\":\"lsmith#cmsrep.com\",
\"Name\":\"Bus Test\",
\"ACHRejectFee__c\":\"123456789\",
\"ApplicationDate__c\":\"2000-01-01\",
\"B‌​usinessPhone__c\":\"(555) 123-4567\",
\"Email__c\":\"thetest#testemail.com\",
\"InternetPercentage2__c\":\"0\"‌​,
\"MailingState__c\":\"CA\",
\"MOTO7__c\":\"true\",
\"NumOfLocations__c\":\"15\"
}"
The generic app just expects to get a JSON object with the proper fields. When I submit the following through a REST client it works as intended (again, line breaks added for readability):
{"attributes":
{"type":"Generic_App__c"},
"Application_Type__c":"iPay",
"Return_Email‌​__c":"test#example.org",
"Name":"Bus Test",
"ACHRejectFee__c":"123456789",
"ApplicationDate__c":"2000-01-01",
"BusinessPho‌​ne__c":"(555) 123-4567",
"Email__c":"thetest#testemail.com",
"InternetPercentage2__c":"0",
"Mailing‌​State__c":"CA",
"MOTO7__c":"true",
"NumOfLocations__c":"15"}
Anyone have ideas on how to solve this?
From the looks of those var_dumps, I'd say you need to strip those slashes out of $data before you use it. Try stripslashes.
http_build_query also expects an array. Since your data is already a json string, I think you should probably omit it. You may need to url encode it, but you should just use the regular urlencode function for that.
Also, I'm not familiar with the php context mechanism you're using and I'm deeply unsatisfied with the php.net documentation, but I can't shake this nagging feeling that the 'content' => $data is doing something more than just setting the content. Do you have a good documentation link for the stream contexts actually using the 'content' option?

Consuming JSON object in PHP, sent from jQuery

I'm sending a JSON object to PHP using jQuery via
$.ajax({
url: myURL,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: myData,
processData: false,
dataType: 'html',
async: false,
success: function(html) {
window.console.log(html);
}
});
and trying to decode the JSON object using
$GLOBALS["HTTP_RAW_POST_DATA"];
but the contents of variable are printed as
[object Object]
with json_decode() returning NULL (of course).
Any ideas what I need to do to get the at the actual JSON data?
Thanks,
Gaz.
Looks like you are sending a string to the PHP. Jquery by default sends data in a normal post format. PHP can read this data just fine. I would recommend just getting the data you need out of the POST array.
If you are trying to serialize a Javascript object via JSON and then convert it back to an object in the PHP side, then you might want to go the JSON route. You will need a plugin to convert the data from a string to JSON. You might want to consider:
http://code.google.com/p/jquery-json/
You would change the line:
data: myData,
To:
data: $.toJSON(myData),
Then on the PHP side you will still receive the data in the post array and you can convert it with the following command:
$params = json_decode($_POST[]);
Looks like you do not send a JSON object to your php script, just the string 'object Object'.
Have you tried using $_POST?
I handle all of my JSON requests more or less like this:
$params = json_decode($_POST[]);
You are actually sending a string through POST. I recommend using JSON2 to stringify your Javascript object.
Use
var myData = JSON.stringify(myObject, replacer);
Use file_get_contents('php://input') instead $GLOBALS["HTTP_RAW_POST_DATA"];
You've set your dataType to 'html' in your ajax call. Shouldn't it be 'json'? I think your nice json object is being condensed down into a meaningless string.

Categories