javascript redirect in ajax response - javascript

I have a modal for my login form. I submit the login form using Ajax. If username and password were invalid, I display a message to inform user about failure
But if login data was valid, I'd like to redirect the user to dashboard.php
Here is what I wrote in php file for response:
$action = $_GET['action'];
if($action=="checkLogin")
{
$result = check_login();
if($result=="failure")
{
echo "login failed";
}
else
{
echo 'success
<script>
window.location = "dashboard.php";
</script>
';
}
}
But it is not working as I expect. "failure" and "success" are shown, but redirect does not happen in case of success
Please help me were I am wrong?
Thanks in advance

Your PHP can't control what the client does from an AJAX response; It can't set headers or redirect the client. Instead, you need to return an appropriate success or failure HTTP status code and redirect based on that. A 200 status means success, a 401 means a unauthorized. Click here to learn more about HTTP status codes.
In PHP, response codes can be set in a variety of ways, depending on your version. My example below is the most bare-bones way and should work in PHP4 but Click here for more ways to set them.
if($result == "failure") {
header("HTTP/1.1 401 Unauthorized");
echo "failure";
}
else {
header("HTTP/1.1 200 OK");
echo "success";
}
You can then capture those status codes in your javascript client and redirect if the login is successful. If you were using JQuery it might look something like this:
$.ajax("example.php")
.done(function() {
// done() is called on any 200 response codes (200, 201, etc)
window.location = "dashboard.php";
})
.fail(function() {
// fail() is called on any 400 or 500 response codes (400, 401, 404, 500, etc)
alert("error");
});
It's worth noting that because of the status codes, you do not need to check the response body in your javascript for the words "success" or "failure". Browsers and other clients are already designed to gracefully handle HTTP response codes, so use them as much as possible.

If you can redirect using php you could do this:
header('location : your_php_page.php');
the problem with your code is that you're calling it from ajax. meaning the code is most probably returning text. not html or javascript. if this was coming back to an HTML page, sure it'd print the "Script" part and your js would run. but here, you'd have to do something like this:
in your ajax callback('success' or 'then'. whichever you used):
success: function(data){
if(data == "success")
window.location.redirect("path.php");
}

Try this:
else
{
header('location:your_location.php');
}
or if you are using ajax than return false or something else from here and for this put this in js:
window.location.href = "your_location";

This is what I have done to redirect page:
else{
echo "<meta charset='utf-8'/>";
//direct after five seconds
echo "<meta content='5; url=http://".$_SERVER['HTTP_HOST']."/dashboard.php"."' http-equiv='refresh'> ";
}
What I think about is you don't need 'success' as response ,
If the login valid , just redirect the page.
If fail , OK , let us know with echo "login failed";

Related

jQuery AJAX HTTP error codes not being picked up in Safari

I'm using jQuery.ajax() to send data to my own PHP file for adding subscribers to a MailChimp list. The Javascript looks like this:
$.ajax({
url: url,
method: 'POST',
data: params, // the data is working so here is just the variable I'm using
error: function(response) {
console.error($.parseJSON(response));
// show some response text through DOM manipulation
}, success: function (response) {
console.log($.parseJSON(response));
// show some response text through DOM manipulation
}
});
The PHP looks like this (at least just for the HTTP status code response):
// All my PHP code, which is working is above this
$result = curl_exec($ch);
echo $result; // This is for the response text in the ajax call
http_response_code(intval(json_decode($result)->status)); // This should be sending a success code or triggering errors
On Chrome, if I get a good response (a HTTP status in the 200s), the success function will run. If I trigger an error (in my testing, a HTTP status in the 400s), the error function will run. All is good.
However, on Safari, whether it is a 200 or a 400 code, the success function runs. There seems to be no detection in my Javascript of error codes when using the Safari browser. How can I fix this? Why is it different between Chrome and Safari?
In case it matters, I'm working locally with CodeKit and MAMP PRO to run my project. Thanks.
You need to send the response code before the actual response, i.e.,
$result = curl_exec($ch);
http_response_code(intval(json_decode($result)->status)); // This should be sending a success code or triggering errors
echo $result; // This is for the response text in the ajax call
This is because http_response_code is essentially running a header("HTTP/1.0 $code $codeMessage") and the header needs to be sent before the response.

how can i change http respose code of the php page, on specific if condition depending upon response of ajax call in jquery?

in my search page i call page using ajax which returns json data, now i want to set http response code of this page according result, if keyword found then remain default response code but if not found then change to 404. here is what i am trying.
$.ajax({
url: 'search.php',
data: u,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
type: 'post',
success: function(data) {
if(data == null){
<?php header('HTTP/1.1 404 Not Found'); ?> //update header code to 404
$('#msh_warper').html(err_msg_m);
} else if(data.msg == 'success'){
$('#msh_warper').html(data.return_html);
$('#total_rewr').html(data.total_re);
$('#page_rec').html(data.page_rec);
} else if(data.msg == 'error'){
<?php header('HTTP/1.1 404 Not Found'); ?> //update header code to 404
$('#msh_warper').html(data.return_html);
} else {
<?php header('HTTP/1.1 404 Not Found'); ?> //update header code to 404
$('#msh_warper').html(err_msg_m);
}
$('.ml_warper').hide();
$('#msh_warper').slideDown(1000);
$('.page_overlay').hide();
}, error: function(jqXHR, textStatus, errorThrown){
<?php header('HTTP/1.1 404 Not Found'); ?> //update header code to 404
$('#msh_warper').html(err_msg_m);
$('.ml_warper').hide();
$('#msh_warper').slideDown(1000);
$('.page_overlay').hide();
}
});
but in this case on every request it changes response code to 404, either it is success case or anyother.
can any body help me? can I change http response code on some specific if condition(fail case) which must not effect other (success case)
You can't mix and match programming languages like that. Javascript is a client side language, and PHP is server side. Your PHP tags are going to be processed before the browser ever sees the javascript, so the first header tag you have is what's going to get served to the browser. Since the first PHP tag you have is sending a 404, that's why you always see that.
Aside from that, sending a 404 header when a search didn't return any results is really strange. 404 is for resource not found, not, "no results match your search". It would be much more standard to simply tell the user that there were no results found for their query.

php custom error codes for ajax app

I have an ajax application which returns content of article with given id. All requests are sent to a php file, which takes article content from database and echos it.
Now, there is problem: php file will always have 200 OK status. And I want it to send some status code, which says that article doesn't exists. Something completely out of usual range (like 100 000 or similar).
My question is, is it possible to set some status like that with php?
You can set the HTTP status code with http_response_code. You can only use status codes in the 1xx, 2xx, 3xx, 4xx, or 5xx ranges. You can't make up your own status codes. See this answer for info on that: https://stackoverflow.com/a/11871377
For a status of "article doesn't exist", you can simply use 404 Not Found.
http_response_code(404);
Here is a list of HTTP status codes: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
EDIT: http_response_code only works on PHP 5.4+. If you don't have PHP 5.4 you can do:
header("HTTP/1.0 404 Not Found", TRUE, 404);
More info on this: https://stackoverflow.com/a/12018482
You could send a 404 status code back using http_response_code.
Another option would be to encode a status code and the data you want to return as a JSON response and return that to the browser.
$response = array(
'status' => 100001,
'result' => '<h1>Title...'
);
echo json_encode($response);
exit;
Generally you can mix two ways of answering in PHP. Best practice is to send correct http status code , but with correct code (like 404 for not found and 409 for wrong input (just example)) you can send text response message like if it is standard answer.
So you can mix previous answers (if you need it):
http_response_code(404);
$response = array(
'status' => 100001,
'result' => 'Document was not found on server'
);
echo json_encode($response);
exit;
But i'm not sure you need sub-statuses in that situation.
With that in your javascript you can operate by xhr response code to determine the error itself and show to user some text and substatus that came from server in response body;

Using AJAX to call a php function keeps failing

im having a problem trying to get an ajax call to trigger a php function and then return successfully. As far as i can see my syntax is correct.
But all i get back is failed! Any ideas?
EDIT
I have changed my AJAX request to send without using data, just to rule out that being a problem and i have implemented some of the things people suggested below but to no avail, heres what my 2 files look like now:
ship.js:
function set_ship()
{
//var datastring = {'ship':'true'};
$.ajax({
type:'POST',
url:'soap/classes/class.ship.php',
success: function(success){
alert('success');
},
error: function(fail){
console.log(fail);
}
});
}
And my PHP class.ship.php:
<?php
var_dump("hello");
header('Content-type: application/json');
echo json_encode(array("result"=>"true"));
From the var_dump on my PHP script i can see that the class.ship.php isnt even being called for some reason.
Thanks
Please try this
json_encode(array("result"=>"true"));
because
json_encode(true) // will return just "true" which is not a valid json
Also try serializing the dataString , by doing
data: datastring.serialize();
lowercase JSON_ENCODE
success: function(success), error: function(fail)
check what is returned in network tab of firebug.
You need to set the content header to json header('Content-type: application/json'); and make sure you request return only json coz ajax is waiting only for "JSON" and it will throw parse error
if(isset($_POST['ship']) && $_POST['ship'] == "true"){
$result = "result";
header('Content-type: application/json');
echo json_encode(true);
}
I would suggest that you check what it being actually returned by the server.
The error callback receives one argument representing the xhr object, so you can inspect that directly by placing a breakpoint or using console logging, like this
error: function(xhr) {
console.log(xhr);
}
Likewise, the success callback receives three parameters: the status, the returned data and the XMLHTTPRequest Object, so you can check those in the very same way:
success: function(status, data, xhr) {
console.log(status, data, xhr);
}
You should look for the response status code and the response text in the xhr object to understand what is going wrong. If you're seeing a 200 OK response status, the data returned from the server is probably not being interpreted correctly as JSON data, so you should try setting the response header server side to application/json.
An error might occur also if something else is appended or prepended to your response. This happens especially when warnings occur in the code before returning and you have error reporting set to ON.

ajax request in extjs always executes success

I have a ajax request, where i have code for both success and failure
success: function(my_response) {
},
failure: function(my_response) {
}
I am using Perl CGI in the server to handle the Ajax request, it prints below string when there is a failure
print "Content-type: text/plain\n\n";
print "{success: false, errors: {response: 'Query Failed -- Please check the syntax'}}";
exit
In the firebug, i can see the above response. But, my browser is always executing the code in success. Is there anything wrong in the way i am handling the ajax request?
You are sending JSON message with status code 200 which is considered as success. The fact that this JSON message contains some custom structure with an error message is not something that extjs is capable of knowing. You could either send a 500 HTTP status code from your server or simply use an if condition in your success handler like this:
success: function(my_response) {
if (my_response.success) {
alert('it worked!');
} else {
alert('oops, something went wrong: ' + my_response.errors.response);
}
}
Also readapt the content type to what you are actually sending:
print "Content-Type: application/json\n\n";

Categories

Resources