Compare Javascript Ajax Response with String - javascript

I'm trying to compare the result from from ajax call with a string. My result is returning the correct result but i can't get the if statement to compare this with my string, any ideas?
$.ajax({
type: "POST",
url: "sessionCheck.php",
data: {id:mwdata},
success: function(html) {
if (html == "open"){
alert ("yes it's open");
}else if(html == "closed"){
alert ("no it's closed");
}
}
});

So the answer was to trim the result var result = $.trim(html);

Related

How to use Return data after ajax call success in if statement

I have something like this, where it is a simple call to a script that gives me back a value, a string but when i use alert function than it display correct value but after if condition it didn't showing the alert message. I just want to compare the value of data to the value that is coming from login.php.
$("#login").click(function(event){
event.preventDefault();
var Email = $("#email").val();
var Password = $("#password").val();
$.ajax({
url : "include/login.php",
method : "POST",
data : {CustomerLogin:1,CustomerEmail:Email,CustomerPassword:Password},
success : function(data){
if(data == 'true'){
alert(data);
}
}
})
})
you cann't compare boolean with string value . So you need to pass the boolean value for comparison
if(data == true){
alert(data);
}
OR
if(data){
alert(data);
}

Retrieve JS function value

I'm currently trying to retrieve a JS return value and I don't really know the reson why it doesn't work...
Hi hoper my code is the most easiest to read as possible, thanks in advance :
<script type="text/javascript">
function getValLocalSto(key, URL){
console.log(key);
console.log(URL);
var myKey = localStorage.getItem(key);
if(myKey == null){
// getting back JSON data
$.ajax({
url: URL,
dataType: 'json',
async: false,
success: function (json) {
var test;
console.log(JSON.stringify(json)); // the result is a well formed JSON string
localStorage.setItem(key,JSON.stringify(json));
myKey = localStorage.getItem(key);
test =jQuery.parseJSON(myKey);
console.log("My function result : "+test); // the result is a [object Object]
return test;
}
});
}else {
// Other work whatever
}
}
//call my function
console.log("sortie fonction : "+getValLocalSto("testJson", "do/profil")); // the result is "undefined"
var myuResult = getValLocalSto("testJson", "do/profil")); // the result is "undefined"
console.log(ff.prenom);
document.getElementById("myDiv").innerHTML="<div><input disabled='disabled' name='text-basic' id='text-basic' type= 'text' value='Votre nom "+ff.nom+"'/></div>";
document.getElementById("myDiv").innerHTML+="<div> <input disabled='disabled' name='text-basic' id='text-basic' type= 'text' value= 'Votre prenom "+ff.prenom+"'/></div>";
</script>
The solution :
function getValLocalSto(key, URL){
// do my stuff
});
}else {
// Other work whatever
}
return test;
}
Just declare test variable outside the ajax success function in the getValLocalSto outer function taking advantage of the variable scope. Else you would need a callback to return the variable from the ajax success function. Try this:
<script type="text/javascript">
function getValLocalSto(key, URL){
...
if(myKey == null){
// getting back JSON data
var test;
$.ajax({
url: URL,
dataType: 'json',
async: false,
success: function (json) {
console.log(JSON.stringify(json)); // the result is a well formed JSON string
localStorage.setItem(key,JSON.stringify(json));
myKey = localStorage.getItem(key);
test =jQuery.parseJSON(myKey);
console.log("My function result : "+test); // the result is a [object Object]
}
});
return test;
}else {
// Other work whatever
}
}
//call my function
console.log("sortie fonction : "+getValLocalSto("testJson", "do/profil")); // the result is "undefined"
...
</script>
You can pass a callback to AJAX.
Change function definition to:
function getValLocalSto(key, URL, callback){
...
$.ajax({
url: URL,
dataType: 'json',
async: false,
success: callback
});
...
in the code:
getValLocalSto("testJson", "do/profil", function(data) {
localStorage.setItem(key,JSON.stringify(data));
myKey = localStorage.getItem(key);
test = jQuery.parseJSON(myKey);
// here you work with test as you want as a result of getValLocalSto
});

Return javascript array not working [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have a javascript functions that fetches some JSON from a PHP. When I get the JSON my plan is to parse it and load it in to an array and then return that array so that I can use the data anywhere.
This is the ajax function:
function get_ajax(route_val){
$.ajax({
url: "ajax.php",
dataType: 'json',
data: {
route: route_val
},
success: function(result) {
if(result.error == true){
alert(result.message);
}else{
$.each(result, function(key1, value1){
//console.log(key1 + ":" + value1);
returnarray[key1] = value1;
});
return returnarray;
}
}
});
}
</script>
If I then try to define say var arr = get_ajax('1'), arr is going to be empty. I can alert and console.log stuff from the array from inside the function but returning it returns nothing.
It does not seem to exist outside of the function.
Any ideas?
You are using Ajax incorrectly, the idea is not to have it return anything, but instead hand off the data to something called a callback function, which handles the data.
IE:
function handleData( responseData ) {
// do what you want with the data
console.log(responseData);
}
$.ajax({
url: "hi.php",
...
success: function ( data, status, XHR ) {
handleData(data);
}
});
returning anything in the submit handler will not do anything, you must instead either hand off the data, or do what you want with it directly inside the success function.
The problem is that your success function isn't returning your array to anywhere. What you need to do is fully handle your data right there inside of the success handler, or else call another method/function to do what's needed.
Hypothetically it might look something like this:
success: function(result) {
if(result.error == true){
alert(result.message);
}else{
$.each(result, function(key1, value1){
returnarray[key1] = value1;
});
//Something like this
ajaxHandlers.handleReturnedArray(returnarray);
}
}
If you absolutely want to have it return something, you can do a synchronous request (Despite it's not the point of AJAX (asynchronous JavaScript and XML)).
function get_ajax(route_val){
var returnarray = [];
$.ajax({
url: "ajax.php",
dataType: 'json',
async: false,
data: {
route: route_val
},
success: function(result) {
if(result.error == true){
alert(result.message);
}else{
$.each(result, function(key1, value1){
returnarray[key1] = value1;
});
}
}
});
return returnarray;
}

How do I alert my json results?

I get these results via php to alert in my ajax alert
[{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}]
How do I do $('#divid').html(message); ?
I want only specified value from the json array.
Here is the code
function showMessage(id){
var dataString = 'id=' + id;
$.ajax(
{
type: "POST",
url: "/inbox/instshow",
data: dataString,
success: function(results)
{
if(results == "error")
{
alert('An error occurred, please try again later. Email us with the issue if it persists.');
}
if(results != "notallowed" && results != "error" && results != "login")
{
alert(results);
alert(results[0].message);
}
}
});
}
data = [{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}]
$('#divid').html(data[0].message);
DEMO
You might have to parse a JSON string using jQuery.parseJSON.
// results is your JSON string from the request
data = jQuery.parseJSON(results);
$('#divid').html(data[0].message);
If you ajax you should include:
dataType: 'json'
code
$.ajax(
{
type: "POST",
url: "/inbox/instshow",
data: dataString,
dataType: 'json', // here
success: function(results) {
}
.........
Including this jQuery will parse the returned data as JSON for you automatically (don't need any manual parsing effort) and you'll get your result that you're trying now.
use JSON.stringify() function
var data=[{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}] ;
alert(JSON.stringify(data));
Here's your data broken down by levels:
[
{
"message_id":"3",
"box":"0",
"from_id":"3",
"to_id":"1",
"title":"Hello sir!",
"message":"how are you?",
"sender_ip":"",
"date_sent":"",
"status":"0"
}
]
You would use data[0].message because the first level indicates an array, hence the need of [0] to reference the first and only element, and the second is an object, which properties can be accessed by the object.member syntax.
for debugging purposes
console.log(data, data.message, "whatever")
You need to open firebug or safari's inspector and look in the "console"

How do I get a string from my servlet and use it in my ajax function [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 7 years ago.
I have a servlet that contains a string, wherein the latter is a JSON string with multiple entries. Now I want to access this String with ajax through jQuery. Now here if my function:
function myFunction() {
$("#myButton").click(function() {
$.ajax({
url: // servlet,
type: "GET",
dataType : "text",
success: function() // I want to display the string from the servlet,
error: // stuff
// other code
Anyway how can I do this. Also can I place another function in the success part rather than an anonymous function?
Is this what you're looking for?
function getString(url, handleResponse, handleFailure) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
if (handleResponse) {
handleResponse(request.responseText);
}
} else {
if (handleFailure) {
handleFailure(request.status);
}
}
};
}
this just gets a string from URL (No JQuery)
I want to display the string from the servlet,
your success method has a parameter data
success: function(data){ alert( data ); }
Also can I place another function in the success part rather than an
anonymous function?
success: namedFunction,
function namedFunction(data){ alert(data); }
You can pass function expression to be executed on success or error. First argument for success callback is response sent via server.
Try this:
function successGoesHere(response) {
console.log(response);
}
function errorGoesHere(err) {
console.log(err);
}
function myFunction() {
$("#myButton").click(function() {
$.ajax({
url: "YOUR_URL",
type: "GET",
dataType: "text",
success: successGoesHere,
error: errorGoesHere
})
})
}
As you are passing dataType : "text" in ajax config, response will always be plain text, just in case you are expecting it to be json, your response will be string representation of json hence you will have to parse it using JSON.parse(response) to get JSON object
Use ajax request success : function(resp){
code for parsing json and show parsed json
// var json = $.parseJSON(data);
}
You need to look this
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
}
var testman = function(str, cb) {
var data = 'Input values';
$.ajax({
type: 'post',
url: '',// servlet
data: data,
success: cb
});
}
testman('Hello, Dear', callback);

Categories

Resources