Ajax response looks undefined - javascript

I'm trying to get the ajax response and attribute it to a variable (let's say _has_weekend_hollidays) as follows:
JS Call:
_has_weekend_hollidays = checkWeekendHollidays( _i );
console.log ( checkWeekendHollidays( _i ) );
AJAX Call
$.ajax({
url: "./directory/ajax_check_weekend_hollidays.php",
type: "POST",
data: {
start_date: _date1,
final_date: _date2
}
}).done(function (_result) {
return ( _first_weekday == 0 || _last_weekday_id >= 6 || _result!="0" );
}).fail(function (_result) {
console.log("ERROR:" + _resultado);
});
The AJAX _result is OK but the return is not working.
So console.log shows undefined.
Any ideas?
Thanks in advance!

If you need the result to continue, do your work after the Ajax callback.
It's undefined because there are no variable return by Ajax:
{
url: "./directory/ajax_check_weekend_hollidays.php",
type: "POST",
data: {
start_date: _date1,
final_date: _date2
}
}
This line:
return ( _first_weekday == 0 || _last_weekday_id >= 6 || _result!="0" );
is not executed until Ajax is "Done".
It you wish to log the return data, use console.log in the return function.
Example:
$.ajax({
url: "./directory/ajax_check_weekend_hollidays.php",
type: "POST",
data: {
start_date: _date1,
final_date: _date2
}
}).done(function (_result) {
console.log(_first_weekday == 0 || _last_weekday_id >= 6 || _result!="0");
//do something else here too
}).fail(function (_result) {
console.log("ERROR:" + _resultado);
});

Related

AJAX Success function if there is no returned JSON data

I know this is simple but I am struggling to get this right. I am using jQuery/AJAX to retrieve some data (JSON) from my database. I then have a success function to display the data. This works fine but I want to have alert the user if there are no returned results.
My PHP excerpt which encodes the JSON:
...
while($row = $result->fetch_all())
{
$returnResult = $row;
}
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
....
My JSON data format looks like this:
{"result":[["Grade 12","Studies","John","Doe"]],"errors":false}
My jQuery that then uses the JSON data and displays in html elements:
function getworkload(){
$.ajax({
type: "POST",
url: "modules/getworkload.php",
dataType: 'json',
data: {id:id},
cache: false,
})
.success(function(response) {
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
$("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
$("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
});
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
I have tried to replace if(!response.errors && response.result) { with the following:
if(!response.errors && response.result=null) {
if(!response.errors && !response.result) {
if(!response.errors && response.result.length < 1) {
Instead of passing errors false in your JSON, throw an HTTP error code like 404 or 500. Then, you can put an error section in your javascript instead of checking in the success section.
Assuming the returned JSON is as follow,
{"result":[["Grade 12","Studies","John","Doe"]],"errors":false}
You just have to put one condition to check if the result length is 0 or not.
Like this,
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
$("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
$("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
});
} else if(!response.errors && response.result && response.result.length==0) {
// Handle 0 result output here...
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
In your PHP script change your echo json_encode... to
echo json_encode(['result' => (count($returnResult)) ? $returnResult : 0, ...]);
Then in your JS simply do
if(!response.errors && !!response.result) {...
Let the server return the word 'nothing' for example in case of no result and split the code to three cases if result and if error and if nothing
if(isset($returnResult) && $returnResult!=null){
echo json_encode('result' => $returnResult);
}
else if (isset($errors) && $errors!=null){
echo json_encode('errors'=>$errors);
}
else { echo "nothing";}
Check that response is not nothing on success function
.success(function(response) {
if(response=='nothing'){
alert('nothing');
}
else {
//rest of the success function
}
Another suggestion is to use this if statement with in success function
.success(function(response) {
if(!response.result && !response.errors){
alert('nothing');
}
else {
//rest of the success function
}
Or
.success(function(response) {
if(response.result==null && response.errors==null){
alert('nothing');
}
else {
//rest of the success function
}
your code is not correctly parsing json value from php file to javascript and you have to parse json before using in javascript
function getworkload(){
$.ajax({
type: "POST",
url: "modules/getworkload.php",
dataType: 'json',
data: {id:id},
cache: false,
})
.success(function(response) {
console.log(response);
var res = JSON.parse(response);
console.log(res);/* console json val*/
if(!res.errors && res .result) {
$.each(res.result, function( index, value) {
$("#divwork").append('<li class="list-group-item"><b>'+value[0]+'</b> : '+value[1]+'</li>');
$("#spnname").html('<b>'+value[2]+' '+value[3]+' Workload </b>');
});
} else {
$.each(res.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
Just use JSON.parse(responce) in success() at firstline and then use it.

Jquery ajax call assigned success val to window

I'm trying to fetch some urls from the back-end and assign data.Results in window.__env.{variable} so I can use it anywhere in the application.
I have this code
(function(window){
window.__env = window.__env || {};
$.ajax({
url: './assets/js/config/config.json',
method: 'GET',
success: function (data) {
let baseUrl = data.BaseApiUrl;
workflowDefinition(baseUrl);
}
})
function workflowDefinition(baseUrl) {
$.ajax({
url: baseUrl + 'api/Management/Configurations?name=SaveWorkflowDefinition&name=WorkflowDefinition',
method: 'GET',
success: function (data) {
if (data && data.Results && data.Results[0] && data.Results[0].Value) {
window.__env.saveWorkflowDefinition = data.Results[0].Value;
console.log(window.__env.saveWorkflowDefinition);
}
if (data && data.Results && data.Results[1].Value) {
window.__env.getWorkflowDefinition = data.Results[1].Value;
}
},
error: function (error) {
var errorMessage = "Failed to contact Workflow Server, please contact your IT administrator";
alert(errorMessage);
}
})
}
}(this))
I can see that the console.log is printing when this loads it gives me the right URL, then I tried passing window.__env.saveWorkflowDefinition to say another file xfunction.js where I want to use window.__env but it gives me undefined.
However if I pass it like this without ajax call, it works fine.
(function(window){
window.__env = window.__env || {};
window.__env.saveWorkflowDefinition= 'www.mybaseurl.com/api/Management/';
})
Can someone point out why its returning undefined when I pass it to xfunction.js when doing an ajax call?
Since your Ajax calls will only provide the response asynchronously, you cannot expect to have the response in the same synchronous execution context.
One idea to resolve this, is to abandon the idea to store the response in a global (window) property, but to store instead a promise, which you do get synchronously.
The code could look like this:
window.promiseWorkFlowDefinition = $.ajax({
url: './assets/js/config/config.json',
method: 'GET',
}).then(function (data) {
return $.ajax({
url: data.BaseApiUrl + 'api/Management/Configurations?'
+ 'name=SaveWorkflowDefinition&name=WorkflowDefinition',
method: 'GET',
})
}).then(function (data) {
return data && data.Results && (data.Results[0] && data.Results[0].Value
|| data.Results[1] && data.Results[1].Value)
|| ('No Results[0 or 1].Value found in:\n' + JSON.stringify(data));
}, function (error) {
var errorMessage =
"Failed to contact Workflow Server, please contact your IT administrator";
alert(errorMessage);
});
// Other file:
window.promiseWorkFlowDefinition.then(function(saveWorkflowDefinition) {
// Use saveWorkflowDefinition here. This is called asynchronously.
// ...
});

jQuery ajax call to variable

For my Phonegap/Cordova project I'm trying to handle all ajax calls with the following functions:
function requestData(action, id ) {
var data = {
user_id: localStorage.getItem('user_id')
};
if( action == 'feed_load_feedings' || action == 'feed_add_load_menu_weight' || action == 'feed_add_load_menu_supps' ) {
data.id = id;
}
$.ajax({
type: 'post',
url: 'http://_______.com/file.php?'+action,
async: false,
crossDomain: true,
data: data,
beforeSend: showLoader,
error: handleError,
success: handleSuccess
});
}
function showLoader() {
console.log('showLoader fired')
$('body').prepend('<p id="loading">De gegevens worden geladen...</p>');
}
function handleError(data) {
console.log('handleError fired')
$('#loading').remove();
$('body').prepend('<p id="error">Fout tijdens het laden van de gegevens...</p>');
return false;
}
function handleSuccess(data) {
console.log('handleSuccess fired')
$('#loading').remove();
if( typeof data !== 'object' ) {
$('body').prepend('<p id="error">Fout in gegevens object...</p>');
return false;
}
else if(data.length == 0 ) {
return 0;
}
else {
return data;
}
}
This handles the request, but also the error handling.
If everything is alright, it should return the data. However using this:
$(function() {
var herd = requestData('herd_load_herds');
console.log(herd):
});
Gives this in the console:
showLoader fired
POST http://_______.com/file.php?feed_load_feedings
handleSuccess fired
undefined
In the POST request I can see that the data is called and okay. However it isn't put into the variable. I thought that adding async: false to my ajax call would prevent that. What am I overseeing?
The reason behind returning undefined is pretty obvious since requestData function doesn't return anything which means it indirectly returns undefined
The flow of the ajax is asynchronous, so returning anything in the function requestData won't work. You need to pass callback function in function calling and execute it in the success/ error handlers.
$(function() {
requestData('herd_load_herds', 'someid', function(err, data){
if(err){
console.log("error");
console.log(err);
}else{
console.log("success");
console.log(data):
}
});
});
in AJAX:
function requestData(action, id, callback) {
var data = {
user_id: localStorage.getItem('user_id')
};
if( action == 'feed_load_feedings' || action == 'feed_add_load_menu_weight' || action == 'feed_add_load_menu_supps' ) {
data.id = id;
}
$.ajax({
type: 'post',
url: 'http://_______.com/file.php?'+action,
async: false,
crossDomain: true,
data: data,
beforeSend: showLoader,
error: function(error){
handleError(error, callback);
},
success: function(data){
handleSuccess(data, callback);
}
});
}
In handler:
function handleSuccess(data, next) {
console.log('handleSuccess fired')
$('#loading').remove();
if( typeof data !== 'object' ) {
$('body').prepend('<p id="error">Fout in gegevens object...</p>');
next(undefined, false);
}else{
next(undefined, data);
}
}
function handleError(err, next) {
console.log('handleError fired')
$('#loading').remove();
$('body').prepend('<p id="error">Fout tijdens het laden van de gegevens...</p>');
next(err);
}
Your code is working perfectly fine. JavaScript functions without a return value return undefined by default. Your function requestData has no return <someValue> statement and so returns the default undefined.
If you want to save the data, you need to save it in the success callback.
My advise is to not try and hack around with async: false. Just do everything async and respond to callbacks appropriately.

jQuery $.ajax() call is hanging and I cannot do nothing until the call ends

Hi;
when i'm using from jQuery ajax, the page getting to freeze until request end.
this is my JavaScript code:
function GetAboutContent(ID, from) {
var About = null;
if (from != true)
from = false;
$.ajax({
type: "POST",
url: "./ContentLoader.asmx/GetAboutContent",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ 'ID': ID, 'from': from }),
async: true,
success: function (msg) {
var Result = msg.d.Result;
if (Result == 'session') {
warning('Your session has expired, please login again!');
setTimeout(function () {
window.location.href = "Login.aspx";
}, 4000);
return;
}
if (Result == 'failed' || Result == false) {
About = false;
return;
}
About = JSON.parse(msg.d.About)[0];
}
});
return About;
}
and this is my WebService
[WebMethod(EnableSession = true)]
public object GetAboutContent(int ID, bool from = false)
{
try
{
if (HttpContext.Current.Session["MahdParent"] != null ||
HttpContext.Current.Session["MahdTeacher"] != null ||
from)
{
functions = new GlobalFunctions();
DataTable queryResult = new DataTable();
queryResult = functions.DoReaderTextCommand("SELECT Field FROM TT WHERE ID = " + ID);
if (queryResult.Rows.Count != 0)
return new { Result = true, About = JsonConvert.SerializeObject(queryResult.Rows[0].Table) };
else
return new { Result = false };
}
else
return new { Result = "session" };
}
catch (Exception ex)
{
return new { Result = "failed", Message = ex.Message };
}
}
How can i solve that problem?
please help me
In the last line you try to return About. That cannot work due to the asynchronous nature of an AJAX request. The point at which you state return About doesn't exist any more when the success function of your AJAX request runs.
I assume you try do do somehting like this:
$('div#content').html(GetAboutContent());
In a procedural lantuage like PHP or Perl this works fine, yet JavaScript functions in a very different way. To make something like this work you'd do something like this:
$.ajax({
type: "post",
url: "./ContentLoader.asmx/GetAboutContent",
dataType: "json",
data: {
'ID': ID,
'from': from
},
success: function(result) {
$('div#content').html(result)
}
});
The difference between the two bits of code is that the first would expect JavaScript to know the value at the time you request it. However, your function GetAboutContent() doesn't have instant access to these data. Instead it fires up an AJAX request and ends right after that with the request still in progress for an unknown amount of time.
Once the request finishes successfully the data is available to JavaScript. and you can work with it in the callback function defined for success. By then the request has absolutely no connection to the function that started it. That's why it's asynchronous.

JavaScript functions not defined?

For some reason, Firefox is throwing "function not defined" errors at this piece of JS:
$(function() { // on document ready
function updateAlerts() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'checkAlerts'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
// Update the DOM to show the new alerts!
if (response.friendRequests > 0) {
// update the number in the DOM and make sure it is visible...
$('#notifications').show().text(response.friendRequests);
}
else {
// Hide the number, since there are no pending friend requests or messages
var ablanknum = '0';
$('#notifications').show().text(ablanknum);
}
}
});
}
function friendRequestAlert() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'sendFriendAlert'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
if (response.theFRAlert !== '0') {
// Display our fancy Javascript notification.
$.jgrowl('' + response.theFRAlert + '');
}
}
});
}
function messageAlert() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'sendMessageAlert'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
if (response.theAlert !== '0') {
// Display our fancy Javascript notification.
$.jgrowl('' + response.theAlert + '');
$('#therearemessages').show().text(response.theAlert);
}
}
});
}
});
I checked through my code and nothing seems to be wrong.
There is no reason to wrap your 3 functions in the document ready wrapper--nothing inside those functions (which may rely on the doc being ready) is executed until they are called. Further, by wrapping them in doc ready, you're forcing them into the scope of that anon function and they cannot be used from outside of it.
Unrelated, you should set your dataType to 'json' on the $.ajax calls and stop making manual calls to $.parseJSON.
New code:
function updateAlerts()
{
$.ajax( {
url: '/check.php',
type: 'POST',
data: {
method: 'checkAlerts'
},
dataType: 'json',
success: function( response )
{
// Update the DOM to show the new alerts!
if( response.friendRequests > 0 )
{
// update the number in the DOM and make sure it is visible...
$( '#notifications' ).show().text( response.friendRequests );
}
else
{
// Hide the number, since there are no pending friend requests or messages
var ablanknum = '0';
$( '#notifications' ).show().text( ablanknum );
}
}
} );
}
function friendRequestAlert()
{
$.ajax( {
url: '/check.php',
type: 'POST',
data: {
method: 'sendFriendAlert'
},
dataType: 'json',
success: function( response )
{
if( response.theFRAlert !== '0' )
{
// Display our fancy Javascript notification.
$.jgrowl('' + response.theFRAlert + '');
}
}
} );
}
function messageAlert()
{
$.ajax( {
url: '/check.php',
type : 'POST',
data: {
method : 'sendMessageAlert'
},
dataType: 'json',
success: function( response )
{
if( response.theAlert !== '0' )
{
// Display our fancy Javascript notification.
$.jgrowl('' + response.theAlert + '');
$('#therearemessages').show().text(response.theAlert);
}
}
} );
}
Scope in javascript is function based.
Since you define the 3 functions inside a function that is run on DOMready and then goes out of scope, so does the funcitons.
In other words: the 3 functions only exist inside the DOmready function, and you cannot use them from anywhere else outside that function.

Categories

Resources