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.
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>")
ok.
I'm using Web API to make AJAX requests.
I'm trying to send a PUT request to an action on a controller.
I'm using route attributes.
When I'm sending the data as part of the route data, everything is fine and the action gets the right info.
However, when I'm trying to send the data in the body, I get a 405 status ((Method is not allowed).
I'm also adding the [FromBody] attribute to the parameter. Here's by jQuery call:
type: 'PUT',
url: 'api/ServerQueue/activity',
data: "=2",
success: function (xhr) {
$("#load").hide();
},
error: function () {
$("#load").hide();
}
};
Here's my action:
[Route("status/{status}")]
public string PutStatus([FromBody]int status)
{
}
I placed a "RoutePrefix" on the controller body.
BTW, I'm using VS 2012.
Any idea what could be the source of the problem?
Try changing the route configuration from
[Route("status/{status}")]
to
[Route("status")]
I have two sites right now. One that has a token and one that is supposed to allow a user to do stuff with the token.
When I visit the first site that has the token, mySite.local/services/session/token it shows it: OTV4Gu9VQfjIo2ioQ0thajdEJ6nEINoxsLuwgT_6S0w
When I am on the page that is supposed to GET this token, I get an empty response and the error for the ajax function is thrown.
The weird part is that when investigating the issue with firebug, I can see the response for the ajax request is 43B - the same size as the token. So for some reason the page with the token is being hit properly, but the response is not coming through.
Here is a screenshot of the firebug response:
And here is the JQuery with the ajax request:
var nid; //global node id variable
$('html').click(function(){
try {
$.ajax({
url:"http://mySite.local/services/session/token",
type:"get",
dataType:"text",
error:function (jqXHR, textStatus, errorThrown) {
alert('error thrown - ' + errorThrown);
console.log(JSON.stringify(jqXHR));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (token) {
//Do some stuff now that token is received
}
});
}
catch (error) {
alert("page_dashboard - " + error);
}
});
Your running into the Same Origin Policy which essentially states any request done by client side/browser language like Javascript must be on the same port, with the same domain name and the same protocol. In your case http://mysitemobile.local does not equal http://mysite.local so you're request is being blocked. Firebug's way of displaying that is no response with 43 bytes.
There are two ways to work around this, Cross-origin resource sharing (CORS) or JSONP. CORS is a HTTP header that is added to the server you are requesting to and provides a whitelist of acceptable domains that are allowed break the same origin policy. Most recent browsers support this header.
The other option is JSONP, wraps a JSON object into a Javascript function that is called using <script> tags normally. If the other server returns {status: 0} and you have a function called parseStatus() in your code that the remote server would wrap into parseStatus({status:0}); thus calling your function without having to worry about the same origin policy.
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
}
}
});