How to add JSON data to GET request to XMLHttpRequest? - javascript

I have a problem with setting JSON data in a GET request.
I tried:
As POST request (with POST request it works)
xhr.open("GET", "http://localhost/test", true);
body = JSON.stringify({"email": "hey#mail.com", "password": "101010"});
xhr.send(body);
As query string:
var json = {"hello": "world"};
var url = "http://localhost/test?data=" + encodeURIComponent(JSON.stringify(json));
xhr.open("GET", url, true);
xhr.send();
On the backend method, req.json returns null, but I can see the query string.
Also, it works in Postman if I set JSON data to the body. On the backend, I see JSON data in the request.
P.S.: In my previous project I used the same backend framework but the frontend was based on jQuery instead of pure JS and the ajax method worked correctly.

2 months without web development born such stupid questions. I don't use node.js but I think node.js acts so. I remembered the right way. I have tried to use "localhost?data={a: 9}" but the correct way is "localhost?a=9". The backend will parse all query variables as input in the Rest interface. Thanks to #evolutionxbox for kicking to the right side.

Related

PHP not receiving any data from XMLHttpRequest

I cannot seem to send any POST data to a PHP file via XMLHttpRequest. I have read many questions like this one but everyone had a different issue - none of them seem to be the case here.
I have boiled these two files down to their absolute core basics and it is still is not receiving any POST data. I have done this the exact same way in plenty of other instances before and I'm not sure how this one is any different.
index.php
...
<button id="login-button">Log in</button>
...
Javascript:
function login() {
let ajax = new XMLHttpRequest();
ajax.open('POST', 'login.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
ajax.onload = function() {
alert(this.response);
};
ajax.send({user:'hello', password:'there'});
}
document.getElementById('login-button').addEventListener('click', login)
login.php:
var_dump($_POST);
The alert message with the output, every single time, simply reads:
array(0) {
}
The JS and PHP are both in the same folder of the same website on the same server, running PHP 7 if that matters. What could I possibly be doing wrong here?
By using ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); you basically tell your request to expect url-encoded data.
Lets keep it very simple, you want to submit a username and password.
So the request should look like this ajax.send("username=hello&password=there")
In your sample code you tried to send I dont know what kind of object-notation. The go-to way to exchange data between frontend and backend is JSON.
To modify your example to work with json modify it in the following way:
ajax.setRequestHeader("Content-Type", "application/json");
let data = JSON.stringify({"username": "hello", "password": "there"});
ajax.send(data);
To get an object out of a valid JSON string you can use the json parse method
pe this helps you out :)

Can't send large json data via XMLHttpRequest - javascript

I need to pass a json variable as a paramater to a php script that will process the json data and store it in Database.
So first, in javascript, i was testing sending data like this :
$('#sendResult').load('http://localhost/myurl/phpFile.php?mrData=' + jsonArrFinal);
This was working well when passing small records (records can vary, it depends the data that user insert).
But when i increased the records, it started appearing this error in console:
414 (Request-URI Too Long)
I've changed the js code to:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/myurl/phpFile.php?mrData=' + jsonArrFinal );
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.send();
But still appearing the same error with POST method.
I've checked the json param and it has 5439 characters.
How can i resolve this? Thanks in advance.
Please note that the length can be 8x more than 5439 characters.
Don't use a GET request.
You're storing data, so you should be using a POST request anyway.
Use $.post instead of $.load and write your own logic to display the response in the done() handler.
I've changed the js code to:
You need to put the data in the body of the request. POST requests don't change the rules for how much data you can put in the URL.
$.post("http://localhost/myurl/phpFile.php", { mrData: jsonArrFinal })
.done( data => $("#sendResult").html(data) );

How to create an in memory file and upload to server using client side javascript?

I have a test suite written in JavaScript running in a browser that runs on an embedded system. The test suite collects a lot of data and I want to push that to the server. I could use a simple HttpRequest, post-method, but that would require a lot of character escaping to send the content. It would much simpler to upload it to the server as a file using http-file-upload.
Is there a way to create an in memory file and use http-file-upload to push it to a server, using client-side JavaScript?
Since the browser of the embedded system is Ekioh and the system itself is a minimal one, technologies such as flash, JavaApplet, SilverLight are not available. Only pure HTML5 and JavaScript are available.
I think a post would be the better way to do this. Dealing with escaped data is a much easier, more established problem then in-memory files and pushing files to the server with client side javascript. Moreover, escaping data is done for a reason. What you're trying to do is going to welcome a lot of security vulnerabilities.
Try doing something like this.
Snippet taken from Write javascript output to file on server
var data = "...";// this is your data that you want to pass to the server (could be json)
//next you would initiate a XMLHTTPRequest as following (could be more advanced):
var url = "get_data.php";//your url to the server side file that will receive the data.
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);//check if the data was revived successfully.
}
}
http.send(data);
This worked for me. The key part is to create a file and blob. I use angular JS to do the actual http call. However, once you have a file in memory, it shouldn't be too hard to send the data using your http client.
Note: I do the http call to https://httpbin.org/post. This echoes what the server received/parsed, which is useful while iterating to figure your problem out.
function multiPartPost(bodyObj) {
const url = 'https://httpbin.org/post';
const bodyJson = JSON.stringify(bodyObj);
const blob = new Blob([bodyJson], {
type: 'application/json;charset=UTF-8'
});
const fileName = 'jsonAttrs';
const file = new File([blob], fileName, {type: "text/json;charset=utf-8"});
const formData = new FormData();
formData.append(fileName, file);
return this.$http.post(url, formData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
}

Send a request with openlayers

I am trying to make a request to a SOS service using Openlayers like this (part of the code):
var params = {'service':'SOS','version':'1.0.0','request':'getCapabilities'};
var paramString = OpenLayers.Util.getParameterString(params);
url = OpenLayers.Util.urlAppend(this.url, paramString);
OpenLayers.Request.GET({url: url,
success: this.parseSOSCaps, scope: this,
failure: alert(url)});
}
For some reason the url that I produced in this code is not correct. The failure function, alerts this url:
http://cawa.gfz-potsdam.de:8080/SOS/sos?service=SOS&version=1.0.0&request=getCapabilities
I also tried manually, through my browser to send the request (using the above url) but it doesn't work. I am sure that the host server is correct.
My questions are: what am I doing wrong? Is the above format of the url wrong? What would be the alternative? Perhaps to send the request in XML format?
Thanks
Dimitris
After all I managed to make the above code to work. There is not a bug in the code. The problem was that I haven't included in the allowedHosts of the proxy.cgi (wamp\bin\apache\apache2.2.22\cgi-bin\proxy.cgi) file, the host of the service. After I did it was working perfectly.

How to send data in request body with a GET when using jQuery $.ajax()

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.
The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.
I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
data: "id1-id2-id3",
contentType: "text/plain",
dataType: "json",
processData: false, // avoid the data being parsed to query string params
success: onSuccess,
error: onError
});
Anyone know how I can force the "data" value to be sent in the body of the request?
In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.
You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.
If you aren't absolutely tied to GET requests with the body being the data, you have two options.
POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.
GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.
url: 'somesite.com/models/thing?ids=1,2,3'
we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}

Categories

Resources