Posting JSON to PHP script - php

I am stuck a long time with trying to send a JSON from javascript to a PHP script : the sending is fine (I can see the JSON in fiddler) yet I receive nothing in the PHP script :
javascript:
var person = {
name: 'yoel',
age: 28
};
xmlhttp.open("POST","http://localhost:8888/statisticsdb.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(person));
php :
echo 'trying to print ' . var_dump($_POST["name"]);
I would expect obviously to see SOMETHING but var_dump returns nothing. Help would be much appreciated!

try:
$data = json_decode(file_get_contents('php://input'));
var_dump($data->name);
the reason for this is, that the body of your POST-request is:
{"name":"yoel","age":28}
though, php expects something like (ref):
name=yoel&age=28
The json string can not be parsed properly, and thus $_POST will be empty.

$_POST holds value decoded from request having Content-Type application/x-www-form-urlencoded, i.e. it parses:
param1=value1&param2=value2
into:
array( 'param1' => 'value1', 'param2' => 'value2')
If you send data in json format, you have to json_decode it from the raw php input:
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
And you'll have a PHP object filled with your json stuff.

Add this:
xmlhttp.setRequestHeader("Content-length", JSON.stringify(person).length);

Related

Rails send four backslashes using Net::HTTP

My rails application need to send some data to a php application, which expects a POST call.
I use the folowing code:
uri = URI.parse(apiUrl)
req = Net::HTTP::Post.new(uri.to_s, initheader = {'Content-Type' =>'application/json'})
req.basic_auth(api_key, token)
req.set_form_data({"action" => action, "data" => data})
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(req)
Where data is a hash converted to json:
data = {
:key1 => val1,
:key2 => val2
}.to_json
(it is a nested hash, i.e. some values are hash as well)
My problem is that the php application receives 4 backslashes before each quotation mark:
$data_json = $_POST['data'];
error_log($data_json);
and in error log I see:
'{\\\\"key1\\\\":val1,\\\\"key2\\\\":\\\\"val2\\\\"}'
Looks like rails add one of them, but even if I remove it and replace it with the following code:
a.gsub!(/\"/, '\'')
I still get many backslashes inside the php application, hence cannot convert the string to array.
Any idea??
By using set_form_data net/http is POSTing the form as urlencoded. Its NOT posting your request body as pure JSON.
If you want to POST raw JSON you will need to follow a pattern like:
uri = URI('https://myapp.com/api/v1/resource')
req = Net::HTTP::Post.new(uri, initheader = {'Content-Type' =>'application/json'})
req.body = {param1: 'some value', param2: 'some other value'}.to_json
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end

NSDebugDescription = "JSON text did not start with array or object and option to allow fragments not set.";

I am using AFJSONRequestOperation to request a server and parse the returned JSON response, but while parsing, I got this error:
NSDebugDescription = "JSON text did not start with array or object and option to allow fragments not set.";
I checked the API and it's returning JSON data:
header('Content-type: text/json');
$arr[] = array("Message" => "update succeeded");
echo '{"Result":'.json_encode($arr).'}';
Any idea how to fix that?
EDIT
I tried to call the API from browser and include the request in the url, and so I got a valid JSON response:
{"Result":[{"Message":"update succeeded"}]}
First thing, json_encode the entire object rather than breaking into it pieces.
Secondly, unless $arr contains multiple elements (not clear from example above), it should be initalized as thus:
$arr = array("Message" => "update succeeded");
I'm still not certain what else could be the issue here. You should echo out what your app is receiving and that should indicate the issue.
Please use acceptable content type.
in your webservice that should be only plain text.
here is my swift code and fixed:
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer=AFJSONRequestSerializer()
manager.responseSerializer = AFHTTPResponseSerializer();
manager.GET(
baseURL + (webServiceType as String) + secureParam,
parameters:[:],
success:
{ (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
completion(obj: responseObject)
},
failure:
{ (operation: AFHTTPRequestOperation!,
error: NSError!) in
completion(obj: nil)
})
Check you have added /api/ before your base url of API like
http:// someurl / yourBasrUrl /api/apiName
To make a valid json response, your code should
look something like this:
$response = array(
"Result" => array(
"Message" => "update succeeded"
)
)
echo json_encode($response);
If you need read fragment json you can use option .allowFragments like this:
JSONSerialization.jsonObject(with: someData, options: .allowFragments)
Please try this:
let manager = AFHTTPSessionManager(baseURL: NSURL("Base URL"))
manager.requestSerializer = AFJSONRequestSerializer()
manager.responseSerializer = AFJSONResponseSerializer()
let params = [
"foo": "bar"
]
manager.POST("API url", parameters: params,
success: {
(task: NSURLSessionDataTask!, responseObject: AnyObject!) in
print("success")
},
failure: {
(task: NSURLSessionDataTask!, error: NSError!) in
print("error")
})
First of all, your API is returning improper Content-Type. Proper content type for JSON data is application/json. This may be conflicting while using third-party libraries.
Secondary, you should not produce json string "by hand". Altogether API should be modified to face:
header('Content-type: application/json');
$arr[] = array("Message" => "update succeeded");
echo json_encode(array('Result' => $arr));
Last bat not least. There is one more thing in charge possible: you might have BOM characters at very beginning of your api PHP script. Those are whitespace, so you may not see them in browser. Please, ensure that your PHP files are encoded without BOM.

Extjs JSON response

I have a form, which sends data to the server. I process the form with a PHP script, which can return 3 differents JSON strings:
One
exit("{\"success\":\"false\", \"msg\":\"Las claves no cohinciden\"}");
Two
exit("{\"success\":\"false\", \"msg\":\"".$failure->getMessage()."\"}");
Three
exit("{\"success\":\"true\",\"msg\":\"El usuario: $nombreUsuario ha sido dado de alta correctamente.\"}");
The first and second strings, are errors to show. The third string is the normal case.
When the script return some of these values, i catch the response with ExtJs do:
var respuesta = Ext.JSON.decode(response.responseText);
But, when do:
console.log(respuesta);
Firebug console says that "respuesta" are undefinied.
Any idea ?
When you are outputting JSON for using in AJAX, it's best to set the headers for JSON and return properly formatted JSON. In my below example, we create a normal PHP array with your response and convert it to JSON with json_encode().
Try it. I've had issues before with Javascript not taking a string in as JSON before without a proper content type and formatting.
<?php
$response = array("success" => "false", "msg" => "Las claves no cohinciden");
header("Content-type: application/json");
exit(json_encode($response));
?>
Optionally, if you have jQuery... You can do $.parseJSON('your string'); to output JSON from a string.
you can use this url for testing your Json code:
http://www.utilities-online.info/xmltojson/#.UNr9FhhQ-gY

POSTing binary data over http with Python -> PHP

I'm want to post a binary data string from a Python script to a webserver where a PHP script should pick it up and store it. I receive the whatever I echo in my POST part of the php script on the Python side so I assume, the actual POST works. However, I'm posting 23 Bytes and strlen($_POST['data']) stays 0.
My PHP script to pickj up the data looks like this:
if (isset($_REQUEST["f"]) && $_REQUEST["f"]=="post_status") {
$fname = "status/".time().".bin";
if (file_exists($fname)) {
$fname = $fname."_".rand();
if (file_exists($fname)) {
$fname = $fname."_".rand();
}
}
echo strlen($_POST['data'])." SUCCESS!";
}
and the Python POST script looks like this:
data = statusstr
host = HOST
func = "post_status"
url = "http://{0}{1}?f={2}".format(host,URI,func)
print url
r = urllib2.Request(url, data,{'Content-Type': 'application/octet-stream'})
r.get_method = lambda: 'PUT'
response = urllib2.urlopen(r)
print "RESPONSE " + response.read()
Why does my data not seem to get through, I'm wondering?
Thank you,
PHP will only populate posted values into the $_POST/REQUEST arrays for data that is sent as one of the form data content types. In your case, you need to read in the binary data directly from standard in like this:
$postdata = file_get_contents("php://input");

QT sending post array, how to recieve it in PHP

Hi all so here is a code I want to receive data in PHP.
so I have this in QT:
QUrl params;
params.addQueryItem("action","Dodaj_korisnika");
params.addQueryItem("ime","qt");
params.addQueryItem("prezime","QT");
params.addQueryItem("broj","998873");
params.addQueryItem("adresa","kkakka");
QByteArray data;
data.append(params.toString());
data.remove(0,1);
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QNetworkReply *reply = manager->post(QNetworkRequest(url), data);
connect(reply, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
How to write PHP to retireve array.
I have tried this:
$_FIELD=array(
"action" => $_POST{action},
"ime" => $_POST{ime},
"prezime" => $_POST{prezime},
"broj" => $_POST{broj},
"adresa" => $_POST{adresa}
its not working
and this:
$_POST array($_POST['action'],$_POST['ime'],$_POST['prezime'],$_POST['broj'],$_POST['adresa'];
still not working..any idea what is right way to get post data..
);
$_POST is like any other array in PHP and can be accessed like this:
echo $_POST['action']; // echos the value for the key "action"
To see whats in there you can use:
print_r($_POST);
Your code has syntax errors . It must be like this :
$field = array(
"action"=>$_POST["action"],
"ime"=>$_POST["ime"],
"prezime"=>$_POST["prezime"],
"broj"=>$_POST["broj"],
"adresa"=>$_POST["adresa"],
);

Categories