AJAX GET request not sending data to Django - javascript

I am trying to send data in localStorage via an AJAX GET request to Django, but the Django server never receives it. I am confident that I have data in localStorage("preselection") as console.log shows it. Here is my JavaScript snippet which is inside index.html (am a beginner, so apologies if this is basic and I'm avoiding jQuery for now):
var preselection = localStorage.getItem("preselection");
function previous_selection () {
if (localStorage.getItem("preselection") != null) {
console.log("PRESELECTION IS: ", preselection);
const data = new FormData();
data.append("preselection", preselection);
const request = new XMLHttpRequest();
request.open('GET', '/');
request.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
request.send(data);
request.onload = () => {
var url = '/prebasket';
window.location.href = url;
};
return false;
}
}
previous_selection();
Below is my view in views.py. I tried request.GET.dict(), request.GET.get(), request.GET.copy(), etc. and my data comes as JSON in case it matters, but Django just gets an empty {} or Null for q_preselection:
#login_required
def index(request):
q_preselection = request.GET.dict()
print(q_preselection) # comes back empty
context = {
#irrelevant
}
return render(request, "pizza/index.html", context)

XMLHttpRequest send() does not pass the body data for GET
send() accepts an optional parameter which lets you specify the
request's body; this is primarily used for requests such as PUT. If
the request method is GET or HEAD, the body parameter is ignored and
the request body is set to null.
Use POST instead, you almost never want to have GET request with BODY ( parameters should be passed through URL for GET)

Related

Not receiving correctly multipart form data with PHP Klein

I have a big issue with receiving data from multipart form request sent by my reactJS front-end to the PHP api handled with Klein.
I just tried to send with Javascript this fetch request
const data = new FormData();
data.append('sourceId', sourceId);
data.append('customerId', customerId);
const resp = await fetch(URL_CREATE_DOC, {
method: 'POST',
body: data,
headers: {
'Content-Type': 'multipart/form-data; boundary=stackoverflowrocks',
}
and then to receive in my PHP Api with this
var_dump($request->files()->all());
but there's no data ! In the header, I see that the data is well sent by the front and when I make a var_dump($request->server()), I see the CONTENT_LENGHT changing if I send files. I think I don't do something well but how can I get the data from the multipart request ?
According to the readme:
$request->
id($hash = true) // Get a unique ID for the request
paramsGet() // Return the GET parameter collection
paramsPost() // Return the POST parameter collection
paramsNamed() // Return the named parameter collection
cookies() // Return the cookies collection
server() // Return the server collection
headers() // Return the headers collection
files() // Return the files collection
body() // Get the request body
params() // Return all parameters
params($mask = null) // Return all parameters that match the mask array - extract() friendly
param($key, $default = null) // Get a request parameter (get, post, named)
files() is exclusively for uploaded files, which you don't seem to have; your values can be found in POST data, which means any one of paramsPost(), params() or param($name) would be correct.

How do I send data from Plain Old Javascript to Flask and get CSV data back using XMLHTTPRequest?

I am stuck on an issue. I am hoping to send data back to my Flask backend using Plain Old Javascript's XMLHTTPRequest object. I hope to get CSV data in String format back.
function ajax_request() {
const request = new XMLHttpRequest();
let csrf_token = '{{ csrf_token() }}';
let json_data = {
'data' :[]
};
json_data['data'].push(data);
// Define what happens on successful data submission
request.addEventListener('load', function(event) {
console.log("This Worked");
});
// Define what happens in case of error
request.addEventListener('error', function(event) {
alert('Error: AJAX request failed.');
console.log(request.responseText);
} );
// Open our request and set the headers.
request.open("POST", "/my-route", true);
request.setRequestHeader("X-CSRFToken", csrf_token);
// Add the required HTTP header for form data POST requests
request.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
request.send(json_data);
}
This seems fair enough. I am not sure whether I can send json with the x-www-form-urlencoded format. I might need json instead but am unsure if that then means the response needs to be json, which is not what I want. I keep trying to play around with this and getting nowhere
My app.py is
#dashboard_blueprint.route('/my-route', methods=["GET", "POST"])
def my_page():
# If the user is changing the variables / giving us data
if request.method == "POST":
print(request.form)
json_data = request.form.get('data')
# parse on json data
csv_data = ....
return csv_data
else:
print(form.errors)
I tried request.json, request.data and some other combinations. What is odd is that I can get it to work when I do not pass any variables to get the new CSV data but just make the request for CSV data without any variables. So I seem quite stuck. Any advice is appreciated!

Access parameters in a XMLHttpRequest Google Apps Script

I am currently trying to access the parameters of a POST request using Google Apps Script. I can logger the params object using e.parameter though i cannot seem to access the keys of the object by by using e.parameter.name.
XMLHttpRequest
var http = new XMLHttpRequest();
var url = "myappURL";
var params = JSON.stringify({employeeStatus: "Active", name: "Henry"});
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
// call back function
} // end callback
http.send(params);
Google Apps Script
function doPost(e) {
if (typeof e !== 'undefined') {
Logger.log(e.parameter.name); // does not work (undefined)
} // end if
} // end doPost
There are subtle quirks with the different ways data is posed via http. For instance I notice that you are using Content-type "application/x-www-form-urlencoded" when the usual header for json data is Content-Type: application/json.
I added a line that just returns the contents of the e variable so you can see what is returned.
I used curl to debug it with the following command.
curl -H "Content-Type: application/json" ---data "{status:123}" https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec
The response I received was:
{"parameter":{},"contextPath":"","contentLength":12,"queryString":null,"parameters":{},"postData":{"length":12,"type":"application/json","contents":"{status:123}","name":"postData"}}
You can see that in my case the json was returned in the contents field rather than the parameters.
You could try this with your script to see what you get. You could also try changing the Content-Type.
After Further testing I think you would be better submitting your fields a form data rather than json. I have been able to get the paramer back by amending your javascript to:
var http = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec";
var params = "employeeStatus='Active'&name='Henry'";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
if (http.readyState==4) {
//alert the user that a response now exists in the responseTest property.
console.log(http.responseText);
// And to view in firebug
// console.log('xhr',xmlhttp)
}
} // end callback
http.send(params);

XHR in Chrome Extension with CI

I'm sending a POST from a chrome extension content script to a server I control. I setup the permissions in the manifest ok. Here is my XHR code. (I want to avoid jQuery for this). Its sending an empty responseText
var xhr = new XMLHttpRequest();
xhr.open("POST",'http://mysite.com/make',true);
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
var res = JSON.parse(xhr.responseText);
console.log(res);
}
}
xhr.send({'textbox':data[0].user,'from':'extension'});
data[0].user is an object I got directly from the Twitter API
in my CI controller I have
$user = $this->input->get_post('textbox', TRUE);
$from = $this->input->get_post('from', TRUE);
$fullURL = 'http://www.google.com'; //example of a URL from code.
$json = $this->output->set_content_type('application/json');
$json->set_output(json_encode(array('URL' => $fullURL)));
The response text is empty
a jquery call on the other hand works fine
$.post("http://mysite.com/make", { 'textbox': data[0].user, 'from':'jquery' },
function(data) {
console.log(data);
});
Reason is simple, JQuery post method can accept JSON and then convert it to string and send to the server.
What you are trying to do is to directly send JSON here :
xhr.send({'textbox':data[0].user,'from':'extension'}) // Incorrect way
send method should either accept NULL or a string which is generally made up of QueryString Parameters like.
xhr.send("textbox="+ data[0].user + "&from=extension"); // Correct way
This will ensure that your data goes to the appropriate URL with textbox and from as post request parameters.
and queryString will be generated like textbox=username1234&from=extension in the packet's body unlike one goes in Get with the headers along side the URL.
jQuery's post method makes it simpler for you to format data you send using JSON and then internally it converts that to a queryString to send parameters.
You can't directly send Javascript object like that with an XHR object!
Also checkout this example:
http://beradrian.wordpress.com/2007/07/19/passing-post-parameters-with-ajax/

Need to post large amount of data using xmlHttprequest

I need to pass huge amount of data to server without page loading. I have this code:
var GlType = "<%=GlType %>";
var pageUrl = "SelectAccount.aspx?callback=true&AccountList=" +accountList +"&AnalysisDate="+analysisDate+"&GlType="+GlType;
if (window.XMLHttpRequest)
{
var xmlRequest = new XMLHttpRequest();
}
else
{
var xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlRequest.open("POST", pageUrl, true);
xmlRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlRequest.send(null);
I am have passed using query string its exceeded the maximum Length of query string. Help me on this..
Since you're already using the POST method, you can pass data in the body.
xmlRequest.send("Field1=abc&Field2=def");
You can retrieve the data on the server, e.g. in ASP.NET:
if (Page.Request.Form["Field1"] == "abc") ...
For GET method you can only use the query string for transferring data.
You're sending the request via post, but putting everything in the query string!
Instead, you should send the data as the body of the request (passed to the send method).

Categories