Unable to post json data using javascript - javascript

function myAjax(type, url, data){
url = type == "GET"? (url+"?"+data): url;
var xhttp = new XMLHttpRequest();
if (!window.XMLHttpRequest) xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open(type, url, true);
xhttp.setRequestHeader('Content-Type', 'application/json');
console.log(JSON.stringify(data));
type=="GET"?xhttp.send():xhttp.send(JSON.stringify(data));
}
myAjax("POST","http://localhost:8008/testv/",
{csrfmiddlewaretoken:"{{csrf_token}}",sss: 'sssssssss',});
I'm using django 2.0 with python 3.6. I know csrf_token is required to post data and I am passing it. But still in javascript console I get:
403 Forbidden error.
In servers console I get:
CSRF token missing or incorrect.
What am I doing wrong here?

Related

Why is my firefox extension only posting data when on localhost and not on any other websites?

I have a Spring server and am using xhttp to post data to the server from a firefox extension. The data will only send from localhost and not from any other websites.
'''javascript
function sendo(keys) {
try{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8080/index", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("X-Data", keys);
xhttp.send("{\"name\": \"Urmi\"}");
console.log("Sent " + keys);
}
catch(e){
console.log(e);
}
}
'''
When this function is called while on localhost, everything executes correctly and the keys are correctly posted to the server. When on any other website, the code seemingly runs, as the console.log at the end of the try statement runs, but nothing is ever posted to the server.

Can't download file with HTTP request: response for preflight is invalid

I'm trying to use an HTTP request in JavaScript to retrieve a file from the Slack API. I managed to get the url_private_download of the file, but if I try to make an HTTP GET request using that URL, I get an error in the console saying that: Failed to load url_private_download: Response for preflight is invalid (redirect).
Here's my code:
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
console.log(xmlHttp.responseText);
}
};
xmlHttp.open("GET", url_private_download, true);
xmlHttp.setRequestHeader("Authorization", "Bearer " + my_slack_token);
xmlHttp.setRequestHeader('Access-Control-Allow-Headers','*')
xmlHttp.send(null);

Parsing JSON url in pure javascript

I'm trying to parse a url in pure javascript, just one executable file.
url = 'http://myurl.php?format=json'
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var mystuff = JSON.parse(request.responseText);
} else {
// some error
}
};
request.onerror = function() {
// some error
};
request.send();
console.log(mystuff);
When I do this, I get a XMLHttpRequest is not defined error. What's the best way to do this, the simplest way?
Thank you.
This statement is wrong you should url as a variable not "url" as a string,
request.open('GET', 'url', true);
to
request.open('GET', url, true);
Furthermore the xmlHttpRequest works only on some versions of browsers.
You could do something like this to check whether xmlhttpRequest works on your browser,
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}

XMLHttpRequest doesn't send some headers

The title explains my problem clearly. I am testing the AJAX requests of my application but I cannot send some headers, for example Authorization header.
For testing I use this endpoint to echo me the headers I sent. Here is my javascript code:
var loadDoc = function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
console.log(JSON.parse(this.responseText));
};
}
xhttp.open("GET", "http://headers.jsontest.com/", true);
xhttp.setRequestHeader("Authorization", "JWT token");
xhttp.send();
}
I can send the exact same request with python's requests module. But I can't send it with XMLHttpRequest. XMLHttpRequest can send the Content-Type header and the server echoes me the headers but not Authorization.
What is going on here?

XMLHttpRequest alters text in UTF-8

While processing a huge XML client-side, got stuck with the following issue: some unicode characters are replaced with unreadable sequences, so server cannot parse that XML. Testing like this:
var text = new XMLSerializer().serializeToString(xmlNode);
console.log(text);
var req = new XMLHttpRequest();
req.open('POST', config.saveUrl, true);
req.overrideMimeType("application/xml; charset=UTF-8");
req.send(text);
Logging still shows the correct string:
<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />
While in the request (Chrome dev tools) and at server side it appears modified like this:
<Language Self="Language/$ID/Czech" Name="$ID/Czech" SingleQuotes="‚‘" DoubleQuotes="„“" PrimaryLanguageName="$ID/Czech" SublanguageName="$ID/" Id="266" HyphenationVendor="Hunspell" SpellingVendor="Hunspell" />
Original encoding of the XML file is UTF-8, too. Absolutely the same behavior when using jQuery.
Check that overrideMimeType use uppercase "UTF-8" or lowercase "utf-8"
Make sure that string before javascript calculation was in utf-8 (check page charset)
Use escape/encodeURIComponent/decodeURIComponent before send it to server and unescape it on server
Try application/x-www-form-urlencoded ans send xml like plain text
P.S. Modified string is in ISO-8859-15
It seems to do so.
I have here data json parameter that includes a string "Lääke" (finnish word), that i sent to server via ajax.
This did NOT work, server app did not receive 'ää' but '??':
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
status = this.responseText;
if (status === "OK") {
window.location.assign("ackok.html");
}
else {
window.location.assign("ackerror.html");
}
}
};
xhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);
xhttp.send();
This did work, server received 'ää':
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
status = this.responseText;
if (status === "OK") {
window.location.assign("ackok.html");
}
else {
//orderStatusElement[0].innerHTML = "<b>Palvelimella jokin meni vikaan. Yritä myöhemmin uudelleen </b>";
window.location.assign("ackerror.html");
}
}
};
xhttp.open("POST", "ProcessOrderServlet?Action=new&Customer="+data, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();

Categories