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\",
\"BusinessPhone__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",
"BusinessPhone__c":"(555) 123-4567",
"Email__c":"thetest#testemail.com",
"InternetPercentage2__c":"0",
"MailingState__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?
Related
I've been debugging this for hours. Tried to set the header etc but no luck!
My controller
$http({
url: 'http://myphp.php/api.php',
method: "POST",
data: {'wtf':'test'}
})
.then(function(response) {
console.log(response);
},
function(response) { // optional
// failed
}
);
and my php
<?php
echo "test";
echo $_POST["wtf"];
?>
In my network tab this is how it look like
Not sure what's wrong man, really exhausted, I'm stuck for hours! Why my $_POST['wtf] didn't echo?
$http is serializing the data to JSON in the request body but PHP's $_POST is looking for key/values parsed from posted form data. These are two different mechanisms for posting data so you need to choose one and use that mechanism on both sides.
You have two options to solve this:
In your PHP code, parse the request body as JSON data and then use that object to retrieve your data. See this StackOverflow question for more information.
Modify your $http request to post the data as form data. See this StackOverflow question for more information.
$http.post (by default) does not send the data as key/value pairs. It sends it as post request.
Therefore, in your php script you should consume it like this:
$input = file_get_contents('php://input');
And then parse it like this:
$data = json_decode($input, true);
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.
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.
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.
I'm using PHP to connect to an API and register some info using JSON and HTTP POST but it is not going well.
That is what I do:
I create a JSON object with the json_encode function:
$name = 'Mike';
$surname = 'Hans';
$fields = array('name' => json_encode($name), 'surname' => json_encode($surname));
$postData = json_encode($flds);
Once i have the post data, I just connect to the API with curl and login with oauth, but the API responde says:
JSON text must be an object or array (but found number, string, true,
false or null, use allow_nonref to allow this)
I have checked the allow_nonref in Google, but i could not find anything for PHP, all I have found is for Perl. Does anyone have any solution/advice to solve this?
Thanks!
You probably need to send the entire POST as JSON without nesting calls to json_encode, like this:
$fields = array('name' => $name, 'surname' => $surname);
$postData = json_encode( $fields);
To follow up on #nickb's answer, please only use one call to json_encode, it's far better at constructing valid json that you and I are, and it's more efficient to boot! (though we are entering the realm of micro-optimisation).
Have you tried taking the output of the json_encode and putting it into a validator/formatter such as the one here : http://jsonviewer.stack.hu/
Also, I think another likely problem could be the headers you are sending? The recieiving server could be strict and enforce that you use the correct 'Content-Type'. Are there any API docs avaliable?