Async AJAX request wrapped in function won't work with promise() - javascript

I am executing async AJAX requests which are being wrapped into function. Where $.ajax is Deferred object and I can use .promise properly (check: Initially Loaded) then I won't be able to do the same with 'Now really loaded' which will be executed before ajax finish loading.
function WSCall(method, data, callback, type, async, bg) {
// .. code ..
var promise = $.ajax({
'url': useSampleData ? useSampleData || null,
//'async': false,
'type': 'POST',
'dataType': (type == null) ? 'json' : type,
'data': data,
'beforeSend': bg ? null : LoadingBegin,
'complete': bg ? null : LoadingEnd,
'success': callback,
'error' : bg ? null : function(jqXHR, textStatus, errorThrown) { networkError = 1; }
});
promise.done(function(){ console.log('Initially loaded') });
}
function aSyncEvent() {
WSCall(
'status',
{},
function (data) {
if (data.error) {
console.log('Error occured'); return ShowDialogAlert(data.error); }
if (data.statusResult) {
var parts = data.statusResult.split('-');
if (parts[1] === '0') {
sId = parts[0];
console.log('Wow its loaded!');
return true;
}
}
}
)
}
$.when( aSyncEvent() ).then( function () { console.log('now really loaded')});
Initially loaded and Wow its loaded will appear properly AFTER ajax has been executed in proper order however 'now really loaded' will appear before ajax finishes executing.
I beg for help regarding this matter.
Thanks
Mike

Have you tried returning your deferred?
function WSCall(method, data, callback, type, async, bg) {
// .. code ..
return promise.done(function(){ console.log('Initially loaded') });
}
and
function aSyncEvent() {
return WSCall(
// .. code ..
);
}

Related

How can I serve a "resolve" in my recursive AJAX calls so that I can use 'done'?

I am doing a few recurring AJAX calls where I pass an array from the front-end to the back-end and whenever it comes back to the front-end, the array gets smaller (by 1) and ultimately it'll be empty, therefore my recursive calls will stop.
Here's my calls:
function download_required_files(demo_data) {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
return false;
}
if(data.can_continue !== 'yes') {
return false;
}
if(data.remaining_steps && data.remaining_steps.length) {
demo_data.steps_to_take = data.remaining_steps;
download_required_files(demo_data);
}
$('.demo-loader-content').fadeOut();
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
Assuming I have 2 steps to download files for, this download_required_files will run twice, then it'll be done, but if I do:
var download_process = download_required_files(demo_data) //Runs 2 times
download_process.done(function() { //Do stuff here once that function ran 2 times });
It gives me the: Cannot read property 'done' of undefined error and for good reason. That download_process is not a promise object for it to have that property, it's just...empty.
Where should I intervene in my download_required_files so that it signals to outside code that "Hey, in a promise environment, I'm done!"?
Although the result of the call to $.ajax is a jqXHR object, which is promise-like, for what you describe I think I'd go with your own native Promise (or Deferred if you prefer) to represent the overall recursive process:
function download_required_files(demo_data) {
return new Promise(function(resolve, reject) {
function worker() {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
// *** All done
$('.demo-loader-content').fadeOut();
resolve();
} else if(data.can_continue !== 'yes') {
// *** All done; but is this an error condition? If so
// use `reject` instead of `resolve` below.
$('.demo-loader-content').fadeOut();
resolve();
} else {
demo_data.steps_to_take = data.remaining_steps;
worker(); // This is the internal recursive call
}
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
worker();
});
}
Or using Deferred instead:
function download_required_files(demo_data) {
var d = $.Deferred();
function worker() {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
// *** All done
$('.demo-loader-content').fadeOut();
d.resolve();
} else if(data.can_continue !== 'yes') {
// *** All done; but is this an error condition? If so
// use `d.reject` instead of `d.resolve` below.
$('.demo-loader-content').fadeOut();
d.resolve();
} else {
demo_data.steps_to_take = data.remaining_steps;
worker(); // This is the internal recursive call
}
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
worker();
return d.promise();
}
This would be my approach, separating the individual AJAX requests from the looping over the content, and that also from the DOM updates:
function download_one_file(demo_data) {
return jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: setup_page_params.ajax_nonce,
content_install_request_data: JSON.stringify(demo_data),
}
});
}
function download_loop(demo_data) {
return download_one_file(demo_data).then(function(data) {
if (!data) {
return Promise.reject();
} else if (data.remaining_steps && data.remaining_steps.length) {
demo_data.steps_to_take = data.remaining_steps;
return download_loop(demo_data);
} else {
return Promise.resolve();
}
});
}
function download_required_files(demo_data) {
return download_loop(demo_data).finally(function() {
$('.demo-loader-content').fadeOut();
});
}

Nested promise functions

I have a button that I want to track when the user press it, and if the tracking ajax call returns data, then execute a promise, when thats all done, continue with the button event.
Below is what I have so far, however the button event and the 2nd promise fire at the same time. The button event isn't waiting for the 2nd promise to resolve
Click button
AJAX call records the event
If AJAX doesn't return a question then alert hello.
If the AJAX call returns a question, then build and open modal, when modal closes, then alert hello.
$('.my_button').on('click', function() {
ui_tracking('button_1').then(function () {
alert('Hello');
});
});
function ui_tracking(type, payload) {
var deferred = $.Deferred();
var log_action = function () {
$.ajax({
url: '/api/submit_action',
type: 'POST',
dataType: 'json',
data: {
type: type,
payload: JSON.stringify(payload)
},
success: function(results, textStatus, xhr) {
if (typeof(results) !== 'undefined' && results !== null) {
if (typeof(results.data) !== 'undefined' && results.data !== null) {
if (results.data.question) {
startQuestion(results.data.question).then(function () {
deferred.resolve();
}, function() {
deferred.reject();
});
}
}
}
deferred.resolve();
},
error: function (xhr, textStatus, errorThrown) {
deferred.reject();
}
});
};
log_action();
return deferred.promise();
}
function startQuestion(question_data) {
var deferred = $.Deferred();
var openQuestion = function () {
$('#question-modal .modal-body .question').html(question_data.question).attr('data-question-id', question_data.id);
$('#question-modal').modal('show').on('hidden.bs.modal', function (e) {
deferred.resolve();
$('#question-modal').unbind('hidden.bs.modal');
});
};
openQuestion();
return deferred.promise();
}
sf
your success: callback calls deferred.resolve(); straight away (at the end, after the if condition)
success: function(results, textStatus, xhr) {
if (typeof(results) !== 'undefined' && results !== null) {
if (typeof(results.data) !== 'undefined' && results.data !== null) {
if (results.data.question) {
startQuestion(results.data.question).then(function () {
deferred.resolve();
}, function() {
deferred.reject();
});
}
}
}
// this gets called regardless of the above conditions!
deferred.resolve();
Knowing $.ajax returns a (jQuery) Promise, I believe you could simplify ui_tracking function as follows:
function ui_tracking(type, payload) {
return $.ajax({
url: '/api/submit_action',
type: 'POST',
dataType: 'json',
data: {
type: type,
payload: JSON.stringify(payload)
}
}).then(function(results) {
if (results && results.data && results.data.question) {
return startQuestion(results.data.question);
}
});
}
In the above .then, if the conditions are not met, the return is undefined ... basically the same thing as you were doing with deferred.resolve() - the returned Promise will be resolved to undefined once the ajax completes
However, if the conditions are all met, the return is the Promise returned by startQuestion - which will mean the returned Promise will be that which is returned by startQuestion - therefore your code will wait on that promise to resolve before continuing
Also, no need for error handling that simply returns a rejected promise - let the outer call handle errors
Alternatively, you could write the whole lot as
$('.my_button').on('click', function() {
ui_tracking('button_1')
.then(startQuestion)
.then(function () {
alert('Hello');
});
});
function ui_tracking(type, payload) {
return $.ajax({
url: '/api/submit_action',
type: 'POST',
dataType: 'json',
data: {
type: type,
payload: JSON.stringify(payload)
}
});
}
function startQuestion(results) {
var deferred;
var openQuestion = function (question_data) {
$('#question-modal .modal-body .question').html(question_data.question).attr('data-question-id', question_data.id);
$('#question-modal').modal('show').on('hidden.bs.modal', function (e) {
deferred.resolve();
$('#question-modal').unbind('hidden.bs.modal');
});
};
if (results && results.data && results.data.question) {
deferred = $.Deferred();
openQuestion(results.data.question);
return deferred.promise();
}
}
Sure the logic has moved about, so maybe not exactly what you'd like
You can encapsulate each "step" in a function returning a promise (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) and then "chain" them.
This is a great post on executing promises in a series: http://www.datchley.name/promise-patterns-anti-patterns/#executingpromisesinseries (you may need a polyfill for your promising: https://github.com/stefanpenner/es6-promise)

Trouble forming a promise chain

I have a function that has to connect to DB to get a upload token, then upload a file, then close the stream and log the file in DB. I'm having trouble chaining all this together.
var saveNewRequest = function (image_arr) {
return $.ajax({
url: 'http://' + AppVar.ServerUrlWithPort + '/restapi/MtReqNewRequest_SaveData',
type: 'POST',
data: JSON.stringify({
'SessionId': AppVar.SessionId,
'Name': $('#MtReqNewRequest_name').val(),
'Desc': $('#MtReqNewRequest_desc').val(),
'Obj': $('#MtReqNewRequest_obj').val(),
'Priority': $('#MtReqNewRequest_priority2').val(),
'Status': $('#MtReqNewRequest_status2').val(),
'Type': $('#MtReqNewRequest_type2').val()
}),
dataType: 'json',
contentType: "application/json",
timeout: 10000
}).done(function (response) {
if (response.ResultCode === '0') {
if (image_arr.length != 0) {
//this is recursively called upload function which returns jQuery promise (this works as intended)
// the promise resolves with RequestId which I need later on
return uploadImages(image_arr, image_arr.length, 0, response.RequestId)
} else {
//I would like this to return just this RequestId
Promise.resolve(response.RequestId)
}
} else {
Promise.reject().promise();
}
}).fail(function (x, t, m) {
if (t === "timeout") {
reject("Timeout: " + t);
} else {
reject($.i18n('Error-RetrivingDataProblem'));
}
})
}
And I call this in an event:
MtReq.saveNewRequest(image_arr).then(function (output) {
AppVar.nav.popPage().then(function () {
Utility.hideModalWithProgressBar();
if (!isNaN(output)) {
setTimeout(500, AppVar.nav.pushPage("MtReqRequestPage.html", { animation: "slide", id: output }));
}
})
}).catch(function (e) {
Utility.hideModalWithProgressBar();
ons.notification.alert(e);
})
I need to pass the RequestID to the AppVar.nav.pushPage, to open the page I just created. However, I'm getting whole response of the very first Ajax request in saveNewRequest.
This is Cordova app, using OnsenUI framework (but that's not relevant to the problem). Also, I'm using latest BluebirdJs as Promise polyfill (which to my knowledge should make JS and jQuery promises compatible).
Thanks for any help!
Substitute .then() for .done(); .done() returns same jQuery promise object returned by $.ajax(). return the Promise or other value from .then().
var saveNewRequest = function (image_arr) {
return $.ajax({
url: 'http://' + AppVar.ServerUrlWithPort + '/restapi/MtReqNewRequest_SaveData',
type: 'POST',
data: JSON.stringify({
'SessionId': AppVar.SessionId,
'Name': $('#MtReqNewRequest_name').val(),
'Desc': $('#MtReqNewRequest_desc').val(),
'Obj': $('#MtReqNewRequest_obj').val(),
'Priority': $('#MtReqNewRequest_priority2').val(),
'Status': $('#MtReqNewRequest_status2').val(),
'Type': $('#MtReqNewRequest_type2').val()
}),
dataType: 'json',
contentType: "application/json",
timeout: 10000
}).then(function (response) {
if (response.ResultCode === '0') {
if (image_arr.length != 0) {
//this is recursively called upload function which returns jQuery promise (this works as intended)
// the promise resolves with RequestId which I need later on
return uploadImages(image_arr, image_arr.length, 0, response.RequestId)
} else {
//I would like this to return just this RequestId
// added `return`
return Promise.resolve(response.RequestId)
}
} else {
// note `return`, removed `.promise()`
return Promise.reject()
}
}).fail(function (x, t, m) {
if (t === "timeout") {
// included `Promise`, chain `.reject()`
// note, `return`
return Promise.reject("Timeout: " + t);
} else {
// note `Promise.reject()`, added `return`
return Promise.reject($.i18n('Error-RetrivingDataProblem'));
}
})
}

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.

how to stop one method execution untill another method completes in javascript with Linkedin API people search?

I am calling IN.API.PeopleSearch() from a for loop, and this for loop is in ajax success method, but before completing for loop execution, ajax method complete is getting called.
I want to stop until the for loop completes.
$.ajax({
type: 'GET',
dataType: 'json',
url: "get_data.htm",
async : false,
success: function(data, textStatus ){
for(i in data){
searchClick(data[i].firstName,data[i].lastName);
}
alert(resultArray);//here i want to send the response to server side
}
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
here is my searchClick function :
function searchClick(firstName, secondName) {
if (!IN.ENV.auth.oauth_token) {
alert("You must login w/ LinkedIn to use the Search functionality!");
return;
}
IN.API.PeopleSearch()
.fields("id", "firstName", "lastName","emailAddress","headline","industry","pictureUrl","positions",
"summary","numConnections")
.params({
"first-name": firstName,
"last-name": secondName
})
.result(function(result, metadata) {
for (i in result.people.values) {
try{
resultArray[i] = result.people.values[i];
}catch(err){
alert(err);
}
}
});
}
alert(resultArray) is getting called before completion of for loop, how to handle this.
I don't know if I get your question, but maybe something like that works for you: (not tested)
var Queue = function(callback) {
this.count = 0;
this.done = 0;
this.callback = callback;
};
Queue.prototype.oneDone = function() {
if (++this.done == this.count) {
this.callback();
}
}
Queue.prototype.process = function(data, callback) {
this.count = data.length;
for (i in data ) {
callback(data[i], this);
}
};
$.ajax({
type: 'GET',
dataType: 'json',
url: "get_data.htm",
async : false,
success: function(data, textStatus) {
var myQueue = new Queue(function() {
alert(resultArray); //here i want to send the response to server side
});
myQueue.process(data, function(item, queue) {
searchClick(item.firstName, item.lastName, queue);
});
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
function searchClick(firstName, secondName, queue) {
if (!IN.ENV.auth.oauth_token) {
alert("You must login w/ LinkedIn to use the Search functionality!");
return;
}
IN.API.PeopleSearch()
.fields("id", "firstName", "lastName","emailAddress","headline","industry","pictureUrl","positions",
"summary","numConnections")
.params({
"first-name": firstName,
"last-name": secondName
})
.result(function(result, metadata) {
for (i in result.people.values) {
try {
resultArray[i] = result.people.values[i];
} catch(err) {
alert(err);
}
}
if (queue) {
queue.oneDone();
}
});
}
I don't know what you are doing exactly, but can say we have one method, async
Function.prototype.async = function () {
setTimeout.bind(null, this, 0).apply(null, arguments);
};
This allows me to write code like this:
alert.async("This will be displayed later.");
alert("This will be displayed first.");
so the code with .async will called once the other event is completed.
Else in your case, use
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
for checking if the document is ready then send /fill /success. this is Raw AJAX method. :)
O hope this may help :)

Categories