I'm trying to make a ajax post request to django this is js snippet
const xhr = new XMLHttpRequest();
console.log(xhr.readyState);
xhr.open('POST', '');
var data = '{% csrf_token %}';
console.log(data);
console.log(typeof(data));
xhr.setRequestHeader('X-CSRF-Token', data);
xhr.onload = function(){
console.log(xhr.readyState);
console.log(xhr.status);
if(xhr.status == 200){
console.log(JSON.parse(xhr.responseText));
}else{
console.log("Something went wrong!!");
}
}
xhr.send({'userId' : userId})
}
This is my error log:
I've been getting a 403 forbidden error can anybody help me out?
This function should get you the csrf-token
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
then:
const csrftoken = getCookie('csrftoken');
to get the csrf-token.
What also might be worth looking at is changing X-CSRF-Token
xhr.setRequestHeader('X-CSRF-Token', data);
to X-CSRFToken
xhr.setRequestHeader('X-CSRFToken', data);
hope this helps
The {% csrf_token %} in the templates page translates to:
<input type="hidden" name="csrfmiddlewaretoken" value="WRWu3DwbdHDl1keRwSqUNrvcwZXqhCzkInEGVftyuwWG0v5kBBzeGrZ34wKpjFB5">
We need to get the CSRF token , i.e., the value of this element:
x = document.getElementsByName("csrfmiddlewaretoken")[0].value;
Then, we need to pass this value to the setRequestHeader method of the JSON request, with "X-CSRFToken" as the first argument:
function requestJSON() {
x = document.getElementsByName("csrfmiddlewaretoken")[0].value;
jsonRequest = new XMLHttpRequest();
jsonRequest.overrideMimeType("application/json");
jsonRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 ) {
var j = JSON.parse(this.responseText);
// do whatever with the JSON data
}
else {console.log(this.status);}
};
jsonRequest.open("POST","url/");
jsonRequest.setRequestHeader("content-type","application/x-www-form-urlencoded");
jsonRequest.setRequestHeader("X-CSRFToken",x);
jsonRequest.send();
}
I observed a very strange behavior. If I set a button from web to upload string to S3, it works fine. But if I set a button from web to bring up a bootstrap modal, then from this modal I set a button to upload the string, it doesn't work.
Frontend is like below in both cases. The difference is whether clicking to run function 'saveToAWS' from web or from modal as 2-step-process, the latter returns xhr.status as 0.
function saveToAWS() {
var file = new File([jsonStr], "file.json", { type: "application/json" });
var xhr = new XMLHttpRequest();
var fn=file.name;
var ft = file.type;
xhr.open("GET", "/sign_s3_save?file-name=" + fn + "&file-type=" + ft);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log('signiture returned')
save_file(file, response.signed_request, response.url);
}
else {
alert("Could not get signed URL.");
}
}
};
xhr.send();
}
function save_file(file, signed_request, url) {
var xhr = new XMLHttpRequest();
xhr.open('PUT', signed_request);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('200');
}
else {
alert('cannot upload file');
}
}
};
xhr.send(file);
}
Backend as Node.js, in order to get a signed URL:
app.get('/sign_s3_save', isLoggedIn, function (req, res) {
var fileName = req.query['file-name'];
var fileType = req.query['file-type'];
aws.config.update({ accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var ac = req.user._id;
var timenow = Date.now().toString();
var fileRename = ac + '/json/' + timenow + '.json';
var s3_params = {
Bucket: S3_BUCKET,
Key: fileRename,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function (err, data) {
if (err) {
console.log(err);
}
else {
var return_data = {
signed_request: data,
url: 'https://' + S3_BUCKET + '.s3.amazonaws.com/' + fileRename
};
res.write(JSON.stringify(return_data));
res.end();
}
});
});
Any suggestion, please?
So I created an ajax request which is here
function postForm(url, data) {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.send(data);
xhr.onreadystatechange = function () {
const DONE = 4; // readyState 4 means the request is done.
const OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
const requestMessage = xhr.responseText;
console.log(requestMessage); // 'This is the returned text.'
const success = requestMessage.search(1);
const error = requestMessage.search(0);
if(success !== -1) {
console.log("success");
removeClass(modal, 'is-active');
closeModal();
window.location.reload();
} else {
console.log("error");
const parent = findAncestor(this, 'folder');
const errorMessage = document.createElement('div');
errorMessage.className = "errorMessage";
errorMessage.innerHTML = requestMessage;
errorMessage.innerHTML = requestMessage.replace('0','');
parent.append(errorMessage);
};
} else if (xhr.status === INT_ERROR) {
console.log(xhr.responseText);
} else {
console.log('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
}
and im having an issue with this part. I want be able to generalize this. when a user presses a button that calls this ajax call, the ajax calls the parent of what they clicked and finds the ancestor and adds errorMessage to the parent of that element. how can i generalize this ajax?
console.log("error");
const parent = findAncestor(this, 'folder');
const errorMessage = document.createElement('div');
errorMessage.className = "errorMessage";
errorMessage.innerHTML = requestMessage;
errorMessage.innerHTML =
requestMessage.replace('0','');
parent.append(errorMessage);
I am trying to play with tvOS, and I have small question regarding handling json call. I have to get some data through an API, let's say for sake of test that I am calling this link
http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json
I tried to use this function with some modification
function getDocument(url) {
var templateXHR = new XMLHttpRequest();
templateXHR.responseType = "json";
templateXHR.open("GET", url, true);
templateXHR.send();
return templateXHR;
}
but didn't work out. Any hints or help ?
If I need to use NodeJS, how can I do that ?
This is one that I got working. It's not ideal in many respects, but shows you something to get started with.
function jsonRequest(options) {
var url = options.url;
var method = options.method || 'GET';
var headers = options.headers || {} ;
var body = options.body || '';
var callback = options.callback || function(err, data) {
console.error("options.callback was missing for this request");
};
if (!url) {
throw 'loadURL requires a url argument';
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
try {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback(null, JSON.parse(xhr.responseText));
} else {
callback(new Error("Error [" + xhr.status + "] making http request: " + url));
}
}
} catch (err) {
console.error('Aborting request ' + url + '. Error: ' + err);
xhr.abort();
callback(new Error("Error making request to: " + url + " error: " + err));
}
};
xhr.open(method, url, true);
Object.keys(headers).forEach(function(key) {
xhr.setRequestHeader(key, headers[key]);
});
xhr.send();
return xhr;
}
And you can call it with the following example:
jsonRequest({
url: 'https://api.github.com/users/staxmanade/repos',
callback: function(err, data) {
console.log(JSON.stringify(data[0], null, ' '));
}
});
Hope this helps.
I tested this one out on the tvOS - works like a charm with jQuery's syntax (basic tests pass):
var $ = {};
$.ajax = function(options) {
var url = options.url;
var type = options.type || 'GET';
var headers = options.headers || {} ;
var body = options.data || null;
var timeout = options.timeout || null;
var success = options.success || function(err, data) {
console.log("options.success was missing for this request");
};
var contentType = options.contentType || 'application/json';
var error = options.error || function(err, data) {
console.log("options.error was missing for this request");
};
if (!url) {
throw 'loadURL requires a url argument';
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.timeout = timeout;
xhr.onreadystatechange = function() {
try {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (xhr.responseType === 'json') {
success(null, xhr.response);
} else {
success(null, JSON.parse(xhr.responseText));
}
} else {
success(new Error("Error [" + xhr.status + "] making http request: " + url));
}
}
} catch (err) {
console.error('Aborting request ' + url + '. Error: ' + err);
xhr.abort();
error(new Error("Error making request to: " + url + " error: " + err));
}
};
xhr.open(type, url, true);
xhr.setRequestHeader("Content-Type", contentType);
xhr.setRequestHeader("Accept", 'application/json, text/javascript, */*');
Object.keys(headers).forEach(function(key) {
xhr.setRequestHeader(key, headers[key]);
});
if(!body) {
xhr.send();
} else {
xhr.send(body);
}
return xhr;
}
Example queries working on Apple TV:
var testPut = function(){
$.ajax({
type: 'PUT',
url: url,
success: successFunc,
error: errFunc,
dataType: 'json',
contentType: 'application/json',
data: data2
});
}
var testGet = function(){
$.ajax({
dataType: 'json',
url: url,
success: successFunc,
error: errFunc,
timeout: 2000
});
}
var getLarge = function(){
$.ajax({
dataType: 'json',
url: url,
success: successFunc,
error: errFunc,
timeout: 2000
});
}
Did you call your function in the 'App.onLaunch'
App.onLaunch = function(options) {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json';
var doc = getDocument(url);
console.log(doc);
}
Might be worth looking at https://mathiasbynens.be/notes/xhr-responsetype-json
I came across this question looking to accomplish the same thing, and was inspired by #JasonJerrett's answer, but found it a bit lacking because in my instance I am using an XML template built in Javascript like this:
// Index.xml.js
var Template = function() {
return `very long xml string`;
};
The issue is that you can't perform the XHR request inside the template itself, because the template string will be returned back before the XHR request actually completes (there's no way to return data from inside an asynchronous callback). My solution was to modify the resource loader and perform the XHR request there, prior to calling the template and passing the data into the template function:
ResourceLoader.prototype.loadResource = function(resource, dataEndpoint, callback) {
var self = this;
evaluateScripts([resource], function(success) {
if (success) {
// Here's the magic. Perform the API call and once it's complete,
// call template constructor and pass in API data
self.getJSON(dataEndpoint, function(data) {
var resource = Template.call(self, data);
callback.call(self, resource);
});
} else {
var title = "Failed to load resources",
description = `There was an error attempting to load the resource. \n\n Please try again later.`,
alert = createAlert(title, description);
Presenter.removeLoadingIndicator();
navigationDocument.presentModal(alert);
}
});
}
// From: https://mathiasbynens.be/notes/xhr-responsetype-json
ResourceLoader.prototype.getJSON = function(url, successHandler, errorHandler) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
if (xhr.readyState == 4) {
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
Then the template function needs to be modified to accept the incoming API data as a parameter:
// Index.xml.js
var Template = function(data) {
return 'really long xml string with injected ${data}';
};
You need to implement the onreadystatechange event on the XHR object to handle the response:
templateXHR.onreadystatechange = function() {
var status;
var data;
if (templateXHR.readyState == 4) { //request finished and response is ready
status = templateXHR.status;
if (status == 200) {
data = JSON.parse(templateXHR.responseText);
// pass the data to a handler
} else {
// handle the error
}
}
};
If you want to call the request on app launch, just add in application.js:
App.onLaunch = function(options) {
var javascriptFiles = [
`${options.BASEURL}js/resourceLoader.js`,
`${options.BASEURL}js/presenter.js`
];
evaluateScripts(javascriptFiles, function(success) {
if(success) {
resourceLoader = new ResourceLoader(options.BASEURL);
var index = resourceLoader.loadResource(`${options.BASEURL}templates/weatherTemplate.xml.js`, function(resource) {
var doc = Presenter.makeDocument(resource);
doc.addEventListener("select", Presenter.load.bind(Presenter));
doc.addEventListener('load', Presenter.request);
navigationDocument.pushDocument(doc);
});
} else {
var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files.");
navigationDocument.presentModal(errorDoc);
}
});
}
In presenter.js add a method:
request: function() {
var xmlhttp = new XMLHttpRequest() , method = 'GET' , url = 'your Api url';
xmlhttp.open( method , url , true );
xmlhttp.onreadystatechange = function () {
var status;
var data;
if (xmlhttp.readyState == 4) {
status = xmlhttp.status;
if (status == 200) {
data = JSON.parse(xmlhttp.responseText);
console.log(data);
} else {
var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files.");
navigationDocument.presentModal(errorDoc);
}
}
};
xmlhttp.send();
},
How to load zip files to the server node js without forms, just using ajax, and unpack this.
I'm trying to do it like:
function sendAjax(request) {
xhr = new XMLHttpRequest();
xhr.open(request.method, request.url);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200){
if (request.callback) {
request.callback(JSON.parse(xhr.response));
}
}
};
var data = null;
if (request.multipleData !== true) {
data = JSON.stringify(request.data);
} else {
var fd = new FormData();
fd.append('file.zip', request.data);
data = fd;
}
xhr.send(data);
}
on the server side I'm doing next:
var body = '';
request.on('data', function (data) {console.log(1111 + data);
body += data;
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e8) {
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
request.connection.destroy();
}
});
request.on('end', function () {console.log(222 + body);
router.route(url.parse(request.url, true), response, body);
});
and
var buf = new Buffer(file.length);
buf.write(file);
var zip = new AdmZip(buf);
var zipEntries = zip.getEntries(); // an array of ZipEntry records
for (var i = 0; i < zipEntries.length; i++) {
console.log(zip.file("content.txt").asText());
But I'm getting error,
...server\node_modules\adm-zip\zipFile.js:66
throw Utils.Errors.INVALID_FORMAT;
^
Invalid or unsupported zip format. No END header found
What the problem?