how to print values in array of deferred objects? - javascript

I have the following requests:
var req1 = $.ajax({
type: "GET",
url: url,
dataType : "xml"
});
req1.done(function (resp1) {
$(resp1).find('interest').each(function() {
var interest_id = $(this).find('id').text();
var interest_name = $(this).find('name').text();
var request = $.ajax({
type:"GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&page="+ interest_name + "&redirects&prop=text",
dataType: "jsonp"
});
requestsArray.push(request);
});
$.when.apply(null, requestsArray).done(function () {
console.log("entrou");
});
});
But when i get inside of
$.when.apply(null, requestsArray).done(function () {
console.log("entrou");
});
I dont know how to reach the individual responses in requestsArray. how can i do that? i have tried and tried but nothing seems to work.

You can use the arguments object to access an unknown number of values passed to a function:
$.when.apply($, requestsArray).done(function(){
console.log(arguments); //plain arguments object
console.log([].slice.call(arguments)); //arguments turned into real array
});
See MDN docs on the arguments object
Since you are pushing $.ajaxs into your array you might consider getting rid of the additional arguments they will pass like:
var request = $.ajax({
type:"GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&page="+ interest_name + "&redirects&prop=text",
dataType: "jsonp"
}).then(function(data, textStatus, jqXHR){
return data; //this will make sure textStatus and jqXHR aren't passed any further
});

Related

AJAX: Store PHP data in a Javascript variable

As stated in the title, I have an ajax call. On the success function I want to store the returned data into a variable for use in my javascript. randNum.php simply returns a random number every 2 seconds, and I would like to use that number for other functions in my scripts. How can I use the data sent back from the php file in my javascript?
I know there are more logical ways to go about this, but want to know how to accomplish the task this way.
var result;
var interval = 2000;
function myCall() {
var request = $.ajax({
url: "randNum.php",
type: "GET",
dataType: "html",
success:function (msg) {
result = msg; //Not working as I intend
setTimeout(myCall, interval);
}
});
}
function(){
do something with result;
}
Declare a Global variable outside of the function and assign response variable to it after the ajax response.
var results;
function TestJSONP(){
$.ajax({
url: "randNum.php",
jsonp: "callback",
dataType: "jsonp",
success: function (response) {
console.log(response);
results = response;
}
});
}
You might not need to specify dataType, but use jqXHR.responseText to get the raw response. Something like
function myCall() {
var request = $.ajax({
url: "randNum.php",
type: "GET",
success:function (data, textStatus, jqXHR) {
result = jqXHR.responseText;
setTimeout(myCall, interval);
}
});
}
When you set dataType, and the response is not that type, then the ajax did not succeed and error call back will be invoked.

Data is lost after ajax call

I've got one ajax call after two previous. I need to pass results of those calls to the new one, so I do the following
$.when(getRespData(), getAxisComponents()).done(function (respData, axisData) {
var a = respData; //everything is ok
var b = axisData; //everything is ok
$.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName+ '&type=' + 'VAL',
success: (function (data) {
var c = respData; //everything is ok
var d = axisData; // Uncaught ReferenceError: axisData is not defined
}
but I've got Uncaught ReferenceError when I try to get my axisData inside my new ajax call, although operations with respData are ok.
My first 2 ajax calls look like
function getRespData() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload?runName=' + runName + '&type=' + 'RESP',
success: (function (data) {
return data;
})
});
}
function getAxisComponents() {
return $.ajax({
dataType: "json",
url: '/rest/visualization/' + taskName + '/workload/axis?runName=' + runName,
success: (function (data) {
return data;
})
});
}
where runName, type, taskName are some params of function which contains all these ajax calls.
How can I fix this error, so that I would be able to access both respData and axisData ind my inner ajax call?
i solved it putting async false and declaring an array out of ajax call, like this
let array = [];
$.ajax({
url: path,
type: 'GET',
async: false,
dataType: 'json',
success: function(response){
array = response;
}
});
return array;
You're calling data in your success function but data isn't set before this.
In a jQuery .ajax function, data is the data that is sent to the server when performing the Ajax request, which is why you may think it is lost (because it was never there).
Consider the following:
$.ajax({
data: {"data": data},
dataType: "json",
url: 'yourURl',
success: function(data){
return data;
}

Jquery Ajax Call Return

I have made a function which is the one below that i pass data to and returns the result as is. I made this way because i will be needing a lot of ajax call and i just made a function that i pass the data to and get the result as is and work with the result.
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}});
return ret;}
Now i am calling it where i need it:
$('#register-name, #register-surname').keyup(function(e) {
var x = FunctionsCall({query: $(this).val(), funcid: 1});
(x!==1) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error'); });
But strange is that i always see x as undefined. Pointing out the ret is filled with either 1 or 0 i don't know why it is not being passed to x.
Can you please help me out? It might be simple but i just experiment when needed with javascript and jquery.
Regards
ret doesn't get set until the success function runs, which is when the ajax finishes. FunctionCall returns straight away however. You'll either need to return the ajax deferred object or put your addClass/removeClass functionality in your success function.
A way to add your addClass/removeClass functionality to your success function would be like this:
function FunctionsCall(data, successFn) {
$.ajax({
type: 'GET',
url: 'includes/helpers/functions.php',
dataType: "json",
data: data,
success: successFn
});
}
$('#register-name, #register-surname').keyup(function(e) {
var element = $(this);
var data = { query: element.val(), funcid: 1 };
var successFn = function(x) {
if (x !== 1) {
element.addClass('input-has-error')
} else {
element.removeClass('input-has-error');
}
}
FunctionsCall(data, successFn);
});
The problem is that the ajax call takes time to execute, whereas your processing of x is immediately after the call to FunctionsCall
Imagine that in order to go to the php file and get the result, the browser has to send a request over the wire, the server needs to process the request and return the value, again over the wire. This process takes an unpredictable amount of time as it relies on network connections and server specs / current load.
The code to call the function and process the result happens immediately after this step and as such won't have the required values when it is run (browsers are much quicker at executing the next step than networks are at processing requests).
The best thing to do is to wrap your processing code up in it's own function, so it isn't immediately called, then call that function with the result once you get it. Like this:
// function defined, won't be called until you say so
var processMe = function(result) {
alert(result);
}
$.ajax({
// ajax params
success: function(result) {
// function called within success - when we know the request is fully
// processed, however long it takes
processMe(result));
}
});
You could also do the processing directly in the success block but the advantage of using a function is it's there to re-use in the future, plus, you also get to give it a nice understandable name, like outputValidatedMessage.
you must send ajax request syncronous
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
async: false,
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}
});
return ret;
}
Ajax calls are asynchronous.
This means that while you call $.ajax(), the function continues to run and return x which is undefined, as the ajax response has not been send yet.
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
async: false,
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}
});
return ret;
}
The below should work for you
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
(result !==1 ) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error'); });
}});
}
maybe is because the ajax function is called asynchronously so the line var x= .... doesn't wait for the asignment and thats why is undefined. for that you should use a promise here is an example http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
check if the following works, may be your GET method is taking time to execute.
var x;
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
x= result;
alert(x)
}});
return ret;}
if the snippet works, you should make you synchronous async: false or make callback function
try this code.
function FunctionsCall(data,callback) {
try {
ajax({
type: 'GET',
url: 'includes/helpers/functions.php',
dataType: "json",
data: data,
success: function (result) {
callback(result);
}
});
} catch(e) {
alert(e.description);
}
}
$('#register-name, #register-surname').keyup(function (e) {
var data = {
uery: $(this).val(),
funcid: 1
};
FunctionsCall(JSON.stringify(data), function (result) {
(result !== 1) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error');
});
});

Uncaught TypeError: callback is not a function

I have a function:
reportAdminActions.reportMemberList(project, function(data) {
console.log(data);
});
This function is called by another ajax operation like these:
reportMemberList: function(projectId, callback) {
var projectDetail = new Object();
projectDetail.projectId = projectId;
var pluginArrayProject = new Array();
pluginArrayProject.push(projectDetail);
$.ajax({
url : ConfigCom.serverUrl + 'projectreportonmember',
dataType: "jsonp",
type: "POST",
data: JSON.stringify(pluginArrayProject)
}).always(function(data) {
callback(data.responseText);
});
}
I need return value to function defined area after ajax operation. But here I got a error
Uncaught TypeError: callback is not a function
Check the rest of your code for calls to reportMemberList and make sure you always call it with the callback as a parameter. If you omit the callback parameter anywhere (e.g. call reportMemberList with just the projectId parameter), the code above would parse correctly the other calls to the function with the callback would produce the error. (This was the solution for me.)
guessing, but try to change your "jsonp" to "json". If you don't make cross-origin requests there, it should work
reportMemberList: function(projectId, callback) {
var projectDetail = new Object();
projectDetail.projectId = projectId;
var pluginArrayProject = new Array();
pluginArrayProject.push(projectDetail);
$.ajax({
url : ConfigCom.serverUrl + 'projectreportonmember',
dataType: "json",
type: "POST",
data: JSON.stringify(pluginArrayProject)
}).always(function(data) {
callback(data.responseText);
});
}

How can I return a variable from a $.getJSON function

I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()
j.getJSON(url, data, function(result)
{
var studentId = result.Something;
});
//use studentId here
I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does
it doesn't seem to work the same way
c# does
To accomplish scoping similar to C#, disable async operations and set dataType to json:
var mydata = [];
$.ajax({
url: 'data.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json.whatever;
}
});
alert(mydata); // has value of json.whatever
Yeah, my previous answer does not work because I didn't pay any attention to your code. :)
The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should:
var studentId = null;
j.getJSON(url, data, function(result)
{
studentId = result.Something;
});
// studentId is still null right here, because this line
// executes before the line that sets its value to result.Something
Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.
Even simpler than all the above. As explained earlier $.getJSON executes async which causes the problem. Instead of refactoring all your code to the $.ajax method just insert the following in the top of your main .js file to disable the async behaviour:
$.ajaxSetup({
async: false
});
good luck!
If you wish delegate to other functions you can also extend jquery with the $.fn. notation like so:
var this.studentId = null;
$.getJSON(url, data,
function(result){
$.fn.delegateJSONResult(result.Something);
}
);
$.fn.delegateJSONResult = function(something){
this.studentId = something;
}
var context;
$.ajax({
url: 'file.json',
async: false,
dataType: 'json',
success: function (json) {
assignVariable(json);
}
});
function assignVariable(data) {
context = data;
}
alert(context);
hmm, if you've serialized an object with the StudentId property then I think that it will be:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0].StudentId;
}
But if you're just returning the StudentId itself maybe it's:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0];
}
Edit: Or maybe .length isn't even required (I've only returned generic collections in JSON).
Edit #2, this works, I just tested:
var studentId;
jQuery.getJSON(url, data, function(json) {
if (json)
studentId = json;
});
Edit #3, here's the actual JS I used:
$.ajax({
type: "POST",
url: pageName + "/GetStudentTest",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
alert(json);
}
});
And in the aspx.vb:
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function GetStudentTest(ByVal id As String) As Integer
Return 42
End Function

Categories

Resources