Can't send large json data via XMLHttpRequest - javascript - 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) );

Related

How to add JSON data to GET request to XMLHttpRequest?

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.

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 :)

How to send XMLHttpRequest to specific php function?

I am trying to do a image uploading with ajax. I have run into a bit of problem. I have two functions in func-ajax.php : function doSth(){} and function doSthElse(){}. I want to target the doSth() function
This is my javascript side:
var xhr = new XMLHttpRequest();
xhr.open("POST", 'func-ajax.php', true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
How can I specify whick function to send the request?
You cannot run a specific function from the func-ajax.php file.
What you should do is create something like ajax-controller.php, containing
$functionName = $_POST["func"]; // func parameter should be sent in AJAX, determines which function to run
if (function_exists($functionName)) { // check if function exists
$functionName(); // run function
}
And send all requests from JS to this file xhr.open("POST", 'ajax-controller.php', true);
Hope you get the idea.
You want to send GET/POST parameters along with your request, and catch those in the PHP script.
You can't send an HTTP request to a function.
You make a request for a resource. That request can include POST data and it can include HTTP headers.
The server then decides how to respond the request. It might choose to run a PHP program.
It is up to the PHP program to look at the requested resource / POST data / headers and determine which function(s) to run.
You can add a parameter in the data being sent and that you check for in some sort of if block that you call the function manually from. You could also introduce a framework like Slim, to create an REST-api point that you can hit.

Cross-domain Jquery JSONP POST to Rails app

This is killing me. Trying to load data from a different domain from an API-sorts of that I'm trying to write. When sending JSON parameters as POST they get discarded, I've read somewhere that some special headers must be set before_filter:
def cors_headers #set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Max-Age'] = "1728000"
headers['Access-Control-Allow-Headers'] = 'content-type, accept'
end
Haven't had any luck with these though. Guess it's a browser limitation.
When I try sending the data as GET instead of POST, it gets added to the URL like this:
Completed in 959ms (View: 0, DB: 2) | 200 OK [http://www.somedomain.com/connector/browse/Sport.json?callback=jQuery16105855946165975183_1379526705493&{%22filters%22:[{%22filter%22:{%22attribute%22:%22id%22,%22op
erator%22:%22%3E%22,%22value%22:%222%22}},{%22filter%22:{%22attribute%22:%22id%22,%22operator%22:%22%3C%22,%22value%22:%227523%22}}]}&_=1379526723982]
So Rails basically can't see the filters which are the params that I'm trying to send
Parameters: {"{\"filters\":"=>{}, "id"=>"Sport", "_"=>"1379526723982", "callback"=>"jQuery16105855946165975183_1379526705493"}
The jquery snippet I'm playing with is:
$jq.ajax({url: "http://www.somedomain.com/connector/browse/" + x + ".json" + "?callback=?",
type: "get", // tried post too
dataType: "json", // tried jsonp too
accepts: "json",
data: req_data, // this is JSON.stringified already
processData:false,
contentType: "application/json; charset=UTF-8;",
success: output
});
The sample data I'm trying to send is this
{"filters":[{"filter":{"attribute":"id","operator":">","value":"2"}},{"filter":{"attribute":"id","operator":"<","value":"7523"}}]}
Has anyone an idea on how to sort this out?
Muchos gracias!
Basically the JS SOP prevents us from sending a POST request and reading the response, but this can be worked around like this:
1) Compose the request data, send it as POST. Don’t expect to receive a response. Don’t use on success, use on complete instead. Add a random-ish variable to the request
2) Temporarily store the response on the server side in a file or session variable or memcached server, use the random var mentioned above as key within the store.
3) send a 2nd JSON AJAX call to fetch the cached object.
With memcached, make sure the cached responses get removed from time to time or expire, in my case the app gets a lot of traffic, it would spam my memcache servers with junk if not set to expire.
here's some sample code

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