Using flask, ajax - get response header value - ajax

I'm sending request through ajax,
sending response through Flask.
This is my code
ajax
'''
$.ajax({
url:'/get',
type: "post",
data: {"hi":"hello"},
success(function(data, textStatus, jqXHR){
console.log(jqXHR.getResponseHeader('token'));
})
})
'''
Flask
'''
#app.route('/get', methods=['POST'])
def hello():
data = {'result': 0}
resp = make_response(data)
resp.headers['hi'] = 123
return resp'''
If I run this, I can see response header ('hi', 123) in chrome inspection. But NO CONSOLE LOG.
Is there anything wrong with my code?

There's no token response header in your server response, try reading hi header:
$.ajax({
url:'/get',
type: "post",
data: {"hi":"hello"},
success(function(data, textStatus, jqXHR){
// this line:
console.log(jqXHR.getResponseHeader('hi'));
})
})

Related

POST method with ajax and express

I want to send and object model to my server
$.getJSON(request, function(data){
$.ajax({
type: "POST",
data: {data},
contentType: "application/json",
url: "/movie",
success: function(){
console.log("Movie data send");
}
});
express:
app.post("/movie", function(req, res){
console.log(req.body.data);
});
The error i'm getting on the console browser is:
POST http://localhost:8888/movie 400 (Bad Request)
send # jquery.min.js:4
ajax # jquery.min.js:4
(anonymous) # session:47
i # jquery.min.js:2
fireWith # jquery.min.js:2
A # jquery.min.js:4
(anonymous) # jquery.min.js:4
and in my server console:
SyntaxError: Unexpected token d
What am I doing wrong? I checked other similar questions but I don't know how to apply their solutions to my case
EDIT: I changed the code, now it looks like this:
var movie = JSON.stringify(data);
$.ajax({
type: "POST",
data: movie,
dataType: "json",
url: "/session/movie",
success: function(){
console.log("Movie data send");
}
});
server:
app.post("/session/movie", function(req, res){
console.log(req.body.movie);
});
And now I'm getting undefined on the server console ...

Getting data from get request?

I'm sending an ajax request like so:
$.ajax({
type: "GET",
url:"/game/set",
data: JSON.stringify({colour: col, size: size}),
success: function(){console.log("SUCCESS.")},
dataType: 'json'
});
I can receive the request on the server just fine, but I can't figure out how to pull the data from it before responding. He is how I'm handling it.
var jsonString = '';
req.setEncoding('utf8');
req.on('data', function (data) {
jsonString += data;
});
req.on('end', function () {
reqData = JSON.parse(jsonString);
respond(200, JSON.stringify(reqData));
});
but I seem to get this error when trying to parse.
SyntaxError: Unexpected end of input
You can't send data in a GET request. Try POST instead.

How do django send ajax response?

Here is my code ,I got response is 200 OK but ajax came to error part
I can't figure it out
My html:
$(".statics").click(function(){
var name = $(this).attr("data-name");
$.ajax({
url: 'statics/',
data: {
'name':name
},
type: 'POST',
async: false,
dataType: 'json',
success: function(dataArr){
console.log("ssss:",dataArr)
if(dataArr == "IS_PASS"){
alert('PASS!');
}else if(dataArr == "NOT_PASS"){
alert('NOT_PASS');
}
},
error: function(ts){
console.log("eeee:",ts)
alert('fail');
},
});
});
My views.py
def statics_r(request):
if request.is_ajax():
name = request.POST['name']
...
if is_pass:
return HttpResponse("IS_PASS")
else:
return HttpResponse("NOT_PASS")
And the console is : eeee: Object {readyState: 4, responseText: "NOT_PASS", status: 200, statusText: "OK"}
Why it is not success???
For an ajax response, you should be returning json, the easiest way is to use the JsonResponse class instead of HttpResponse, or set the content_type
HttpResponse("{'result': 'IS_PASS'}", content_type="application/json")
You would need to adjust your success function to access the results, i.e dataArr.result

Ajax POST with csrfmiddlewaretoken and csrftoken cookie set still gets django 403 Forbidden

I've read that both the csrfmiddlewaretoken and the csrftoken cookie have to be the correct value for a django POST request to succeed (django: csrftoken COOKIE vs. csrfmiddlewaretoken HTML Form value). This is the case for me yet I still get a 403:
In the chrome console:
document.cookie
returns
"csrftoken=Wt9eeJop5Vb3OmeNTvogegckm1pVM5MD"
but
$.get('https://learningdollars.fwd.wf/csrftoken/', function(data){
console.log(data)
token = $.parseHTML(data)[0].value
console.log(token)
$.ajax({
type: "POST",
url: 'https://learningdollars.fwd.wf/confirmemail/',
data: {email: 'gdasu#alumni.stanford.edu', csrfmiddlewaretoken: token},
contentType: "application/json"
})
.done(function(response) {
console.log('done!')
})
.fail(function(error) {
console.log('fail!')
})
})
returns
> Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
> <input type='hidden' name='csrfmiddlewaretoken' value='Wt9eeJop5Vb3OmeNTvogegckm1pVM5MD' />
> Wt9eeJop5Vb3OmeNTvogegckm1pVM5MD
> POST https://learningdollars.fwd.wf/confirmemail/ 403 (Forbidden)
> fail!
I have
'django.middleware.csrf.CsrfViewMiddleware',
activated in my django middleware.
My root urls.py contains:
url(r'^csrftoken/$', views.get_csrf_token),
url(r'^confirmemail/$', views.confirm_email, name='confirm_email'),
And, my views are:
def get_csrf_token(request):
c = {}
c.update(csrf(request))
print c
return render_to_response('csrf.html', c)
def confirm_email(request):
print 'here'
return JsonResponse({'response': 0})
And by the way, the contents of csrf.html are just the csrftoken (inside an input tag):
{% csrf_token %}
What am I doing wrong?
Well, I found a solution. It was just sending in the data as a URI rather than as json. (I by the way tried specifying dataType: 'json' in the above to no avail.) The following is in the chrome console:
> email = 'gdasu#alumni.stanford.edu'
< "gdasu#alumni.stanford.edu"
> csrftoken = 'L2MxD1XQIF1Xto5NkzUgGUYiHPyyz3K5'
< "L2MxD1XQIF1Xto5NkzUgGUYiHPyyz3K5"
> $.ajax({
type: "POST",
url: 'https://learningdollars.fwd.wf/confirmemail/',
data: "email="+ encodeURI(email) + "&csrfmiddlewaretoken=" + encodeURI(csrftoken),
success: function(data) { console.log(data); }
})
< Object {response: 1}
Still unsure what I was doing wrong on the json side, but the following is what I tried:
$.ajax({
type: "POST",
url: "https://learningdollars.fwd.wf/confirmemail/",
data: JSON.stringify({ email: email, csrfmiddlewaretoken: csrftoken }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
You can forbid Django CSRF by adding csrf_exempt to tell the view not check csrf token.
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def get_csrf_token(request):
c = {}
c.update(csrf(request))
print c
return render_to_response('csrf.html', c)
#csrf_exempt
def confirm_email(request):
print 'here'
return JsonResponse({'response': 0})

JQuery.Ajax POST request to Azure returning bad request

I have mobile services configured on my Azure database and I am trying to send a POST request to update the data. The service keeps returning a bad request and I fear its because of the format of my JQuery.Ajax request. I have tried a number combinations but I can't see what I'm doing wrong. The schema of the request can be found here (http://msdn.microsoft.com/en-us/library/windowsazure/jj677200.aspx), any help would be appreciated.
function RegisterPatient(){
var wsUrl = "https://vervemobile.azure-mobile.net/tables/ref_*****";
var data = {"YearOfBirth":1970,"Sex":"M","ControlGroupMember":false,"OrganisationID":null,"Type":null}
$.ajax({
url:wsUrl,
type: "POST",
data:data,
beforeSend: function (request)
{
request.setRequestHeader("X-ZUMO-APPLICATION", "******");
request.setRequestHeader("Content-Type", "application/json");
},
success: function(data, textStatus, jqXHR)
{
alert(JSON.stringify(data));
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(JSON.stringify(jqXHR));
console.log(JSON.stringify(jqXHR));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
}
});
}
Thanks in Advance,
Bradley
The request requires a json body to be sent, so you have to stringify your data.
...
$.ajax({
url:wsUrl,
type: "POST",
data: JSON.stringify(data),
...

Resources