Execute ajax function until get success of another ajax call - javascript

I need to execute an ajax function, the detail here is that i want to execute this function until another ajax function return success.
This is the function that will i have to wait to return success (try..catch block)
Ajaxfunction1
$.ajax({
type : "GET",
url :url,
data : parameters,
success : function(msg) {
try {
var jsonObject = JSON.parse(msg);
console.debug(msg);
//SendToDMS(msg);
} catch (e) {
$("#SaveConfig").removeAttr("disabled");
toastr.error(msg + '.', "Message");
}
},
failure : function(msg) {
$("#SaveConfig").removeAttr("disabled");
toastr.error('Error: ' + msg + '.', "Message");
}
});
I want something like this:
while ( Ajaxfunction1 != success ) { // while the previous ajax function not return success execute this another ajax function
$.ajax({
type : "GET",
url :url,
data : parameters,
success : function(msg) {
// something on success
},
failure : function(msg) {
// something when comes an error
}
});
}
How can I accomplish this? Thanks for your help

You can use the returned Deferred from $.ajax and check it's state() to see if it's resolved, rejected or pending, so something like this with a recursive function should do what you want.
var waitFor = $.ajax({
type : "GET",
url : url,
data : parameters
}).done(function(msg) {
try {
var jsonObject = JSON.parse(msg);
} catch (e) {
$("#SaveConfig").removeAttr("disabled");
toastr.error(msg + '.', "Message");
}
}).fail(function(msg) {
$("#SaveConfig").removeAttr("disabled");
toastr.error('Error: ' + msg + '.', "Message");
});
(function rec() {
$.ajax({
type : "GET",
url : url,
data : parameters
}).always(function() {
if (waitFor.state() != 'resolved') rec();
}).done(function(msg) {
// something on success
}).fail(function(msg) {
// something when comes an error
});
})();

Related

TypeError: jQueryxxxxxx is not a function

When first opening the mobile app homepage it returns an error
"TypeError: Jqueryxxxxxx is not a function" although it shows the API
callback results
"jQuery111309512500500950475_1459208158307({"code":1,"msg":"Ok","details":{"data"..."
according to Firebug.
I have to open different app pages then return to homepage to see Featured Merchants parsed.
JS Code
case "page-home":
callAjax('getFeaturedMerchant','');
break;
case "getFeaturedMerchant":
displayFeaturedRestaurant( data.details.data ,'list-featured');
break;
case "getFeaturedMerchant":
createElement('list-featured','');
break;
API PHP Code
public function actiongetFeaturedMerchant()
{
$DbExt=new DbExt;
$DbExt->qry("SET SQL_BIG_SELECTS=1");
$start=0;
$limit=200;
$and='';
if (isset($this->data['restaurant_name'])){
$and=" AND restaurant_name LIKE '".$this->data['restaurant_name']."%'";
}
$stmt="SELECT a.*,
(
select option_value
from
{{option}}
WHERE
merchant_id=a.merchant_id
and
option_name='merchant_photo'
) as merchant_logo
FROM
{{view_merchant}} a
WHERE is_featured='2'
AND is_ready ='2'
AND status in ('active')
$and
ORDER BY sort_featured ASC
LIMIT $start,$limit
";
if (isset($_GET['debug'])){
dump($stmt);
}
if ($res=$DbExt->rst($stmt)){
$data='';
foreach ($res as $val) {
$data[]=array(
'merchant_id'=>$val['merchant_id'],
'restaurant_name'=>$val['restaurant_name'],
'logo'=>AddonMobileApp::getMerchantLogo($val['merchant_id']),
);
}
$this->details=array(
'data'=>$data
);
$this->code=1;$this->msg="Ok";
$this->output();
} else $this->msg=$this->t("No Featured Restaurant found");
$this->output();
}
I'm stuck and confused what's causing this error and how to resolve it.
EDIT: Added the full callAjax Function
function callAjax(action,params)
{
/*add language use parameters*/
params+="&lang_id="+getStorage("default_lang");
dump(ajax_url+"/"+action+"?"+params);
ajax_request = $.ajax({
url: ajax_url+"/"+action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function() {
if(ajax_request != null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
} else {
},
complete: function(data) {
ajax_request=null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code==1){
switch (action)
{
case "getFeaturedMerchant":
displayFeaturedRestaurant( data.details.data ,'list-featured');
//$(".result-msg").text(data.details.total+" Restaurant found");
$(".result-msg").text(data.details.total+" "+ getTrans("Featured Restaurants found",'restaurant_found') );
break
)
else {
/*failed condition*/
switch(action)
{
case "getFeaturedMerchant":
createElement('list-featured','');
//$(".result-msg").text(data.msg);
break;
}
},
error: function (request,error) {
hideAllModal();
if ( action=="getLanguageSettings" || action=="registerMobile"){
} else {
onsenAlert( getTrans("Network error has occurred please try again!",'network_error') );
}
}
}};
Calling URL is:
http://domain.com/mobileapp/api/getFeaturedMerchant?
This is actually an issue with the way jQuery handles the abort method when using JSONP, which I have encountered before.
Basically, JSONP works by adding a script tag to the DOM, and adding a callback it will fire when it executes.
Unlike AJAX, the request generated by a script tag cannot be cancelled, so when you call abort like below, it only sort-of works.
ajax_request.abort();
jQuery will unset the global callback it registered, jQuery111309512500500950475_1459208158307 in your case, but it cannot stop the script from trying to run it when it loads. Thus, when it tries to call the now-undefined function, you get the error.
Personally, I think jQuery should set, or have an option to set, these global handlers to an empty function or something instead, but it doesn't. In your case, if possible, I would recommend avoiding making the request if you only plan to abort it before sending it.
Edit:
Two issues I see:
Your code bracing is wrong leading to some unintended execution paths.
You are trying to call .abort() on a JSONP request which is not supported. Doing so will cause the callback function to be removed BEFORE the JSONP script loads that tries to call that callback function. The .abort() will stop the processing of the request, but leave you with the type of script error you see reported.
Here are the notes on the code bracing:
It appears like your code bracing is wrong so you are executing the success callback too soon. When I put your callAjax through a code formatter, it looks like this (see the spot marked "problem area"
function callAjax(action, params) {
/*add language use parameters*/
params += "&lang_id=" + getStorage("default_lang");
dump(ajax_url + "/" + action + "?" + params);
ajax_request = $.ajax({
url: ajax_url + "/" + action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function () {
if (ajax_request != null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
} else {}, // <========== problem here
complete: function (data) {
ajax_request = null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code == 1) {
switch (action) {
case "getFeaturedMerchant":
displayFeaturedRestaurant(data.details.data, 'list-featured');
//$(".result-msg").text(data.details.total+" Restaurant found");
$(".result-msg").text(data.details.total + " " + getTrans("Featured Restaurants found", 'restaurant_found'));
break
) // <========== problem starts here
else {
/*failed condition*/
switch (action) {
case "getFeaturedMerchant":
createElement('list-featured', '');
//$(".result-msg").text(data.msg);
break;
}
},
error: function (request, error) {
hideAllModal();
if (action == "getLanguageSettings" || action == "registerMobile") {} else {
onsenAlert(getTrans("Network error has occurred please try again!", 'network_error'));
}
}
}
};
Add a missing brace in the problem area and you get this. But this is still not really correct. The two switch statements in the success handler are not correct syntax so they need to be fixed too. I think your issue is that you had some counteracting syntax errors that allowed the code to somehow run, but not execute in the proper way.
function callAjax(action, params) {
/*add language use parameters*/
params += "&lang_id=" + getStorage("default_lang");
dump(ajax_url + "/" + action + "?" + params);
ajax_request = $.ajax({
url: ajax_url + "/" + action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function () {
if (ajax_request != null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
}
}, // <======== Added this brace to close off the function
complete: function (data) {
ajax_request = null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code == 1) {
switch (action) {
case "getFeaturedMerchant":
displayFeaturedRestaurant(data.details.data, 'list-featured');
//$(".result-msg").text(data.details.total+" Restaurant found");
$(".result-msg").text(data.details.total + " " + getTrans("Featured Restaurants found", 'restaurant_found'));
break
) // <============= This is out of place and so are the next few lines
else {
/*failed condition*/
switch (action) {
case "getFeaturedMerchant":
createElement('list-featured', '');
//$(".result-msg").text(data.msg);
break;
}
},
error: function (request, error) {
hideAllModal();
if (action == "getLanguageSettings" || action == "registerMobile") {} else {
onsenAlert(getTrans("Network error has occurred please try again!", 'network_error'));
}
}
}
}
});
}
One possible way to approach fixing this is to fix the missing brace in the beforeSend: handler, then remove most of the success handler code to this stub and then add back in the proper code in the success handler under a careful eye:
function callAjax(action, params) {
/*add language use parameters*/
params += "&lang_id=" + getStorage("default_lang");
dump(ajax_url + "/" + action + "?" + params);
ajax_request = $.ajax({
url: ajax_url + "/" + action,
data: params,
type: 'post',
async: false,
dataType: 'jsonp',
timeout: 6000,
crossDomain: true,
beforeSend: function () {
if (ajax_request !== null) {
/*abort ajax*/
hideAllModal();
ajax_request.abort();
}
}, // <======== Added this brace to close off the function
complete: function (data) {
ajax_request = null;
hideAllModal();
},
success: function (data) {
dump(data);
if (data.code == 1) {
// <=========== Removed faulty code in here
}
}
});
}
Original Answer
That particular error and network response looks like your client wants some data from the server. The client (for some reason) decides that it needs to use JSONP to get the response from the server so the server is sending back JSONP, but the client code that sent the request did not properly prepare for the JSONP request by defining the appropriate callback function that the JSONP script can call.
You will either have to switch to a regular Ajax call that is not JSONP or we will have to see the details of your callAjax() implementation to see why the JSONP response is not working.

Calling Javascript function inside controller action -YII

I'm trying to call Javascript function inside controller action method, Is there any right way to call setTimeout() to be invoked on certain condition inside controller action method ?
window.setTimeout(function() {
alert("test");
$.ajax({
type: "POST",
url: "'.$this->createUrl("/operator/createViopNode/").'",
data: {
id: '.$bc_id.',
callid:"'.$num.'",
taskid:'.$this->taskid.'
},
success: function(msg){
var ifrm = document.getElementById("frame");
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write(msg);
ifrm.document.close();
},
error: function (jqXHR, textStatus, errorThrown){
alert("" + textStatus + ", " + errorThrown);
}
});
}, parseInt('.$tps_call.'));
I need to write above js function inside controller action method, how to write this ?
Index.csHtml
function abc()
{
alert("called")
}
now Ajax Call function
function ExecuteAjax(URL,Data,Success)
{
try {
$.ajax({
type: "post",
url: URL,
data: Data,
contentType: "json",
success: function (data) { if (typeof Success == "function") { Success(data); } }
})
} catch (e) {
alert(e.message)
}
}
Call ajax like this
ExecuteAjax("/Home/FillColorDropDown", "", function (data) {
eval(data.script);
});
return from controller
if(demo=="true")//put condition here whatever you want
{
string strscript="abc();";
}
protected JObject jobj = new JObject();
jobj.Add("Script", strscript);
return Json(jobj);
Execute js function when controller return success
You should register your javascript function like this:
function actionTest(){
$cs = Yii::app()->clientScript;
$cs->registerScript('my_script', 'alert("Hi there!");', CClientScript::POS_READY);
$this->render('any_view');
}
source

How to get data from ajax call?

I am trying to get data from ajax call by cross domain.
Here is code
function GetMaxWULen() {
var x;
$.ajax({
url : url,
method : 'POST',
jsonp : "callback",
async : false,
data : {
Function : "GetMaxWULen",
Authorization : Base64.encode(login + ":" + token),
WuType : $("#ddlWUType").val()
},
dataType : 'jsonp',
crossDomain : true,
error : function(request, status, error) {
alert('nie udało sie');
alert(error);
}
}).done(function(result) {
console.log('done result');
x = result;
console.log(x);
});
console.log('function end');
console.log(x);}
At the end of the function, x variable is undefined but in done event value is correct.
Could anyone can help me or tell what is wrong in this code?
This happens because your AJAX request is done asynchronously. It means the rest of your code won't wait your response be ready to continue.
If you need to use the data returned from AJAX outside your function, you might want to create a parameter to serve as a callback when the response is ready. For example:
function yourFunction(callback) {
$.ajax({
/* your options here */
}).done(function(result) {
/* do something with the result here */
callback(result); // invokes the callback function passed as parameter
});
}
And then call it:
yourFunction(function(result) {
console.log('Result: ', result);
});
Fiddle: http://jsfiddle.net/9duek/
try
$.ajax({
url : url,
method : 'POST',
jsonp : "callback",
async : false,
data : {
Function : "GetMaxWULen",
Authorization : Base64.encode(login + ":" + token),
WuType : $("#ddlWUType").val()
},
dataType : 'jsonp',
crossDomain : true,
error : function(request, status, error) {
alert('nie udało sie');
alert(error);
}
}).success(function(result) {
var datareturned = result.d;
console.log('done' + datareturned);
x = datareturned;
console.log(x);
});

No indication jquery ajax call completes

I have the following ajax call
function update_ledger_amount(id) {
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
success: function (str) {
var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}
},
error: function (request, status, error) {
alert(error);
}
});
}
The problem I'm having is that I get no alerts on success or error. Watching the traffic via firebug I can see the response is a simple
success
I believe the problem could have to do with the content-type of the response, it shows as text/javascript. I'm thinking maybe I need to do something different to handle that content type.
use dataType as json and send the response as json in your controller(php).. you can do that by ...echo json_encode(array('success'=>'success'))
JQUERY
$.ajax({
type: "POST",
url: "/ledgeritems/UpdateAmount",
data: "Id=" + id + "&Amount=" + $('#ledger_edit_amount_input_' + id).val(),
dataType:'json',
success: function (str) {
alert(str.success); //in mycase.. you can do your stuff here
/*var result = str.split('|');
alert(str);
if (result[0] == 'success') {
set_display_message('Item updated', 'success');
load_ledger_month($('#BankAccountId').val(), $('#StartDate').val());
}
else {
alert('bad');
set_display_message(result[1], 'error');
}*/
},
error: function (request, status, error) {
alert(error);
}
});
PHP
.....
echo json_encode(array('success'=>'success'));
this sends success as json and you can get that in success function of ajax
put a try catch block in your success handler. I guess it is failing at this line
ar result = str.split('|');
You're doing a POST ajax not GET. The data part of the ajax should be in the form of:
data: { name: "John", location: "Boston" }
Remove the line
type = "POST",
because you want to append params to the url with your request.
As of jQuery 1.8 success, error and complete are deprecated, use done, fail and allways instead.
http://api.jquery.com/jQuery.ajax/#jqXHR
The syntax for a POST would be like:
data = {id:"something", Amount:"someval"};

setting a jquery ajax request to async = false doesn't work

I'm attempting to get started with google wallet and am generating a jwt token via an ajax request.
When a user hits the purchase button it fires the purchase() function which in turn sends off some data to get the jwt using the get_jwt_token_for_user() function. I've set the ajax request to not be asynchronous to ensure that the jwt is sent to the google payments handler.
However the purchase() function seems to continue before the jwt is returned by the get_jwt_token_for_user() function. The log output shows that the numbers 1 and 2 are printed to console before the jwt is printed to the console from the get_jwt_token_for_user() function.
function get_jwt_token_for_user(the_key)
{
var JwtTokenURL = "/get_jwt_token";
var the_user_name = $('#user_name').val();
var the_user_email = $('#user_email').val();
var the_user_number = $('#user_number').val();
$.ajax({
type: "Get",
url: JwtTokenURL,
data: {user_number : the_user_number, user_name : the_user_name, user_email : the_user_email, the_d_key : the_key},
async: false,
success: function(result) {
var myObject = JSON.parse(result);
console.log(myObject.jwt_token);
return myObject.jwt_token
},
failure: function(fail){ alert(fail); }
});
}
function purchase(the_key)
{
console.log("1");
var jwt_token = get_jwt_token_for_user(the_key);
console.log("2");
if (jwt_token !== "")
{
console.log(jwt_token);
goog.payments.inapp.buy({
parameters: {},
'jwt' : jwt_token,
'success' : successHandler,
'failure' : failureHandler
});
}
}
Any idea what I can do to ensure that the ajax request has returned the data before the purchase() function marches on without the jwt value?
Your get_jwt_token_for_user function doesn't return anything, you need something more like this:
function get_jwt_token_for_user(the_key) {
//...
var myObject;
$.ajax({
//...
success: function(result) {
myObject = JSON.parse(result);
},
//...
});
return myObject ? myObject.jwt_token : '';
}
Returning something from your success callback doesn't cause that value to be returned by $.ajax and JavaScript functions do not return the value of their last expressions, you must include an explicit return if you want your function to return something.
You should also stop using async:false as soon as possible, it is rather user-hostile and it is going away. Your code should look more like this:
function get_jwt_token_for_user(the_key, callback) {
//...
$.ajax({
type: "Get",
url: JwtTokenURL,
data: {user_number : the_user_number, user_name : the_user_name, user_email : the_user_email, the_d_key : the_key},
success: function(result) {
var myObject = JSON.parse(result);
callback(myObject.jwt_token);
},
failure: function(fail){ alert(fail); }
});
}
function purchase(the_key) {
get_jwt_token_for_user(the_key, function(jwt_token) {
if (jwt_token !== "") {
//...
}
});
}

Categories