multiple ajax call and array variables - javascript

I am running in to some interesting situation. on my application I have couple of situations.
1. I have to grab data from two different sources.(for that i have used ajax call).
2. I have to manipulate those data comparing to each other. if both are equal than third array will gets the value input from first array first array. and Eventually i have to return the third value and work on my graphs.
so for that I have :
getData : function(){
var bubbleArray= [];
var companyData=[];
var managerData =[];
$.ajax({
async: false,
url: "data/companyData.json",
dataType: "json",
success: function (bubbleJsonData){
$.each (bubbleJsonData.main.DATA_RECORD, function(index, response){
if(response.C_HRS!=0&&response.D_CUST_HRS!=0){
companyData.push([(response.C_HRS/442)*100, (response.D_CUST_HRS/442)*100, ((response.D_CUST_HRS/response.C_HRS)*100), response.C_HRS, response.D_CUST_HRS, response.CPY_NAME ]);
}
});
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error:"+ errorThrown);
}
//ajax call to get the managerData.
$.ajax({
async: false,
url: "data/managerData.json",
dataType:"json",
success: function(managerjsonData){
$.each (managerjsonData.main.DATA _RECORD, function(index, responsedata){
if(responsedata.CPY_NAME!=""){
managerData.push([responseData.CPY_NAME]);
}
});
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error:"+ errorThrown);
}
});
});
now, I have to compare the managerData. CPY_NAME with companyData.CPY_NAME if the match found generate the bubbleArray with the details of companyData means bubbleArray should have C_HRS, D_CUST_HRS,..........
if any help available form anybody would be highly appreciated

You need to wait until both the requests finish and save their results in some variable, and then compare them.
var yourAjaxRequests = [];
var jqXHR = $.ajax();
yourAjaxRequests.push(jqXHR);
$.when.apply($, yourAjaxRequests).done(function() {
/* compare logic here */
);

Related

jQuery Ajax each function check return ID is the same as the previous one

I am using AJAX to grab data from a remove server , then I am using each to loop.
Now what I want to do is if the return value data is the same as the previous one I do something
I have 10 val.userId == 1 , I wanna to do sth in once only not in 10 times.
how about in the real case I do not know the user ID i wanna make it dynamic
fox example user 12123 has 10 times , user 1239823 has 1000 times
FOr example here
https://jsonplaceholder.typicode.com/posts
$(document).ready(function(){
getData();
});
function getData(){
$.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
dataType: 'json',
success: function(response){
$.each(response, function(index, val) {
console.log(val); // get all return data
// as we can see userId == 1 have 10 posts , I just want to console.log only once if usdId == 1
if(val.userId == 1){
console.log(val.userId); // this one consoloe .log 10 times since we have 10 userId
}
// how about in the real case I do not know the user ID i wanna make it dynamic
// fox example user 12123 has 10 times , user 1239823 has 1000 times
});
},
error: function(xhr, textStatus, error){console.log(xhr.statusText);console.log(textStatus);console.log(error);
}
});
}
thanks for reading
If you want to remove duplicate items based on userId, you can make a loop with the response and filter them.
$(document).ready(function(){
getData();
});
function getData(){
$.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
dataType: 'json',
success: function(response){
var arr = [];
response.forEach(function (item) {
var result = arr.find(x => x.userId === item.userId);
if (!result) {
arr.push(item);
}
});
console.log(arr);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Best way to call function inside of another function JavaScript/JQuery?

I have built function that checks if record exist in local storage, if not trigger ajax call to get the data. Once data is returned I set the data in local storage. After this function completes I have to pass the data to another function that will feed the data in the form. I'm wondering what is the best practice now days to achieve this? I see more object oriented JavaScript now days and I'm wondering if any of OOP methods can be applied in this case. Here is example of my fucntion:
function getData(fnName,storageID,recID){
var inStorage = localStorage.hasOwnProperty(storageID) ? true : false,
frmData;
if(inStorage) {
frmData = JSON.parse(localStorage.getItem(storageID));
}else{
$.ajax({
type: 'POST',
url: 'AjaxFunctions.cfc?method='+fnName,
data: {'recID':recID},
dataType: 'json',
async: false
}).done(function(obj){
if(obj.STATUS == "200"){
var storageData = $.isEmptyObject(obj.DATA) ? null : JSON.stringify(obj.DATA);
localStorage.setItem(storageID,storageData);
frmData = storageData;
}else{
$('#error').html(obj.MESSAGE);
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
}
//frmFeed(frmData);
return frmData;
}
Function above once completed should pass the data in another function that will populate the form:
function frmFeed(frmData){
//Loop over frmData and populate the fields
}
I know the one way to accomplish this is to simply call frmFeed inside getData function that I showed above (commented code). is there any other way to call frmFeed and pass the data? If anyone can provide some example please let me know. Thank you!
There are several ways:
Callbacks
Promises
Not recommended would be to use synchronous ajax requests because it will block the UI.
Here's an implementation using promises:
function getData(fnName,storageID,recID){
return new Promise(function(resolve, reject) {
var inStorage = localStorage.hasOwnProperty(storageID) ? true : false;
if (inStorage) {
resolve(JSON.parse(localStorage.getItem(storageID)));
} else {
$.ajax({
type: 'POST',
url: 'AjaxFunctions.cfc?method='+fnName,
data: { 'recID': recID },
dataType: 'json'
// removed sync
}).done(function(obj){
if(obj.STATUS == "200"){
var storageData = $.isEmptyObject(obj.DATA) ? null : JSON.stringify(obj.DATA);
localStorage.setItem(storageID,storageData);
resolve(storageData);
}else{
$('#error').html(obj.MESSAGE);
// or reject here
reject(obj);
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
// or reject may be better here
reject({ 'jqXHR': jqXHR, 'textStatus': textSTatus, 'errorThrown': errorThrown });
});
}
});
}
getData('blah', 'storageId', 'recId')
.then(function(frmData) {
frmFeed(frmData);
});

Looping incorrect in for each loop in jquery

I am pushing na element into a javascript array while it is in for each loop. but the loop is not as expected.
Code:
//lets say the length is 1 for array id.If its in error it has to loop 2 times, but looping only once
$.each(id, function(i, itemI) {
$.ajax({
type: "GET",
url: url1.trim(),
dataType: "json",
success: function(data) {//do something
},
error: function(xhr,status){
//push an element into array here
id.push("something");
}
});
})
As per doc, $.each takes the length property of object/array initially and iterate until it meet the length.
You can do like this.
var id=0, req = makeReq(id), makecalltimeout;
function makeReq(id)
{
id = id || "something"; //If id is undefined during first call.
var data = {id:id};
$.ajax({
type: "GET",
url: "google.com",
dataType: "json",
data:data,
success: function(data) {//do something
},
error: function(xhr,status){
clearTimeout(makecalltimeout);
makecalltimeout = setTimeout(makeReq(Math.floor(Math.random()*10)),1000)
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here I will make the request when it fails recursively with a time interval of 1 second. Just to send random data in the params, I have used Math.floor(Math.random()*10. You can replace with what you like.

JQuery Ajax limiting deep recursion "too much recursion"

The idea is that I send lots of synchronous requests to an API to create a JSON that I will need later to do some clusterizations. This API gives me information about articles, review etc. from a site (scopus.com). First I send a request based on a query from which I get a JSON which contains information about some articles. These articles are cited by other articles. I have to get information about these ones too so I need recursion. The problem is that I get an error because of "too much recursion". It seems that the error appears when the recursion is over and the program has to go back to the "root"/the first call. So the program will look like a very deep tree.
Pure Javascript does have this limitation too? What can I do?
Also I have to do SYNCHRONOUS requests otherwise the JSON I will get will be a mess.
EDIT:
I tested the script on queries that need a small recursion such as a tree with 4-5 levels.
var result = '{"entry":[ ';
function query(){
var results = getNumberResults();
if(results>0)
{
var pages = Math.ceil(results/25);
var i;
for(i=0; i<pages; i++){
$.when($.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(data){
$.each( data['search-results']['entry'], function( i, item ) {
get info from json and save it in my variable
if(data['search-results']['entry'][i]['citedby-count'] > 0)
getCitedBy(data['search-results']['entry'][i]['eid']);
else{
result += '"children-id":[]},';
}
});
}
}));
}
}
result = result.slice(0,-1);
result += "]}";
}
function getCitedBy(eid){
var results = getCitedByNumberResults(eid);
if(results>0)
{
var pages = Math.ceil(results/25);
var i;
for(i=0; i<pages; i++){
$.when($.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(data){
$.each( data['search-results']['entry'], function( i, item ) {
get info from json and save it in my variable
if(data['search-results']['entry'][i]['citedby-count'] > 0)
getCitedBy(data['search-results']['entry'][i]['eid']);
else{
result += '"children-id":[]},';
}
});
}
}));
}
}
}
function getNumberResults(){
var innerResult;
$.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(output){
innerResult = output['search-results']['opensearch:totalResults'];
},
error: function (xhr, ajaxOptions, thrownError) {
innerResult = 0;
}
});
return innerResult;
}
function getCitedByNumberResults(eid){
var innerResult;
$.ajax({
url: url,
type: "GET",
async: false,
headers: {'Accept':'application/json'},
success: function(output){
innerResult = output['search-results']['opensearch:totalResults'];
},
error: function (xhr, ajaxOptions, thrownError) {
innerResult = 0;
}
});
return innerResult;
}
The problem was as trincot mentioned and I also thought so was that 2 or more articles are referencing each other making an infinite cycle. I fixed it by searching my string variable for the unique identifier. So if in my variable already exists and article with that identifier I will skip recursion for the current article.
So I tested my script again for relative short queries (few hundreds of articles returned) because there are queries with huge outputs (millions of articles). When I will search for big queries I could come upon string size limitations(browser specific) or even “too much recursion”. If so I will let you know.
Advice: if “too much recursion” error occurs in your ajax request search first for an infinite cycle because this is the most probable cause.

parameters in jquery ajax success

I am trying to find out what parameters I can pass to a jQuery ajax call.
What I am used to is writing something like:
$.ajax({
....
success: function(response) {
// put callback here
}
....
});
So here is my question:
Obviously the "response" variable I put in the success function just takes back whatever the server sends back from the ajax call. Is there any possible way to send multiple variables back? Something like:
...
success: function(response,httpStatus,whateverElse) {
}
...
Or, is there some other way to get the http response codes?
Thanks to whoever can answer this!
You can get the response's status code on the success' third parameter or complete's first parameter, something like this:
$.ajax({
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
Further to #Kokizzu you can check the jQuery API site to see what parameters are passed to the other functions http://api.jquery.com/jquery.ajax/.
Also another way that I find handy to work out what parameters are being passed when there are no docs available is:
success: function() {
console.log(arguments);
}
That will log to the console all of the arguments that were passed to that function when it was called.
You can also have the server send back json json_encode in php:
Php:
$array['status'] = 0;
$array['foo'] = 'bar';
json_encode($array);
Ajax:
$.ajax({
...
success: function (data) {
console.log(data);
}
});
Then obviously you could have your callback handle those variables.
$.ajax({
success: function(data, status, xhttp) {
console.log(status + ": " + data);
},
error: function(data, status, xhttp) {
console.log(status + ": " + data);
}
});

Categories