Accessing params sent by an Ajax POST request - php

I am writing an Ajax request that sends a JSON-formatted string in a POST request. Here is the relevant code:
var params=jsonString;
request.onreadystatechange = functionXyz;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
request.send(params);
My question is how do I access the content of the POST on the other side? In a typical form submission the data is sent as an associative array, but in this case I am not sure how to access the data - what the label is. Is it by calling $_POST["params"]?

You have to set a label for the json string (which is just a string):
request.send("params=" + encodeURIComponent(params));
Then on the server:
$object = json_decode($_POST['params']);
If you just send a JSON string, you can extract it from the post body, but I think that's unnecessary.

Related

how to get string from xmlhttp.send(str) via POST in PHP

My code looks like that:
Client side JavaScript:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST",url + page,true);
xmlhttp.send(str);
I'm missing the code to in PHP side to extract this string, which I assume is in the http post body.
Is it possible to send string array or is this method is restricted for xmls and strings?
You can send any data you like.
Usually, you would encode the data as application/x-www-form-urlencoded:
var data = "foo=" + encodeURIComponent(data) + "&bar=" + encodeURIComponent(more_data);
xmlhttp.send(data);
And then access it via $_POST['foo'] and $_POST['bar'].
If you want to access the raw data, then you can access it via file_get_contents('php://input');
Use setRequestHeader to specify the content type of the data you are sending.
As Canttouchit said, these headers must be send for any POST request:
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // for POST escaped 'form' data
xhttp.setRequestHeader("Content-length", post_str.length);
xhttp.setRequestHeader("Connection", "close");

Send json as request body or POST json in a variable

I am trying to figure out, is there any way of sending raw json to php instead of POST parameter. If it is possible then which way is best i mean either request body or POST parameter.
Send an HTTP request which has a JSON string as its request body (here: using curl on the command line):
$ curl -d '{"foo":"bar"}' example.com/test.php
Read this request body in PHP:
$json = file_get_contents('php://input');
Decode it:
$data = json_decode($json, true);
PHP's $_POST superglobal is automatically populated as an array if the request body of a POST request contains URL encoded key-value pairs (e.g. foo=bar&baz=42). In the above example you're still using an HTTP POST request with "POST data". It just doesn't automatically end up in $_POST because PHP doesn't know how to decode JSON automagically.

How to access Backbone model ID from a fetch request on server side

In an attempt to learn how BackboneJS works, I am building a PHP script with basic CRUD cabibilities. My problem is, when BackboneJS sends a "Fetch" request (GET) it will send an ID encoded in JSON. My problem is, how can I handle this on the server?
I have tried:
$data = json_decode(file_get_contents('php://input'));
or just handling it via the $_GET array.
I simply need to get the ID that comes through, so I can do some DB work with it.
You get the ID from _SERVER["REQUEST_URI"]
var Student = Backbone.Model.extend({
urlRoot : "/students"
});
var student = new Student({id:123});
student.fetch();
url that is hit is www.yourdomain.com/students/123
Hence you need to parse it out from the request uri.
In a model.fetch() ID is not passed as Request payload, but as part of the url it self.
ID along with all other attributes are passed as request payload for model.put(). model.save() does not have any id, attributes are passed as request payload in which case
you need to
$content = json_decode(file_get_contents('php://input'));

Server not seeing the JSON sent in javascript ajax request

I'm trying to make an ajax request in straight javascript (jQuery is not available to me) with some JSON parameters.
The javascript:
var params = {'ajax': true, 'albumid': albumid, 'sequencenum': sequencenum};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
console.log(xhr.responseText);
}
}
xhr.open("GET","viewpicture.php",true);
xhr.setRequestHeader("Content-Type", "application/json")
console.log("sending request");
xhr.send(JSON.stringify(params));
In viewpicture.php, a var_dump($_GET) yields an empty array. What am I doing wrong?
In short, when you make a GET request, .send is expected to have 0 params (or be null).
The only way to send the data through GET would be to append it to the URL itself.
To wit:
If you were sending in form-data, in a POST, the anticipation would be that send would contain the form-encoded data (json for json-data, etc), and the URL would just be the access point on the server.
A GET request is just fetching data from that access point (including query string).
See where I'm going with this?
So if you want this to work in a GET, you need to set your JSON as a property of a query parameter (or turn it into query params/values).
If you want to send in the request body you should use a POST request, however if you need to use a get request you should send the data as key value pairs in the url. e.g. xhr.open("GET","viewpicture.php?data=" + encodeURIComponent(JSON.stringify(params)),true); Then retrieve via $_GET['data'].

XHR request to PHP

Hi i am having problems with an XHR post request.
in javascript:
self.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xhr.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
In firebug:
Parametersapplication/x-www-form-urlencoded
{"u":"andrepadez","m":"\n...
JSON
m
"sfdsfsdfdsfdsf"
u
"andrepadez"
Source
{"u":"andrepadez","m":"\nsfdsfsdfdsfdsf"}
In .NET, I post this to an .ASHX, and in the ProcessRequest i do:
StreamReader sr = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding);
javaScriptSerializer.Deserialize<MyClass>(message);
and I have no problems.
I don't know how to get the data in PHP, either $_POST and $_REQUEST are empty arrays.
Any help please?
thanks
You've not set a field name for the data being sent. PHP requires data coming in via POST to be in a fieldname=value format. _POST is an array like any other, and every value stored in a PHP array must have a key (which is the form field name).
You can try retrieving the data by reading from php://input:
$post_data = file_get_contents('php://input');
But the simplest solution is to provide a fieldname in your XHR call.
You are setting the Content-Type to application/x-www-form-urlencoded, but you are setting the content to json. I'm guessing this is confusing your PHP webserver. Try setting your POST contents to what you tell the server it will be (application/x-www-form-urlencoded) or read the raw HTTP contents in php://input.
If you set the Content-Type to application/x-www-form-urlencoded then naturally PHP will want to parse the POST body. But as the data does not actually constitute form data, it is discarded as invalid.
You need to set the correct CT application/json (actually doesn't matter) so PHP will leave it alone. Then it becomes available as php://input or $HTTP_RAW_POST_DATA

Categories