Ajax response doesn't equal what I think it should - javascript

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.

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
}
});
}

Var not found in IF statement, but is set correctly.

I have a var that's value is set, with an if statement to check which value, then deploy depending on the statement.
function Sort() {
var Response = document.getElementById("ResponseDiv").innerHTML;
if (Response == "Verified.") {
alert("Verified");
}
else if (document.getElementById("ResponseDiv").innerText == "Not verified.") {
alert("Not verified");
}
else {
alert("Else: " + Response);
}
}
My code isn't landing on "Verified" or "Not Verified" instead it lands on the else statement. I went through several times thinking I had a typo but isn't the same.
The ResponseDiv is filled by this (which works fine):
function Check() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://' + Http + '/ID_' + ID + '.html', false);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("ResponseDiv").innerHTML = xhr.responseText;
//setTimeout(Sort, 200);
Sort();
}
}
};
xhr.send(null);
}
My div gets the correct data, and the alert box in the else even gives me what I'm looking for, but lands on the else.
Debugger shows Response as coming back as "Verified.\n", but in no other way. However statement works fine when coded as if(Response == "Verified.\n").

Window.location is being canceled in ajax

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.

request.responseText receives correct data but JavaScript cannot understand it

I am new to AJAX and presently learning it from Head First AJAX. The problem I am facing is really weird. I developed a simple program that creates a request through JavaScript and then shows the output.
main.js
window.onload = initPage;
function initPage() {
request = createRequest();
if(request == null) {
alert("request could not be created");
}
else {
var url = "requestMe.php";
request.onreadystatechange = showResult;
request.open("GET", url, true);
request.send(null);
}
}
function showResult() {
if(request.readyState == 4) {
if(request.status == 200) {
if(request.responseText == "okay") {
alert("A successful request was returned");
}
else {
alert("ALERT : " + request.responseText);
}
}
else {
alert("Request status received was not correct");
}
}
}
//--function to create request objects--
function createRequest(){
try{
request = new XMLHttpRequest();
}
catch(tryMS){
try{
request = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(otherMS){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(failed){
request = null;
}
}
}
return request;
}
Now, here is the php script.
requestMe.php
<?php
echo 'okay';
?>
This code should give the alert A successful request was returned
But instead it gives the result ALERT : okay
The weird thing is this same code was working yesterday for me when I tried it and now it is giving me this result. I tried to create similar programs and they all are showing me this kind of weird behavior. The responseText received is correct because it appends okay after ALERT :. What wrong am I doing here in the code? Why is it going to the else part when the responseText received is correct?
Any Help? Thanks in advance.
I personally would do it using jQuery's Ajax Function in the following way:
document.addEventListener("DOMContentLoaded", function()
{
$.ajax({
"url": "requestMe.php"
}).done(function(data)
{
if(data == "okay")
{
alert("A successful request was returned");
} else
{
alert("ALERT : " + data);
}
}).fail(function()
{
alert("Connection Failed");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I haven't tested this Script, but it should in theory work out well.
Do one thing add exit; after echo 'okay';
Issue in your code is after ?> there is extra space available you can fix it either by removing ?> or removing extra space after ?>.
I hope it will fix your issue.

Passing values from javascript to servlet not working in chrome

Im trying to pass parameters to servlet from javascript with :
function selectHandler() {
var selection = table.getChart().getSelection()[0];
var topping = data.getValue(selection.row, 0);
var answer=confirm("Delete "+topping+"?");
if(answer){
document.location.href="/item?_method=delete&id="+topping;
alert(topping+" has been deleted");
location.reload();
}
else return false;
}
The values are getting passed to the servlet and is working fine when I'm using firefox as in I'm getting the url as: http://XXXXXXX/item?_method=delete&id=xxxx
But when I'm using chrome the URL that is send is http://XXXXXXX/item. as the values are not getting passed!! I have tried with window.location.href also with no change. what could be the issue?
What you need is ajax call or say XMLHttpRequest as below:
<script type="text/javascript">
function doAjax () {
var request,
selection = table.getChart().getSelection()[0],
topping = data.getValue(selection.row, 0),
answer=confirm("Delete "+topping+"?");
if (answer && (request = getXmlHttpRequest())) {
// post request, add getTime to prevent cache
request.open('POST', "item?_method=delete&id="+topping+'&time='+new Date().getTime());
request.send(null);
request.onreadystatechange = function() {
if(request.readyState === 4) {
// success
if(request.status === 200) {
// do what you want with the content responded by servlet
var content = request.responseText;
} else if(request.status === 400 || request.status === 500) {
// error handling as needed
document.location.href = 'index.jsp';
}
}
};
}
}
// get XMLHttpRequest object
function getXmlHttpRequest () {
if (window.XMLHttpRequest
&& (window.location.protocol !== 'file:'
|| !window.ActiveXObject))
return new XMLHttpRequest();
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {
throw new Error('XMLHttpRequest not supported');
}
}
</script>
You can also do it easily by jquery,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" />
<script type="text/javascript">
function doAjax () {
...
$.ajax({
url: "item?_method=delete&id="+topping+'&time='+new Date().getTime()),
type: "post",
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
console.log("It worked!");
// do what you want with the content responded by servlet
}
});
}
</script>
Ref: jQuery.ajax()

Categories

Resources