In my method feedContactCategorySelection, i would like to wait the assignContactCategoryToLocal call to be finished before continuing to run the rest of the code
feedContactCategorySelection();
function feedContactCategorySelection(){
assignContactCategoryToLocal();
var category = sessionStorage.getItem("category");
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
//....
}
}
function assignContactCategoryToLocal() {
var category = sessionStorage.getItem("category");
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
}
});
}
You can pass a callback function to the assignContactCategoryToLocal() that way you can continue running the code only when the ajax is done. Something like this:
feedContactCategorySelection();
function feedContactCategorySelection() {
// Do anything here before running the ajax
// For instance, get category and pass it to the assignContact...
var category = sessionStorage.getItem("category");
...
assignContactCategoryToLocal(category, myCallbackFunction);
}
function myCallbackFunction(category) {
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
}
function assignContactCategoryToLocal(category, callback) {
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
// Now that it is done and successful, run the rest...
callback(category);
}
});
}
}
For sake of example, you can get the category once and then pass it along the functions, maybe that helps understand how they are connected.
EDIT:
To address the issue with the category being null, here is a revised version.
feedContactCategorySelection();
function feedContactCategorySelection() {
// Do anything here before running the ajax
// For instance, get category and pass it to the assignContact...
var category = sessionStorage.getItem("category");
...
// Move the if statement here so it checks the condition earlier.
if (category === null) {
assignContactCategoryToLocal(category, myCallbackFunction);
} else {
myCallbackFunction(category);
}
}
function myCallbackFunction(category) {
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
}
function assignContactCategoryToLocal(category, callback) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
// Now that it is done and successful, run the rest...
callback(category);
}
});
}
Consider using Promise in this case.
Pseudocode as below:
feedContactCategorySelection();
function feedContactCategorySelection(){
assignContactCategoryToLocal().then(function(){
var category = sessionStorage.getItem("category");
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
....
}
})
}
function assignContactCategoryToLocal() {
return new Promise(function(resolve, reject){
var category = sessionStorage.getItem("category");
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
resolve()
}
failed:{reject(reason)}
});
})
}
Please check i have added async: false, to wait until get the ajax response.
feedContactCategorySelection();
function feedContactCategorySelection(){
assignContactCategoryToLocal();
var category = sessionStorage.getItem("category");
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
//....
}
}
function assignContactCategoryToLocal() {
var category = sessionStorage.getItem("category");
if (category == null) {
$.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET',
async: false,
success: function (json) {
sessionStorage.setItem("category", JSON.stringify(json));
}
});
}
function feedContactCategorySelection() {
// `data` : `sessionStorage.getItem("category")` or response from `$.ajax()`
assignContactCategoryToLocal().then(function(data) {
// if `category` set , return `category` , else set `category`
var category = sessionStorage.getItem("category") != null
? sessionStorage.getItem("category")
: sessionStorage.setItem("category", JSON.stringify(data));
category = JSON.parse(category);
for (var i = 0; category["data"].length; i++) {
//....
}
// handle errors, if any, from `$.ajax()` call
}, function err(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
})
}
function assignContactCategoryToLocal() {
var category = sessionStorage.getItem("category");
// if `category` is `null` , return `$.ajax()` response
return category == null
? $.ajax({
url: 'http://localhost:8080/rest/contact/category',
type: 'GET'
})
: $.when(category)
}
Related
I am trying to append array elements to the list using below code:
function GetList() {
let list = [];
$.ajax({
url: '../Lookup/GetList',
type: 'GET',
cache: true,
dataType: "json",
success: function (response) {
debugger;
list = response;
//for (var data in response) {
// list = { value: data, rest: list };
//}
//for (let i = response.length - 1; i >= 0; i--) {
// list = { value: array[i], rest: list };
//}
//for (let i = response.length - 1; i >= 0; i--) {
// list.push(response[i]);
//}
}
});
return list;
}
I have attached the screenshot of array data format.
I need in the below list format:
var list= [
{
"id": "1",
"LookupMasterName": " Source1",
"Description": "xxx",
"Enabled Flag":"Y"
},
{
"id": "2",
"LookupMasterName": " Source2",
"Description": "yyy",
"Enabled Flag": "Y"
}
];
Above code doesn't work. It returns empty list. Can you help?
It's returning an empty list because this line return list; is executed before Ajax is completed. A solution to fix it is wrapping your Ajax request into a Promise:
Example:
function GetList() {
let list = [];
return new Promise((resolve) => {
$.ajax({
url: "../Lookup/GetList",
type: "GET",
cache: true,
dataType: "json",
success: function (response) {
list = response;
resolve(list);
},
});
});
}
Then calling GetList:
GetList().then(list => /* do whatever you need */)
I need to check the status of BranchName every 10 seconds
Need to get "BranchName, status" value,But the result is not smooth.
I'm not familiar with parsing json of javascript.
How can i do?
Thank you!
get "BranchName, status" value, like this:
BranchNameA
1
BranchNameB
1
The get request returns value(json) like this:
[
{
"BranchNameA":{
"branchNumber":"X20001",
"companyId":"64400001",
"shopName":"BOLLYTEST",
"status":"1",
"statusText":"Online",
"statusMessage":"bbbb",
"errorMessage":"",
"connectTime":"xxxxxx",
"disconnectTime":"",
"CheckModel":{
}
}
},
{
"BranchNameB":{
"branchNumber":"X20001",
"companyId":"64400001",
"shopName":"BOLLYTEST",
"status":"1",
"statusText":"Online",
"statusMessage":"bbb",
"errorMessage":"",
"connectTime":"xxxxxx",
"disconnectTime":"",
"CheckModel":{
}
}
}
]
code:
<script>
getApi()
function getApi() {
setTimeout(getApi, 10 * 1000);
$.ajax({
url: "(api)",
type: "Get",
dataType: "json",
success: function (data) {
console.log(JSON.stringify(data));
let user = JSON.parse(data);
var jsonData = JSON.parse(data);
for (var i = 0; i < jsonData.fields.length; i++) {
var Status= jsonData.fields[i];
console.log(counter.status);
}
}
})
}
</script>
This will solve:
success: function (data) {
var jsonData = apiData;
console.log(jsonData);
for (i in jsonData)
{
data = jsonData[i];
keys = Object.keys(data);
console.log(keys[0]);
console.log(data[keys[0]].status);
}
}
I am getting an error on ajax call - "No handler found for "undefined". Attached the screenshot in the following. I'm running this on react-redux application.
Had any of you guys faced the same issue? Any help? The code is given in the following:
export function updateBrandAdmin(data) {
console.log(data);
var brand_admin_data = data;
var updateUrl = `<url for ajax request>`;
return function(dispatch) {
var brandAdminData = new FormData();
//append description
if(data.description && (data.description != "")) {
brandAdminData.append("description", brand_admin_data.description);
}
//append banner name
if(brand_admin_data.brand_name && (brand_admin_data.brand_name != "")) {
brandAdminData.append("name", brand_admin_data.brand_name);
}
//append products
if (brand_admin_data.productids && brand_admin_data.productids.length > 0) {
for(var j=0; j < brand_admin_data.productids.length; j++) {
brandAdminData.append("products_ids[]", brand_admin_data.productids[j]);
}
}
//append logo
//The issue was here when I wasn't giving this check
if (brand_admin_data.logoAttribute.files[0]) {
brandAdminData.append("logo", brand_admin_data.logoAttribute.files[0]);
}
//append banner attributes
if (brand_admin_data.banners_attributes) {
// formData.append("video_attributes[]", null);
// if(brand_admin_data.banners_attributes.length > 0) {
// for(var i=0; i < brand_admin_data.banners_attributes.length; i++) {
brandAdminData.append("banners_attributes[]", brand_admin_data.banners_attributes[0].files[0]);
// }
// }
}
// console.log(data);
// console.log(updateUrl);
$.ajax({
type: "PUT",
url: updateUrl,
data: brandAdminData,
headers: getToken(),
success: function(resp, status) {
console.log(resp);
},
async: true,
cache: false,
contentType: false,
processData: false,
timeout: 60000
});
}
}
I have this code :
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
});
I want if data == 0 need to make another call on app_auction_end after 10 sec. Can you help me please ? Thx in advance and sorry for my english
Give the operation a named function:
var someFunction = function () {
$.ajax({
//...
});
};
Which you would then use for your .on() call:
.on('finish.countdown', someFunction)
And in the success handler, set a timeout for that function:
if (data == 0) {
setTimeout(someFunction, i_timer);
}
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
//do our initial call otherwise it will never get called.
onEndAuction();
});
i have:
function load_data(data) {
var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();
$.ajax({
url: '/dostup/data_json.php',
method: 'GET',
async: true,
data: {
epsg: data
},
dataType: 'json',
error: function(jqXHR, status, error) {
console.log('ошибка получения данных: '+data);
},
success: function(data2) {
window[data] = data2;
window[data+"_layer"].clearLayers();
window[data+"_layer"].addData(eval(data));
myMask.hide();
}
});
}
And myMask hidden before window[data] loading on site(client).
I try set async: false and myMask not show(i try and beforeSend too).
P.S. i have:
function search_handler(val) {
search_list=[];
for (var t = 0; t < layer_array.length; t++) { //>
if (window[layer_array[t]] != undefined && !eval(layer_array[t]).features) load_data(layer_array[t]);
if (window[layer_array[t]] != undefined && eval(layer_array[t]).features) {
for (var i = 0; i < eval(layer_array[t]).features.length; i++) { //>
search_list.push(eval(layer_array[t]).features[i]);
}
}
}
....more script
}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
You need to use ajaxStart and ajaxStop like that:
$(document)
.ajaxStart(function () {
myMask.show();
})
.ajaxStop(function () {
myMask.hide();
});