JSON Response not parsing, using Wordpress and AJAX - php

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.

Related

Send PHP's JSON response from an API call as part of AJAX success function

I have setup a page that takes the data from a form, serializes into JSON and then uses AJAX to call a PHP file to process the form data and send it to an API via cURL.
How can I get the response from the API to come back as part of the AJAX's success function?
At the start of my project, I was able to accomplish this because I was using the php as an include. But cannot use that method because the file is being executed from the AJAX call not from an include.
I tried to follow this tutorial, but just kept catching errors.
I've also scoured, reviewed and attempted more suggestions from various posts on this site than I can even count. Now, I'm asking for some help.
Here is the pertinent ajax on my index.php file.
$.ajax
({
type: "POST",
dataType : 'json',
async: false,
url: 'save_application.php',
data: { filename: fileName, applicationData: jsonFormString, job: adid },
success: function () { console.log("done");},
failure: function() {console.log('error');}
});
And here is the relevant part of the save_application.php file.
$curl = curl_init();
curl_setopt_array($curl, array(
//stuff here
));
$applicantresponse = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
And lastly, the $applicantresponse that comes back is formatted like this:
{
"applicationId": 123456789,
"links": {
"link1": "https://thisisalinkforLINK1.html", //THIS IS THE VALUE I WANT
"link2": "https://thisisalink.html",
"link3": "https://thisisalink.html"
}
}
Ultimately, I want to set a variable to the value for links->resume (ex: var resumeLink = (something goes here); \\returns https://thisisalinkforLINK1.html) back on my index.php within the success function so I can use that response for some other to-dos.
You need to output $applicantresponse from your save_application.php file so that it's returned to your calling code, and you need to change the success function in your ajax code to then use that data. It'll look something like this:
$applicantresponse = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
echo json_encode($applicantresponse);
and then...
$.ajax
({
...
success: function (data) {
console.log(data.links.link1);
// do something with the data that was returned
},
...
});
One thing that is important is that your php code not output any other text to the client. All other echo, print, debugging calls, all of that stuff, has to be removed, because otherwise you're not sending back valid json encoded data that jQuery knows how to interpret.
It looks like save_application.php uses the data submitted by $.ajax for the curl request, and you need to send part of the curl response back to the client to be used in the success function.
The curl response is already JSON, so the simplest thing to do is just
echo $applicantresponse;
which will send the entire curl response back to the client.
If you only want to send one of the links of it, you'll need to decode it and extract the specific piece you want, then re-encode that piece.
$applicantresponse = json_decode($applicantresponse);
$link = $applicantresponse->links->link1;
echo json_encode($link);

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?

Why does PHP's json_decode return a string when it should return an array?

I'm a bit confused as to why I'm not getting an array in my variable after I use json_decode(). I am using cURL to send some post data. Here is what the post data looks like for cURL
upload, post_data: Array
(
[local_file_path] => C:\videos\421F7D21-C659-43E1-9851-2397A4EEFB11.mp4
[botr_video] => "{\"path\":\"\\\/v1\\\/videos\\\/upload\",\"query\":{\"token\":\"b34f75e5c2c4a23db9850b147f0440fc536bcc7a21847e29\",\"key\":\"hKwNuueB\"},\"protocol\":\"http\",\"address\":\"upload.bitsontherun.com\"}"
)
So I call cURL, and on the receiving side of the cURL call I have the following
$upload_link=json_decode($_POST['botr_video'], true);
$file_path=$_POST['local_file_path'];
$api_format="php";
error_log('upload link data is of type: '. gettype($upload_link));
When I go check my error log, it writes this:
upload link data is of type: string
Shouldn't that be an array? The rest of the code in the receiving url depends on the json_decode to work. Am I missing something?
Also, I logged the $upload_link variable after applying the json_decode function on the $_POST['botr_video'] variable like this:
error_log('received upload link data: ' . print_r($upload_link, true));
Here is what I get in the log:
received upload link data: {"path":"\\/v1\\/videos\\/upload","query":{"token":"0835b9c46c0619cec9633a22bc9616a693696e4ea39a827c","key":"kRhvNuIF"},"protocol":"http","address":"upload.bitsontherun.com"}
Why doesn't json_decode take the post data and form an array? It seems like it's leaving it as a string.

PHP's json_encode and jQuery

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.

jquery cant transform json response

I'm using jquery with the form plugin to handle the submit, but when the client receive the server response it cant pass it to a json object:
var options = {
success: showResponse,
dataType: 'json',
error: errorhandler
};
$('#UserEditForm').ajaxForm(options);
The server response is generate with the _json_encode_ php function.
When I submit the form, always the errorhandler function is called and I check the response with firebug it comes with some kind of a space after the first "{"
" {"status":1"}"
, that with utf-8 encode and something like:
"{"status":1}"
with iso-8859-1.
Thanks!!
Do you send headers with your server reply?
Otherwise, try:
header('Content-type: application/json');
Also, I've had problems with jQuery not reading some large chunks of data in JSON correctly, and I used the parse method from json.org:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Categories