Ajax request showing error - javascript

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
});
}
}

Related

Infinite loop to output all values from an array

From the function django I return JSON to JS
paymentparking = paidparking.objects.filter(expirationdate__range=(startdate, enddate)).values('expirationdate','price')
return JsonResponse({'result': list(paymentparking)})
Here I need to get all the expirationdate values. How can this be done and how can the cycle be organized?
$.ajax({
type: "POST",
url: "statistics",
data: {
'startdate': finalDateStrStart,'enddate': finalDateStrEnd,
},
dataType: "json",
cache: false,
success:function (data) {
for (let i = 0; i < 100; i++)
{
console.log(data.result[i].expirationdate)
}
}
});
You could maybe do something like this:
success: function (data) {
if(data.result) {
for (let i = 0; i < data.result.length; i++) {
console.log(data.result[i].expirationdate)
}
}
}
Use Array.map() to iterate over elements and return an array of expirationdate.
success: function (data) {
data?.result && data.result.map(obj => console.log(obj.expirationdate));
}

Split html table values using java script

I am working in rails application and From UI I need to select around 500 parameters(comma separated) in a table for execution. I am sending those selected data in AJAX call. I am unable to post huge string values hence I am planning to get the length of selected parameters if selected parameters count exceeds length 200. I need to split two or three batches and send for execution. How to implement this?
if (Device1) {
parameter_name = $('#parameters_object').val();
var getParams=parameter_name.split(',');
paramLen=getParams.length;
alert(paramLen);
if (paramLen > 200){
}
//m is a selected mac address length count
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "POST",
url: "get_object",
dataType: "json",
data: {
parameter: getParams,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
}
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
You can split your array into chunks of 200 items, and then loop over the chunk array and do your AJAX call.
const chunkSize = 200
const chunkParams = getParams.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index/chunkSize)
if(!resultArray[chunkIndex]) {
resultArray[chunkIndex] = [] // start a new chunk
}
resultArray[chunkIndex].push(item)
return resultArray
}, [])
values.forEach(macAddress =>
chunkParams.forEach(chunkParam =>
$.ajax({
method: "POST",
url: "get_object",
dataType: "json",
data: {
parameter: chunkParam,
mac: macAddress,
....
},
...
});
)
)
You can directly do your AJAX call in the reduce loop, more performant but less readable.
You need to split params to batches and make ajax call for each batch. Try following:
if (Device1) {
parameter_name = $('#parameters_object').val();
var getParams=parameter_name.split(',');
paramLen=getParams.length;
alert(paramLen)
var paramsBatches = [];
var batchSize = 200;
for (i = 0, j = getParams.length; i < j; i += batchSize) {
paramsBatches.push(getParams.slice(i, i + batchSize));
}
//m is a selected mac address length count
for (var i = 0; i < m; i++) {
paramsBatches.forEach((batch, index) => {
var macAdd = values[i];
$.ajax({
method: "POST",
url: "get_object",
dataType: "json",
data: {
parameter: batch,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
}
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
}
}
}

get the notification length depends on ReadFlag

JS:
function getJSON(){
$.ajax({
url: "getgroupednotification.json",
type: "GET",
crossDomain: true,
success:function(res){
$.each(res,function(index, value){
//console.log(res);
//console.log(value);
$.each(value.Notifications, function(index_, value_){
if(value.Source == 'CIRIS'){
var i = value.Notifications.length;
if(value_.ReadFlag != 1){
}
}
});
});
});
i want to get the notification.length if ReadFlag == 0. Im using Source == CIRIS for this example.
This is the link to my JSON
https://api.myjson.com/bins/navph
You could use something like this:
function getJSON() {
$.ajax({
url: "https://api.myjson.com/bins/navph",
type: "GET",
crossDomain: true,
success: function(res) {
var lens = res.filter(function(item) {
// filter by source
return item.Source === 'CIRIS';
}).map(function(item) {
// get only Notifications
return item.Notifications;
}).map(function(notification){
// get lengths of notifications which have at least 1 RedFlag not 0
return (notification.filter(function(item){
return item.RedFlag !== 0;
}).length)
})
console.log(lens[0]);
}
})
}
getJSON();

function call another without waiting to finish

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)
}

How show loading window in async query?(or may be sync)

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();
});

Categories