Display JsonResponse data in template - ajax

I want to send the JsonResponse data in the demo.html and display in it. what is wrong in my code. please help me to solve it.
function ComAction() {
let xhr = new XMLHttpRequest(),
data = new FormData();
data.append('csrfmiddlewaretoken', getCookie('csrftoken'));
brands.forEach(function (brand) {
data.append('brand', brand);
});
xhr.open('POST', 'compare_in/', true);
xhr.onload = function () {
if (xhr.status === 200) {
data = JSON.parse(xhr.responseText);
console.log(data);
alert('Data received successfully. Brands are ' + data.brands);
window.location.assign({% url 'demo' %});
} else if (xhr.status !== 200) {
alert('Request failed.');
}
};
xhr.send(data);
}
it's my urls:
urlpatterns = [
path('compare_in/', views.compare, name='compare'),
path('demo/', views.demo, name='demo'),
]
it's my views:
def compare(request):
if request.method == 'POST':
compare_res = request.POST.getlist('brand')
d3 = {'brand':{'x', 'y'}, 'color':{'black', 'white'}}
response_data = {
'brands': d3,
'redirect_url': 'http://127.0.0.1:8000/demo/'}
return JsonResponse(response_data)
return render(request, 'prodcutSearch/compare_in.html')
def demo(request):
return render(request, 'prodcutSearch/demo.html')

Related

ExpressJS Ajax request is getting redirected/Aborted

I'm trying to make an AJAX request to one of my routes which should return some data, but I can't solve the fact that when I make an AJAX request I'm being redirected to the route I'm requesting.
How can I prevent this from happening?
Ajax:
var request = new XMLHttpRequest();
var url = 'http://localhost:3000/signin';
var credentials = {
email: document.getElementsByName('email')[0].value,
password: document.getElementsByName('password')[0].value
};
JSON.stringify(credentials);
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
if(request.status == 200) {
if(request.readyState == 4) {
var data = JSON.parse(request.responseText);
console.log(data);
}
} else if(request.status == 400) {
console.log('There was an error 400');
} else {
console.log('something else other than 200 was returned');
}
}
}
request.open('POST', url, true);
request.setRequestHeader('Accept', 'application/json');
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send(credentials);
Api Endpoint:
app.post('/signin', function(req, res) {
request.post({
url:'http://localhost:3000/api/authenticate',
form: {
email: req.body.email,
hashed_password: req.body.password
},
}, function(err, httpResponse, body) {
console.log(req.xhr);
console.log(req.headers);
if (err) {
return console.error('failed:', err);
}
console.log('successful! ', JSON.parse(body));
//user.token = data.token;
res.json(JSON.parse(body));
});
});

Django AJAX form, no POST data in view

I have some contact form and JS/Angular code sending it to view for some validation and mailing.
contact_form.js
(function() {
var app = angular.module('contactForm', []);
app.config(function ($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});
app.controller('contactFormController', ['$http', '$scope', function($http, $scope){
$scope.contact_form = {};
this.send = function(form){
if (form.$valid){
$http.post('/contact_form_submit/', {'form': $scope.contact_form}).
success(function(data, status, headers, config) {
if (data.status == 1) {
$scope.msg = 'Twoja wiadomość została wysłana.';
$scope.contact_form = {};
$scope.contactForm.$setPristine();
}
else if (data.status == 'delay')
$scope.msg = 'Odczekaj.';
}).
error(function(data, status, headers, config) {
$scope.msg = 'Wystąpił błąd.';
if (status == '403')
$scope.msg += ' Włącz cookie!';
});
}
else
this.msg = 'invalid!';
};
}]);
})();
view.py
def contact_form_submit(request):
return return_json(request)
if not request.is_ajax() or (request.method != 'POST'):
raise SuspiciousOperation
response_data = {}
# dealing with existing (or not) delay entry
try:
if request.session['mailer_delay'] > str(timezone.now()):
response_data['status'] = 'delay'
return return_json(response_data)
except KeyError:
pass
# validation
form_data = {}
for field in ['name', 'email', 'phone', 'subject', 'text']:
form_data[field] = request.POST.items()
# mailing
mailer = send_mail('Subject here', 'Here is the message.', 'from#example.com',
['to#example.com'], fail_silently=False)
request.session['mailer_delay'] = str(timezone.now()+timedelta(seconds=60))
response_data['status'] = mailer
return return_json(response_data)
and the return_json()
def return_json(data):
from django.http import HttpResponse
import json
return HttpResponse(json.dumps(data), content_type="application/json")
The problem is i get no items at all in request.POST in view. Firebugs tells me that data was sent correctly, but there's no in view.
Someone knows the answer what's wrong?
Ok, i got it. All data was in request.body, not request.POST.
Could anyone explain why? I've read the docs, but still it's not clear for me.

Backbone collection fetch error with no information

I have a strange problem with the fetch of a backbone collection I am working with. In one particular instance of my code I perform a fetch (exactly how I do it in other areas of the code which all work fine), the fetch never seems to make it to the server and the developer tools shows the request as red with the word (canceled) in the status/text field.
I've walked this through into the backbone sync method and I see the $.ajax being built and everything looks fine. Has anyone run into this problem?
here is my code if it helps, this is a function that calls two .ashx services to first check for a file's existence then to open it. The part that isn't working for me is the "me.collection.fetch().
openDocument: function () {
var me = this,
fileId = me.model.get('id'),
userId = Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
fileRequest = '/genericHandlers/DownloadFile.ashx?id=' + fileId + '&userId=' + userId,
fileCheck = '/genericHandlers/CheckFileExistance.ashx?id=' + fileId + '&userId=' + userId;
//hide tooltip
me.hideButtonTooltips();
// Check for file existance
$.ajax({
url: fileCheck
})
.done(function (data) {
if (data && data === "true") {
document.location.href = fileRequest;
me.collection.fetch();
} else if (!!data && data === "false") {
"This file is no longer available.".notify('error');
}
})
.fail(function (data) {
"Something went wrong during the File Existance check".notify('error');
"Something went wrong during the File Existance check".log(userId, 'error', 'Docs');
});
},
my collection:
// docsCollection.js - The collection of ALL the documents available to a given user
// Document Collection
Dashboard.Collections.DocsCollection = Backbone.Collection.extend({
model: Dashboard.Models.DocumentUploadModel,
url: function () {
return 'apps/docs/Docs/' + this.userId;
},
initialize: function (options) {
this.userId = options.userId;
this.deferredFetch = this.fetch();
},
comparator: function (model) {
return -(new Date(model.get('expirationDate')));
},
getDaysSinceViewedDocuments: function () {
return this.filter(function (model) {
return model.get('daysSinceViewed') !== null;
});
},
getNewDocuments: function () {
return this.filter(function (model) {
return model.get('isNew');
});
},
getExpiredDocuments: function () {
return this.filter(function (model) {
return model.get('isExpired');
});
}
});
and my model:
Dashboard.Models.DocumentUploadModel = Backbone.Model.extend({
defaults: {
fileArray: [],
name: '',
description: '',
accesses: [],
tags: [],
expirationDate: ''
},
initialize: function () {
this.set({
userId: Dashboard.Data.Models.UserModel.get("UserInfo").User_ID,
expirationDate: (this.isNew()) ? buildExpirationDate() : this.get('expirationDate')
}, { silent: true });
function buildExpirationDate() {
var date = new Date((new Date()).getTime() + 24 * 60 * 60 * 1000 * 7),
dateString = "{0}/{1}/{2}".format(date.getMonth() + 1, date.getDate(), date.getFullYear());
return dateString;
}
},
firstFile: function () {
return this.get('fileArray')[0];
},
validate: function (attributes) {
var errors = [];
if (attributes.name === '' || attributes.name.length === 0)
errors.push({
input: 'input.txtName',
message: "You must enter a name."
});
if (attributes.description === '' || attributes.description.length === 0)
errors.push({
input: 'textarea.taDescription',
message: "You must enter a description."
});
if (errors.length > 0)
return errors;
return;
},
sync: function (method, model, options) {
var formData = new FormData(),
files = model.get("fileArray"),
$progress = $('progress'),
success = options.success,
error = options.error;
// Nothing other than create or update right now
if (method !== "create" && method !== "update")
return;
// Build formData object
formData.append("name", model.get("name"));
formData.append("description", model.get("description"));
formData.append("accesses", model.get("accesses"));
formData.append("tags", model.get("tags"));
formData.append("expirationDate", model.get("expirationDate"));
formData.append("userId", model.get("userId"));
formData.append("isNew", model.isNew());
// if not new then capture id
if (!model.isNew())
formData.append('id', model.id);
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
xhr = new XMLHttpRequest();
xhr.open('POST', '/genericHandlers/UploadDocsFile.ashx');
xhr.onload = function () {
if (xhr.status === 200) {
if (success)
success();
} else {
if (error)
error();
}
}
if ($progress.length > 0) {
xhr.upload.onprogress = function (evt) {
var complete;
if (evt.lengthComputable) {
// Do the division but if you cant put 0
complete = (evt.loaded / evt.total * 100 | 0);
$progress[0].value = $progress[0].innerHTML = complete;
}
}
}
xhr.send(formData);
},
upload: function (changedAttrs, options) {
this.save("create", changedAttrs, options);
}
});
You're assigning a value to document.location.href before you try to fetch your collection:
document.location.href = fileRequest;
me.collection.fetch();
Changing document.location.href will change the whole page and in the process, any currently running JavaScript will get shutdown so I wouldn't expect your me.collection.fetch() to ever get executed.

ajax JSON dump as array

I have a simple ajax script which returns a json dump from the server:
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
function getIslandName() {
var islandGroup = document.getElementById("id_island_group").value;
var url = ".../find_island?island_group=" + escape(islandGroup);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState == 4)
if (request.status == 200)
var data = JSON.decode(request.responseText);
update(data);
//document.getElementById("ajax_response").innerHTML = request.responseText;
else if (request.status == 404)
alert("Request URL does not exist");
else
alert("Error: status code is " + request.status);
}
function update(data) {
for (var key in data) {
alert(data[key]);
}
}
The problem seems to be in the updatePage() function. If I uncomment this line:
//document.getElementById("ajax_response").innerHTML = request.responseText;
the responseText json dump is displayed as expected. e.g.:
["Foo Island", "Bar Island", "Darwin Island"]
Also if I construct a fresh data array within the updatePage() function like so:
function updatePage() {
var string = "Something something ajax";
if (request.readyState == 4)
if (request.status == 200)
var data=new Array();
data[0]="Foo Island";
data[1]="Bar Island";
data[2]="Darwin Island";
update(data);
}
The update() function works as expected and gives the expected alert output.
Any suggestions as to what I'm doing wrong will be much appreciated.

Control flow with XmlHttpRequest?

XmlHttpRequest works through callbacks. So how can I return a value? I tried to set a global variable, but that doesn't seem to be working.
var response = null; // contains the most recent XmlHttpRequest response
// loads the info for this username on the page
function loadUsernameInfo(username) {
getUserInfo(username);
var profile = response;
if (profile) {
// do stuff
}
else {
indicateInvalidUsername(username);
}
}
getUserInfo() can't return a result, because of the callback:
function getUserInfo(username) {
var request = createRequest();
request.onreadystatechange = userObjFromJSON;
var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
var url = "url.php?url=" + twitterURL;
request.open("GET", url, true);
request.send(null);
}
The callback:
function userObjFromJSON() {
if (this.readyState == 4) {
alert(this.responseText);
response = this.responseText;
}
}
How can I get the response back to loadUsernameInfo()?
You can do synchronous requests, though it is not recommended - the A is for Asynchronous... But the general idea to implement this correctly would be:
var response = null; // contains the most recent XmlHttpRequest response
// loads the info for this username on the page
function loadUsernameInfo(username) {
getUserInfo(username, onLoadUsernameComplete);
}
function getUserInfo(username, oncomplete) {
var request = createRequest();
request.__username = username;
request.onreadystatechange = oncomplete;
var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
var url = "url.php?url=" + twitterURL;
request.open("GET", url, true);
request.send(null);
}
function onLoadUsernameComplete(req) {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var profile = req.responseXML;
if (profile) {
// do stuff
}
else {
indicateInvalidUsername(req.__username);
}
}
}
}

Resources