Server not seeing the JSON sent in javascript ajax request - php

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'].

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");

Accessing params sent by an Ajax POST request

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.

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'));

Receive JSON object from HTTP Get in PHP

I am trying to implement a php client that sends an HTTP GET to the server which sends back a JSON object with the return information. I know how to decode the JSON once my php script has received it, but how would I go about actually getting it?
EDIT: Note - I send the server an HTTP GET, and it generates and sends back a JSON file. It is not a file sitting on the server.
Check out file_get_contents
$json = file_get_contents('http://somesite.com/getjson.php');
Browsers act differently based on what the server responds. It does not matter what type of request you make to the server (be it GET, POST, etc), but to return JSON as a response you have to set the header in the script you make the request to:
header('Content-Type: application/json;charset=utf-8;');
And then echo the JSON string, for example:
//...populating your result data array here...//
// Print out the JSON formatted data
echo json_encode($myData);
User agent will then get the JSON string. If AJAX made the request then you can simply parse that result into a JavaScript object that you can handle, like this:
//...AJAX request here...//
// Parse result to JavaScript object
var myData=JSON.parse(XMLHttp.responseText);
The header itself is not -really- necessary, but is sort-of good practice. JSON.parse() can parse the response regardless.

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