I know that for example:
def home(request):
if request.method == 'POST':
k = 'p' % 1
return HttpResponse(simplejson.dumps(dict()), mimetype='application/javascript')
else:
k = 'p' % 1
return render_to_response('index.html',locals());
url(r'^$', 'app.home'),
If I use the browser to visit the home page, django will return a debug page to me and show that there is an error in k = 'p' % 1
But if I use the $.ajax() to send a post to this view, the console of chrome only show POST http://(some url here):8000/ 500 (INTERNAL SERVER ERROR)
so is there any good way to debug the second case?
I have no idea about debug the django, is there anybody have better way to debug the django?
thanks
have a look at sentry (and the corresponding raven)
(the Network tab should be able to show you the request and the corresponding response. i believe newer django versions even give you a more bare-bones version of the stacktrace if the request was ajax)
There is an error CallBack in ajax. It will spew out the actual error.
$.ajax({
type: 'POST',
url: '{% url 'url_name_for_your_view_here' %}',
data: {'csrfmiddlewaretoken': '{{csrf_token}}'},
dataType: "text",
success: function(response) {
//do something here if everything goes well
},
error: function(rs, e) {
alert(rs.responseText); //throw actual error, just for debugging purpose
alert('Oops! something went worng..'); // alert user that something goes wrong
}
});
There are a number of third party apps make debugging ajax easier. I've used this in the past with success: https://github.com/yaniv-aknin/django-ajaxerrors
Or if you prefer not use an app, chrome developer tools will likely be enough, as is suggested in this thread: Django: Are there any tools/tricks to use on debugging AJAX response?
Related
I've got a problem and I have no idea why it appears. The circumstances of its appearance are very strange for me...
I've got a POST REST service /login. It expects json {"email":email,"password":password}. I am using ajax and everything works correctly... except for the case when email (is in real format) contains '#' sign and some letters before and after( I know it is strange but only in this case such error appears). When I pass email i.e "mum#mum.com" then few things are happening:
I see that browser sends GET request instead of POST and obtains 304 http status
In the browser console I see infomation "The development server has disconnected. Refresh the page if necessary" and page refreshes automatically
The above things happen only when email is in format I described above.When I pass "aaa" or "aaa#" as email everything works correctly(browser sends POST request and I don't get error in console).
I honestly have no idea why this happens... would be extremely grateful for your help and I will answer all your questions concerning this.
PS.
When I use REST web service tool in IntellJ everything always works fine.
handleLogin() {
const input = {
email: this.state.email,
password: this.state.password
};
$.ajax({
url: CONST.USER_SERVICE + "/login",
type: "POST",
data: JSON.stringify(input),
contentType: "jsonp"
})
.fail(function () {
alert("Wrong data");
})
.always(function (arg1, arg2, arg3) {
if (arg3.status === 200) {
alert("ok!");
}
}.bind(this));
}
Try making the ajax request like data: input without stringify. Ajax expects an object.
I am new to Django.I am sending a ajax POST request to a python function which in turn stores the data in the variables from the ajax and return the HttpResponse .So i checked request.method in python its coming as GET.
$.ajax({
url:"create_post/",
type:"POST",
data : {F_Name: First_Name ,L_Name: Last_name,Eadd: Email , Password: Pass},
success:function(){
window.location.href="create_post/";
console.log ("Success")
},
cache:false,
failure: function(errMsg) {
alert(errMsg);
}
});
this is my ajax request.
its sending the data to this function .
def create_post(request):
if request.method == 'GET':
First_name=request.GET['F_Name'];
Last_Name=request.GET["L_Name"];
Email_address=request.GET["Eadd"];
Pass=request.GET["Password"];
return HttpResponse("<html><body>hi this is me .</body></html>");
When I checked as return(request.method) its giving me GET.
Can some one explain this behavior?
And in the function i have request.method==GET in this scenario DJango is giving me internal server 500 error.
Thanks
I am surprised to see that none of you didn't noticed that he has define method: "POST" in his ajax and his function is used on "GET" request.
And the main reason he is getting the output for print request.method = "GET" and 500 error is because of using window.location.href="create_post/" in his ajax success function. Every request is by default a get request unless we explicitly define it "POST" or any other.
So here it goes like this,
- Ajax calls the url via POST, for unknown reason the response comes in success function(weird coz according to the view posted POST method return nothing to ajax request).
- The success function again calls the same url(page refresh) via a GET request and he sees print request.method as "GET" with 500 error coz this is wrong way to do so.
your ajax method is post, so i think your views.py may try this
def create_post(request):
if request.method == 'POST':
First_name=request.POST['F_Name']
Last_Name=request.POST["L_Name"]
Email_address=request.POST["Eadd"]
Pass=request.POST["Password"]
return HttpResponse("<html><body>hi this is me .</body></html>")
I'm developing a django system and I need to create a chat service that was in real-time. For that I used node.js and socket.io.
In order to get some information from django to node I made some ajax calls that worked very nice when every address was localhost, but now that I have deployed the system to webfaction I started to get some errors.
The djando server is on a url like this: example.com and the node server is on chat.example.com. When I make a ajax get call to django I get this error on the browser:
XMLHttpRequest cannot load http://chat.example.com/socket.io/?EIO=3&transport=polling&t=1419374305014-4. Origin http://example.com is not allowed by Access-Control-Allow-Origin.
Probably I misunderstood some concept but I'm having a hard time figuring out which one.
The snippet where I think the problem is, is this one:
socket.on('id_change', function(eu){
sessionid = data['sessionid']
var options = {
host: 'http://www.example.com',
path: '/get_username/',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': sessionid.length
}
}
var request = http.request(options, function(response) {
response.on('data', function(msg){
console.log('Received something')
if(response.statusCode == 200){
//do something here
}
}
})
})
request.write(sessionid);
request.end();
});
And I managed to serve socket.io.js and make connections to the node server, so this part of the setup is ok.
Thank you very much!
You're bumping into the cross origin resource sharing problem. See this post for more information: How does Access-Control-Allow-Origin header work?
I am NOT a Django coder at all, but from this reference page (https://docs.djangoproject.com/en/1.7/ref/request-response/#setting-header-fields) it looks like you need to do something like this in the appropriate place where you generate responses:
response = HttpResponse()
response['Access-Control-Allow-Origin'] = 'http://chat.example.com'
Hello i've got a problem with ajax json request. Im always getting an error, even if the requests are succeeded. At the moment i have this code:
function sumbitLoginForm(user, pass) {
if (user.trim() == '' || pass.trim() == '') {
alert("You must enter username and password!");
} else {
$.ajax({
type : 'POST',
url : 'https://url.php',
dataType : 'json',
data : {
userlogin : user,
userpass : pass
},
contentType: "application/json;",
success : function(data) {
$("#images").html("uspeshno");
},
error : function(data) {
$("#images").html("greshka");
}
});
}
return false;
}
$(document).ready(function() {
clearPageInputs();
$("#submitButton").click(function() {
sumbitLoginForm($("#username").val(), $("#password").val());
});
});
Im always getting an error , no matter what username and password i type . But the status of request is changing , if i type correct user and pass i get status 302 Moved temporarly , but when i type wrong user or pass i get status 200 OK . What am i doing wrong ?
PRG Pattern and Ajax
It looks like your server returns a HTTP 200 status code when the userid and password will not validate. This is proper behavior, as HTTP error codes not meant for application errors, but for HTTP protocol errors.
When the userid and password are matched succesfully, you are redirected to another page. This is also normal behavior, e.g. to prevent other people to re-use your login credentials using the back key.
This is called the Post/Redirect/Get pattern.
See: http://en.wikipedia.org/wiki/Post/Redirect/Get
The problem is that the PRG pattern does not play nice with Ajax applications. The redirect should be handled by the browser. It is therefore transparent for the jQuery code. The Ajax html response will be the page that is mentioned in the Location header of the 302. Your Ajax application will not be able to see that it is being redirected. So your are stuck.
In one of my projects I solved this on the server side. If I detected an Ajax call, I would not send a redirect but a normal 200 response. This only works if you have access to the server code.
If you cannot change the redirect for your Ajax calls, then you can parse the response headers or the html to see if you were being redirected and act accordingly. Probably the login will set a cookie, so you might try and look for the presence of that cookie.
I have developed an ASP.NET MVC2 application and in that i have a login feature implemented.
I have other views that have ajax calls. At times, i find the ajax calls displaying the login page.
In an attempt to get rid of this problem, i have tried to simulate the situation, but the response code that i get from my application was 200 which is OK
I am using ASP.Net MVC2. Why am i getting 200, where i should be actually getting a 302 server redirect for login page redirection from my current view.
Guide me to handle this situation.
Why am i getting 200, where i should be actually getting a 302 server
redirect for login page redirection from my current view.
It's because jQuery follows the redirect and you end up with 200 and the login page. I would recommend you the following article which illustrates a very elegant way to configure ASP.NET to send 401 status code for unauthenticated requests assuming this request was made using an AJAX call. Then your client code will look like this:
$.ajax({
url: '/foo',
type: 'POST',
data: { foo: 'bar' },
statusCode: {
200: function (data) {
alert('200: Authenticated');
// Do whatever you was intending to do
// in case of success
},
401: function (data) {
alert('401: Unauthenticated');
// Handle the 401 error here. You can redirect to
// the login page using window.location.href
}
}
});