Re-run Ajax with data from its own response - javascript

Is it possible to insert into ajax post some altered variable from its own success data?
On page load, first ajax fires and shows some records from mysql, then I take last record ID and store it in latestID, next second ajax fires and retrieves only records from that ID forward and then stores the lastId and fires again.
$.ajax({
type: 'POST',
url: '{{ ... }}',
dataType: 'json',
'success': function (data) {
callback(data);
}
});
function callback(response) {
var idList = [];
var printer_category = response.printer.productcategory_id;
var printer_timer = parseInt(response.printer.timer);
var printer_storeid = response.printer.store_id;
var printer_physicalPrint = parseInt(response.printer.physical_print);
var printer_id = parseInt(response.printer.id);
var data = response.transactions;
console.log(response);
$.each(data, function (i, dataitem) {
console.log(dataitem);
idList.push(dataitem.id);
});
var latestID = Math.max.apply(Math, idList);
function getData() {
$.ajax({
type: 'POST',
url: '{{ ... }}',
dataType: 'json',
data: {latestID: latestID, printer_timer: printer_timer, printer_storeid: printer_storeid, printer_category: printer_category},
success: function (data) {
console.log(data);
data = data.transactions;
if (data != 0) {
var idList = [];
$.each(data, function (i, dataitem) {
console.log(dataitem);
idList.push(dataitem.id);
});
var latestID = Math.max.apply(Math, idList);
console.log(latestID);
}
}
});
}
getData();
setInterval(function () {
getData();
}, 10000);
}
});
If I console.log(latestID) inside the success: function it shows the correct value, but ajax posts data: {latestID: latestID}, value 1 on each setInterval run.
*EDIT: added entire code.

instead of var latestID = Math.max.apply(Math, idList);
use latestID = Math.max.apply(Math, idList); in success callback.
using var before the variable declares a method level variable overriding the value of global variable. As you want to keep on using the latestID, you need to have global variable.

Related

sum values from multiple ajax requests

im trying to get the total value of the data returned by the ajax requests, but it is showing total:0 because it is executing the totalRev before completing the ajax requests.
var totalRev = 0;
$.ajax({
type: "POST",
url: "cloudmobi.php",
data: {action: 'cloudmobi'},
dataType:'JSON',
success: function(response){
document.getElementById('cloudmobi').innerHTML = response.cloudmobi;
console.log(response.cloudmobi);
var cloudmobi = parseInt(response.cloudmobi);
console.log('CLOUDMOBI:'+cloudmobi);
totalRev += cloudmobi;
}
});
$.ajax({
type: "POST",
url: "mobusi.php",
data: {action: 'mobusi'},
dataType:'JSON',
success: function(response){
document.getElementById('mobusi').innerHTML = response.mobusi;
console.log(response.mobusi);
var mobusi = parseInt(response.mobusi);
totalRev += mobusi;
console.log('MOBUSI:'+mobusi);
}
});
$.ajax({
type: "POST",
url: "appnext.php",
data: {action: 'appnext'},
dataType:'JSON',
success: function(response){
document.getElementById('appnext').innerHTML = response.appnext;
console.log(response.appnext);
var appnext = parseInt(response.appnext);
totalRev += appnext;
console.log('APPNEXT:'+appnext);
}
});
console.log('TOTAL:'+totalRev);
I do not want to use async because the whole purpose of using ajax here is to load the site fast then dynamically load the data
jQuery "when" solves your problem:
$.when( d1, d2 ).done(function ( v1, v2 ) {
console.log( v1 ); // "Fish"
console.log( v2 ); // "Pizza"
});
It would be far better to send all the data in a single request so you can do the sum on the server and send it in a single property in the response.
Assuming, for whatever reason, you cannot do that, then you could instead store all the promises from the AJAX requests and then execute your code after all of them have completed and added their values to an array. Then you can sum the array. Something like this:
var values = [];
var promises = [
$.ajax({
// ajax settings...
success: function() {
values.push(parseInt(response.cloudmobi), 10);
}
}),
$.ajax({
// ajax settings...
success: function() {
values.push(parseInt(response.mobusi), 10);
}
}),
// Nrequests...
];
$.when.apply(this, promises).done(function() {
var sum = values.reduce(function(a, b) {
return a + b;
}, 0);
// work with sum here...
});

Assigning JSON value to a Variable that Resides Outside JavaScript Function

I have a question regarding JSON Web Services and AJAX Function. I have declared a JavaScript Function below.
function setJsonSer(){
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
alert("This is Set JSON In "+JSON.stringify(data));
}
});
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'GET',
data: formData,
complete: function(data) {
alert("This is Get JSON Out "+JSON.stringify(data));
}
});
}
As you can see I have alert the JSON.stingify(data) statement and it gave me the result as I expected.
Now I want to get that JSON response out of that particular function SetJsonSer() to assign to avariable that resides out side the SetJsonSer() function.
I already tried return JSON.stringify(data)) and JSON.stringify(data) statements but they did not put the result out from the SetJsonSer() function.
The output must grab from a variable like the below.
function Load(){
//-----------------------------------------------
setJsonSer();
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = "return value of JSON.stringify(data)";
This variable will be used as the query to draw a chart using HighCharts. So could you someone give me a clue how to get the result of the SetJsonSer() function?
Thanks and regards,
Chiranthaka
You're getting a bit mixed up with asynchronous nature of AJAX.
The AJAX event is being fired, but it won't be causing any pause in the execution of your code, as such, you need to implement a callback.
This code isn't particularly nice, but it should give you an idea of how the data needs to be handled.
function setJSONSer() {
formData = {
'Email': 'clientlink#russell.com',
'Password': 'russell1234',
'URL': getVaria()
};
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'POST',
data: formData,
complete: function(data) {
console.log("Successfullly set JSON!");
getJSONSer();
}
});
}
function getJSONSer()
{
$.ajax({
url: "/APIWebService.asmx/AnalyticsDataShowWithPost",
type: 'GET',
complete: function(data) {
//alert("This is Get JSON Out "+JSON.stringify(data));#
Load(data);
}
});
}
function BeginLoad()
{
setJSONSer();
}
function Load(data)
{
setJsonSer();
var labels = new Array();
var values = new Array();
var catogories = new Array();
var arrayOfArray = new Array();
var rowData = "return value of JSON.stringify(data)";
}
BeginLoad();

return ajax.done data gives error on jquery

I have data in my ajax.done and it bugs on jquery.
i googled on it and cant find anything.
what to do?
function select_aragement(arragament){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var postsjson;
var test= $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
}).done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
});
return postsjson;
}
You shouldn't be attempting to return anything from a callback function because the returned value doesn't go anywhere meaningful. Instead you simply use the response from the AJAX request inside that callback function.
Let's say you have this code:
function bar() {
var myObject = foo();
// do something with myObject
}
function foo() {
var bar; // 1
var xhr = $.ajax({
url: yourUrl,
dataType: 'json',
type: 'post',
data: {
some: 'data'
}
}); // 2
xhr.done(function(yourObject) {
bar = yourObject; // 5
}); // 3
return bar; // 4
}
bar();
The comments inside the foo function indicate the order in which those statements execute. So you declare a variable bar, declare a variable xhr that has a Deferred object, attach a done handler to it with a callback function, return the value of bar, then the value of bar is set (too late - you've already tried to return it).
Inside of your execution of the bar function myObject is going to be undefined, because the value of bar inside the foo function wasn't set before the return statement. What you need to do is simply move the // do something with myObject code to the callback function, and use bar there:
function foo() {
var xhr = $.ajax({
url: yourUrl,
dataType: 'json',
type: 'post',
data: {
some: 'data'
}
}); // 1
xhr.done(function(yourObject) {
var bar = yourObject; // 4
// do something with bar
}); // 2
// 3 - function execution has finished
}
You might want to move the return line inside the done section
}).done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
return postsjson;
});
but keep in mind that, being an asynchonous call, so will be your return. My advise would be to pass in a callback.
function select_aragement(arragament, callback){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var postsjson;
var test= $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
});
test.done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
callback && callback(postjson);
});
}
And modify your code to use the callback instead of the returned value.
before
var postjson=select_aragement(arragament);
...stuff with postjson...
after
select_aragement(arragament, function(postjson) {
...stuff with postjson...
});
You are trying to make the ajax call fire synchronously, for that you need to make the async property false.
async: false,
The problem :
Look at the following code :
function getValue(){
var value = 0;
setTimeout(function(){
value = 42;
}, 1000);
return value;
}
What is the returned value ?
fiddle
This is your exact same problem with
function select_aragement(arragament){
var postjson;
$.ajax(...).done(function(vis){
postjson = vis;
});
return postjson;
}
A solution :
I imagine you use your function in the following way :
var data = select_aragement(arragament);
// do something with data :
$.each(data, function(){
....
});
You can change select_aragement's code like this :
function select_aragement(arragament){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var test = $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
});
// return the promise which wraps the ajax call
return test;
}
and the calling code like this :
// "p" stands for "promise"
var p = function select_aragement(arragament);
p.done(function(data){
// do something with data :
$.each(data, function(){
....
});
});
or without the local variable :
select_aragement(arragament).done(function(data){
// do something with data :
$.each(data, function(){
....
});
});
In this case you can use async/await mixed to .done from jQuery like this:
async function myasyncfunction(myArgs){
var response = [];
var req = $.ajax({
method: "GET",
url: resquestURL,
dataType: "json",
})
await req.done( res => {
//DO some stuff with your data
for (let index = 0; index < res.length; index++) {
const element = res[index];
response .push( "some stuff" + element );
}
})
return response;
}

Accessing JSONP data outside of ajax call in jQuery

Now that every google link in the first 5 pages of results is :visited in my browser, I needed to ask...
How can I get the JSON data working so that I can access it/manipulate it in other methods?
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
// works here
console.log(data);
// works here as well & fires local function
testing(data);
// doesnt store
var testvar_1 = data;
}
});
// undefined
console.log(testvar_1);
function testing(data) {
// logs when called from above
console.log(data);
// doesnt store
var testvar_2 = data;
}
// undefined
console.log(testvar_2);
// havent found this yet...
return magicVariableThatLetsMeAccessJSON
}, ...
any ideas? i know theres a lot of other similar questions on stack overflow, but i have found nothing that solves this.
thanks
UPDATE
var storage;
var yourobj = {
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
storage = data;
// logs correctly
console.log(storage);
}
});
}
}
//undefined
console.log(storage);
yourobj._requestText();
//undefined
console.log(storage);
Firstly as noted elsewhere, you need a variable that's in scope, secondly you need to make sure it's not evaluated before the callback is called.
The only way to ensure that is to make the call to _otherMethod inside the success call back method
_otherMethod: function(text) {
//...do what ever you need to do with text
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
_otherMethod(data);
},
}
});
}
callbacks are asyncronous meaning they are called at some point in time that's not determined by the sequence of code lines.
If you know the code using the returned data is never going to be call before the success call back has executed and you need to hold on to the data you can change the code to
_otherMethod: null, //not strictly needed
_requestText: function() {
self = this;
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
self._otherMethod = function(data){
return function(){
//do what you need to with data. Data will be stored
//every execution of _otherMethod will use the same data
console.log(data);
}
}
},
}
});
}
Very simple. You need a storage variable outside of the context of the callback function.
var storage;
var yourobj = {
_otherMethod: function() {
// END GOAL OF WHERE I WANT THIS TO BE AVAILABLE
var text = this._requestText();
},
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
storage = data;
}
});
}
}
Alternatively, storage can be a property on the same object.
By adding var before your variable name, you create a local variable in the current scope.
This doesn't work:
var a = 2;
(function() {
var a = 3;
})();
console.log(a); // 2
While this does:
var a = 2;
(function() {
a = 3;
})();
console.log(a); // 3
Since the variable that you're trying to set is in an outer scope, get rid of var when working with it in an inner scope.
might be this way:
_requestText: function() {
var url = 'http://api.flickr.com/services/feeds/photos_public.gne?format=json';
var testvar_1;
$.ajax({
type: 'GET',
url: url,
async: false,
dataType: 'jsonp',
success: function(data) {
console.log(data);
testing(data);
testvar_1 = data;
}
});
// should work here
console.log(testvar_1);
Actually you were creating a new instance of that var there.

Issue with code inner variable

I have a code like the one stated below, please how do I get the value for (getData), using a code like:
var instanceArray = myGraph.getInstances(component)
I was thinking myGraph.getInstances(component).getData will do it, but it failed
this.getInstances = function(component) {
var getData = {};
$.ajax({
url: "/rpc/alerts2/commonObj_rpc.cfc?method=getInstances",
data: {"component":component},
type: "POST",
async: true,
success: function(data) {
getData = $.parseJSON(data);
console.log("hey");
var $render_component_instance = $("#instances").empty();
$("#instances").append($("<option />").val("all").text("All Instances (Summed)"));
$.each(getData, function (cIndex, cItem){
var $instance = $("<option />").val(cItem.si_instance).text(cItem.si_label.toUpperCase());
$render_component_instance.append($instance);
})
$("#instances").multiselect("refresh");
}
});
};`
You can't, the get is asynchronous. getInstances returns before the GET completes, so it's impossible for getInstances to return the data. (See further note below.)
You have (at least) three options:
Use a callback
Return a blank object that will get populated later, and have the code that needs it poll it periodically
Use a synchronous get (not a good idea)
1. Use a callback
What you can do instead is accept a callback, and then call it when the data arrives:
this.getInstances = function(component, callback) {
$.ajax({
url: "/rpc/alerts2/commonObj_rpc.cfc?method=getInstances",
data: {"component":component},
type: "POST",
async: true,
success: function(data) {
var getData = $.parseJSON(data);
console.log("hey");
var $render_component_instance = $("#instances").empty();
$("#instances").append($("<option />").val("all").text("All Instances (Summed)"));
$.each(getData, function (cIndex, cItem){
var $instance = $("<option />").val(cItem.si_instance).text(cItem.si_label.toUpperCase());
$render_component_instance.append($instance);
})
$("#instances").multiselect("refresh");
callback(getData);
}
});
};
And call it like this:
myGraph.getInstances(component, function(data) {
// Use the data here
});
2. Return a blank object that will get populated later
Alternately, you can return an object which will be blank to start with, but which you'll add the data to as a property later. This may be closest to what you were looking for, from your comments below. Basically, there's no way to access a function's local variables from outside the function, but you can return an object and then add a property to it later.
this.getInstances = function(component) {
var obj = {};
$.ajax({
url: "/rpc/alerts2/commonObj_rpc.cfc?method=getInstances",
data: {"component":component},
type: "POST",
async: false, // <==== Note the change
success: function(data) {
var getData = $.parseJSON(data);
console.log("hey");
var $render_component_instance = $("#instances").empty();
$("#instances").append($("<option />").val("all").text("All Instances (Summed)"));
$.each(getData, function (cIndex, cItem){
var $instance = $("<option />").val(cItem.si_instance).text(cItem.si_label.toUpperCase());
$render_component_instance.append($instance);
})
$("#instances").multiselect("refresh");
// Make the data available on the object
obj.getData = getData;
}
});
return obj; // Will be empty when we return it
};
And call it like this:
var obj = myGraph.getInstances(component);
// ...later...
if (obj.getData) {
// We have the data, use it
}
else {
// We still don't have the data
}
3. Use a synchronous get
I do not recommend this, but you could make the call synchronous. Note that synchronous ajax requests will go away in a future version of jQuery. But just for completeness:
this.getInstances = function(component) {
var getData;
$.ajax({
url: "/rpc/alerts2/commonObj_rpc.cfc?method=getInstances",
data: {"component":component},
type: "POST",
async: false, // <==== Note the change
success: function(data) {
var getData = $.parseJSON(data);
console.log("hey");
var $render_component_instance = $("#instances").empty();
$("#instances").append($("<option />").val("all").text("All Instances (Summed)"));
$.each(getData, function (cIndex, cItem){
var $instance = $("<option />").val(cItem.si_instance).text(cItem.si_label.toUpperCase());
$render_component_instance.append($instance);
})
$("#instances").multiselect("refresh");
}
});
return getData;
};
And call it like this:
var getData = myGraph.getInstances(component);
But again, I don't advocate that. Synchronous ajax calls lock up the UI of the browser, leading to a bad user experience.

Categories

Resources