Window.location is being canceled in ajax - javascript

I have problem with window.location. So I have ajax request as follows:
function login(){
var u = document.getElementById("username").value;
var p = document.getElementById("password").value;
if(u == "" || p == ""){
} else {
var ajax = ajaxObj("POST", "ajaxResp.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "login_failed"){
alert("fail");
}
else {
window.location = "user.php?u="+ajax.responseText;
}
}
}
ajax.send("u="+u+"&p="+p);
}
return false;
}
where ajaxObj is decleared in other file. My ajaxResp.php send me back username to which i should redirect. But when I reach window.location, my request is cancelled. What can it mean?

If the window.location line is being hit. you are not waiting for the Ajax call to be complete.
That means whatever the code is inside of the ajaxReturn is not checking for readyState to be complete.

Related

How can Javascript account for returning a 500?

I am using a login form to construct and send a URL (that'd be the "full url" written to storage in the script below) that should return a JSON object.
If the login is correct, the back-end sends me a JSON object with a validation key in it to validate if it cam back successfully. (like this: [{"result":"VALID"}] )
If the login is incorrect, it only provides a 500 error.
Unfortunately, when it gets that 500 error, instead of booting them because the result isn't VALID, the script just gives up because there's no object to validate.
From the Front-End, how can I detect that I have received a 500 error and then trigger "bootThem()"?
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
window.onload = function () {
// get the url from storage.
var fullURL = localStorage.getItem("fullURLStored")
// if the URL is empty, boot them back to the login page.
if(fullURL == " "){
bootThem();
}
// send the URL to the server.
readTextFile(fullURL, function (text) {
var data = JSON.parse(text);
if(data[0].result !== "VALID"){
bootThem();
} else{
//do stuff
}
});
}
Please see below fiddle I have simulated a 500 response from Mock API and handlinkg it:
if (rawFile.readyState === 4 && ((rawFile.status === 200) || (rawFile.status === 500))) {
console.log("fired");
callback(rawFile.responseText);
}
https://jsfiddle.net/asutosh/vdegkyx2/8/
Okay so thanks to Asutosh for the push in the right direction, I was able to adjust my function to boot the user if a 500 error was returned from the JSON call, and allow the user to pass through if there was not.
This was exactly what I needed to handle the 500 error coming back form the JSON:
function bootThem() {
//execute code to reset session and return user to login page.
}
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.addEventListener('error', () => {
console.log("error code");
});
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && (rawFile.status === 500)) {
console.log("500");
bootThem();
callback(rawFile.responseText);
}
if (rawFile.readyState === 4 && (rawFile.status === 200)) {
console.log("200");
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
window.onload = function () {
// get the url from storage.
var fullURL = localStorage.getItem("fullURLStored")
// if the URL is empty, boot them back to the login page.
if(fullURL == " "){
bootThem();
}
// send the URL to the server.
readTextFile(fullURL, function (text) {
var data = JSON.parse(text);
if(data[0].result !== "VALID"){
bootThem();
} else{
//do stuff
}
});
}

Javascript string comparison error

I have a problem with a piece of code that I use to check if a function returns a string that is equal to another string. The problem sounds trivial, but I cannot seem to get it to work.
Here is the code, and make sure you yell at me if you'll need any more code.
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function login(){
var e = _("email").value;
var p = _("password").value;
if(e == "" || p == "") {
_("status").innerHTML = "Fill out all of the form data";
} else{
_("loginbtn").style.display = "none";
_("status").innerHTML ='please wait...';
var ajax = ajaxObj("POST", "index.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
document.write(ajax.responseText); // returns "login_failed" when I try it
if(ajax.responseText == "login_failed"){
_("status").innerHTML = "Login unsuccessful, please try again.";
_("loginbtn").style.display = "block";
} else {
//window.location = "afterlogin.php?u="+ajax.responseText;
}
}
}
ajax.send("e="+e + "&p="+p);
}
}
</script>
The window.location function is commented out for testing purposes. Don't mind that. Below, I will post code for the two scripts that are used, "main" and "ajax".
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
And the code for main.js
function _(x){
return document.getElementById(x);
}
I do not want to take credit for the original code; it is gathered from developphp.com and just altered slightly.
The problem is that, as I've commented, the line
ajax.responseText == "login_failed"
never seems to be true, not matter how I do. This is what I need guidance on.
Regards
It's too late for the answer, but someone may have the same issue.
You need to write
ajax.responseText == '"login_failed"';

Returning a response from a pure JS AJAX call - POST

This is my PHP function to store some data:
case "start_question":
$user_id = "123";
$p_id = $_POST[""];
$question_id = $_POST["question_Id"];
$answer = $_POST["answer_String"];
$counter = $_POST["counter"];
$points = $_POST["answer_Points"];
$user = new User($uid);
$user ->end_question($p_id,$user_id,$question_id,$answer,$counter,$points);
echo "Hello World";
break;
}
And this is the JS Ajax Call:
function startQuestion(){
var question_Id = questions_array[question_counter].question_Id;
console.log("Start Question",question_Id);
var ajax = new XMLHttpRequest();
var params = 'question_Id=' + question_Id;
ajax.open("POST", "ajax_controller.php?m=start_question", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(params);
ajax.onreadystatechange = function () {
console.log(response);
var response = "";
if (xmlHttp.readyState == 1) {
response += "Status 1: Server connection established ! <br/>";
} else if (xmlHttp.readyState == 2) {
response += "Status 2: Request recieved ! <br/>";
} else if (xmlHttp.readyState == 3) {
response += "Status 3: Processing Request ! <br/>";
} else if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var text = xmlHttp.responseText;
response += "Status 4: Processing Request ! <br/>";
response += text;
} else {
alert("Something is wrong !");
}
}
}
//If an error occur during the ajax call.
if (ajax.readyState == 4 && ajax.status == 404) {
console.log("Error during AJAX call");
}
}
What I would like to do is to log in the console the ''Hello World'' response back after PHP has finished processing the results.
PS: Actually I would like to fire a function with a parameter ''hello world'' but If I figure out how to get the response back it should be trivial to do this.
Its basically just a typo probably from a copy/paste that you didnt completely check.
Your XMLHttpRequest() object is called ajax and not xmlHttp so you pick up the responsea and readyState from your ajax object and not xmlHttp.
Also you should move the ajax.send(params); to be run after you have told the XMLHttpRequest object what to do with the respose when it is received.
function startQuestion(){
var question_Id = questions_array[question_counter].question_Id;
console.log("Start Question",question_Id);
var ajax = new XMLHttpRequest();
var params = 'question_Id=' + question_Id;
ajax.open("POST", "ajax_controller.php?m=start_question", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
console.log(response);
var response = "";
if (ajax.readyState == 1) {
response += "Status 1: Server connection established ! <br/>";
} else if (ajax.readyState == 2) {
response += "Status 2: Request recieved ! <br/>";
} else if (ajax.readyState == 3) {
response += "Status 3: Processing Request ! <br/>";
} else if (ajax.readyState == 4) {
if (ajax.status == 200) {
var text = ajax.responseText;
response += "Status 4: Processing Request ! <br/>";
response += text;
} else {
alert("Something is wrong !");
}
}
}
//If an error occur during the ajax call.
if (ajax.readyState == 4 && ajax.status == 404) {
console.log("Error during AJAX call");
}
ajax.send(params);
}
It's not clear what the problem is...
xmlHttp.readyState == 4 is fired when the request is complete, being when PHP is finished processing your request.
What if you just perform your action within the xmlHttp.readyState == 4?
It seems that your response text is stored into xmlHttp.responseText, so you can work into :
if (xmlHttp.status == 200) {
console.log(xmlHttp.responseText);
/* ... */
}
xmlHttp in your given code seems to be undefined. Try to replace it with your actual ajax object:
if (ajax.readyState == 1){ ... }
You should put ajax.send(params); after ajax.onreadystatechange = function () {/*...*/};
If I understand this right , you should put the console.log (response) where you actually receive the response i.e.
var text = xmlHttp.responseText;
response += "Status 4: Processing Request ! <br/>";
response += text;
/**********************/
console.log(response)
/**********************/

Ajax response doesn't equal what I think it should

I'm trying to call a displayUsers function, if response equals "loggedIn" (response is coming from echo statement in php for ajax request). It always jumps straight to the else statement and doesn't execute displayUsers(). However, when I alert response it displays loggedIn.
Here is my code:
function ajaxRequest(url, method, data, asynch, responseHandler) {
var request = new XMLHttpRequest();
request.open(method, url, asynch);
if (method == "POST") {
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200) {
responseHandler(request.responseText);
}
}
}
request.send(data);
}
//loginCheck
function loginCheck() {
var username = document.getElementById("usernameLogin").value;
var password = document.getElementById("passwordLogin").value;
var data="usernameLoginAttempt="+username+"&passwordLoginAttempt="+password;
ajaxRequest("../PHP/CODE/login_check.php", "POST", data, true, loginCheckResponse);
}
function loginCheckResponse(response) {
//check response, if it is "loggedIn" then call show users function
alert(response);
if (response == "loggedIn") {
displayUsers();
} else {
alert("Login Failed. Please try again.")
}
}
// response is an object which you get from ajex.
// You have not written how you call loginCheckResponse()
// call like loginCheckResponse(response.<variable which you return from service page>)
function loginCheckResponse(response)
{
//check response, if it is "loggedIn" then call show users function
alert(response);
if (response == "loggedIn") {
displayUsers();
} else {
alert("Login Failed. Please try again.")
}
}
Changed my code to:
//logged in
function loginCheckResponse(response) {
if(response.trim()=="loggedIn"){
displayUsers();
}
else{
alert("Login Failed. Please try again.");
}
}
It now works. Thanks for the help anyway people.

JavaScript/jQuery script looping 3 times without a loop

I'm trying to get a notification box to pop up on errors/successes and then hide after 5 seconds. The problem is that it shows up, hides, then repeats 3 times. It's annoying and I'm sure it will bug the user.
I thought maybe my javascript was bad, so I tried jquery, still the same result.
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function login() {
var u = _("user").value;
var p = _("pass").value;
var status = _("status");
var ajax = ajaxObj("POST", "login_script.php");
ajax.onreadystatechange = function(){
if(ajax.responseText !== "success"){
status.innerHTML = ajax.responseText;
_('status').className = "nNote nFailure hideit";
var svalue = _('status').innerHTML;
_('status').innerHTML = svalue + '<span style="float:right; margin-right:20px; font-size:10px;" onclick="hideStatus()"> X </span>';
$( document ).ready(function() {
$('#status').slideDown(1000).delay( 5000 ).slideUp(1000);
});
}
};
ajax.send(
"u=" + u
+ "&p=" + p);
}
If you want to see what it's doing, go to this site and click "login"
Change:
if(ajax.responseText !== "success"){
to:
if(ajaxReturn(ajax) && ajax.responseText !== "success"){
You have this function for checking whether the AJAX request is complete, but you forgot to call it.
leave the function when ajax.readyState!==4
You are calling this function when the onreadystatechange-event fires, but this event will fire multiple times(when readyState===4 the request is complete)
But this question is tagged with "jquery", you better use jQuery.ajax()

Categories

Resources