$.ajax fill changing objectname passed as function argument? - javascript

I am trying to parse several jSON files into several objects.
My approach looks as follows:
function download_datasave (target_object) {
// DOWNLOAD CALCULATION BACKUP
var filename, response
filename = target_object.name + '.json' ;
$.ajax
({
type: "POST",
url: datasave_hostname,
timeout : 3000 ,
data: {
action : "download", target : filename, data : ""
},
success: function (data) {
response = JSON.parse(data) ;
this[target_object] = response ; // doesn´t work , results is empty object
window[target_object] = response ; // doesn't work , results in empty object (as its the same)
aufloesung_history = response ; // does work, but how to solve this for more than one target_Object ??
},
error : function (data) { console.log(target_object.name + " : Download failed , ServerMessage : " + data); }
});
};
Please see the comments inside success. Stuff like "console.log(response)" are returning the correct Object(s) inside aufloesung_history for example.
Any thoughts?
derdigge
EDIT
This is how objects are created:
objects = [
"aufloesung", "aufloesung_history",
"grobsortierung", "grobsortierung_history",
"lcreinigung", "lcreinigung_history",
"fraktionierung", "fraktionierung_history",
"feinsortierung", "feinsortierung_history",
"eindickung", "eindickung_history"
];
function create_objects () {
for (var i = 0; i < objects.length; i++) {
window[objects[i]] = {};
window[objects[i]].name = objects[i] ;
}
};
EDIT2
I commented more of the console logs inside the code look:
function download_datasave (target_object, target) {
// DOWNLOAD CALCULATION BACKUP
var filename, response ;
console.log(this[aufloesung_history]) ; //undefinied
if (!(arguments[1])) {
filename = target_object.name + '.json' ;
} else {
filename = arguments[1] + '.json' ;
}
$.ajax
({
type: "POST",
url: datasave_hostname,
timeout : 3000 ,
data: {
action : "download", target : filename, data : ""
},
success: function (data) {
response = JSON.parse(data) ;
console.log(aufloesung_history) ; // empty object
this[target_object] = {} ;
console.log(aufloesung_history) ; // empty object
this[target_object] = response ;
console.log(aufloesung_history) ; // empty object
aufloesung_history = {} ;
console.log(aufloesung_history) ; // empty Object
aufloesung_history = response ;
console.log(aufloesung_history) ; // right contents inside object
console.log(this[aufloesung_history]) ; // right contents inside object
console.log(this[target_object]) ; // right contents inside object
},
error : function (data) { console.log(target_object.name + " : Download failed , ServerMessage : " + data); }
});
};
The data it self look like this inside an correct object:
correct object
The .json is created earlier from an correct object using JSON.stringify(target_object) in an upload function which looks similar.
Here is one json blob:
{"name":"aufloesung_history","0":{"start":1446043200,"stop":1446063000,"start_h":"28.10.2015, 15:40","stop_h":"28.10.2015, 21:10","duration":19800},"1":{"start":1446153600,"stop":1446157800,"start_h":"29.10.2015, 22:20","stop_h":"29.10.2015, 23:30","duration":4200},"2":{"start":1446170400,"stop":1446173400,"start_h":"30.10.2015, 3:00","stop_h":"30.10.2015, 3:50","duration":3000},"3":{"start":1446229200,"stop":1446267000,"start_h":"30.10.2015, 19:20","stop_h":"31.10.2015, 5:50","duration":37800},"4":{"start":1446270600,"stop":1446363000,"start_h":"31.10.2015, 6:50","stop_h":"01.11.2015, 8:30","duration":92400},"5":{"start":1446366600,"stop":1446409200,"start_h":"01.11.2015, 9:30","stop_h":"01.11.2015, 21:20","duration":42600},"6":{"start":1446415200,"stop":1446421800,"start_h":"01.11.2015, 23:00","stop_h":"02.11.2015, 0:50","duration":6600},"7":{"start":1446422400,"stop":1446435000,"start_h":"02.11.2015, 1:00","stop_h":"02.11.2015, 4:30","duration":12600},"8":{"start":1446436200,"stop":1446450600,"start_h":"02.11.2015, 4:50","stop_h":"02.11.2015, 8:50","duration":14400},"9":{"start":1446452400,"stop":1446456600,"start_h":"02.11.2015, 9:20","stop_h":"02.11.2015, 10:30","duration":4200},"10":{"start":1446457200,"stop":1446464400,"start_h":"02.11.2015, 10:40","stop_h":"02.11.2015, 12:40","duration":7200},"11":{"start":1446473400,"stop":1446481800,"start_h":"02.11.2015, 15:10","stop_h":"02.11.2015, 17:30","duration":8400},"12":{"start":1446488400,"stop":1446496800,"start_h":"02.11.2015, 19:20","stop_h":"02.11.2015, 21:40","duration":8400},"13":{"start":1446498600,"stop":1446513600,"start_h":"02.11.2015, 22:10","stop_h":"03.11.2015, 2:20","duration":15000}}
EDIT_3 (SOLUTION)
I found out!! It is because "this" is an Object inside ajax. jQuery and my Brain have caused that error. console.log(this) inside success of ajax pointed me in the right direction. I use the key name (aufloesung.name for example) to fill a new object. This only is taking place on the first load of the project so this would be ok. Please see comments inside the code.

Very unusual for me but i answer my own question. See commnet inside the ajax function.
function download_datasave (target_object) {
// DOWNLOAD CALCULATION BACKUP
var filename, versuch = 0 ;
filename = target_object.name + '.json' ;
$.ajax
({
type: "POST",
url: datasave_hostname,
timeout : 3000 ,
data: {
action : "download", target : filename, data : ""
},
success: function (data) {
window[target_object.name] = JSON.parse(data) ; // Works as ecxpected ;)
window[target_object] = JSON.parse(data) ; // does not work (dont know why). target_object is here an object with only one key in it (name)
this[target_object.name] = JSON.parse(data) ; // does not "work" because this isnt the DOMwindow Object
},
error : function (data) {
console.log("Versuch : " + versuch + " fehlgeschlagen. Versuche es erneut.") ;
}
});
};

Related

Localstorage setting through ajax data randomly gets undefined

I am setting items to localstorage using the below code. The issue I am getting is whenever I refresh the page some of the items are not set when I inspect the localstorage it shows as undefined, this is absolutely random and sometimes all items are set parfectly. How can I ensure that all the items are set without any undefined?
const catdata = [];
var catArr = JSON.parse(localStorage.getItem('cat'));
for (let i = 0; i < catArr.length; i++) {
const catid = catArr[i]['id'];
const catname = catArr[i]['name'];
$('#topitems').prepend('<div ><a class="topitems" href="'+catArr[i]['id']+'">'+catArr[i]['name']+'</a></div>');
(function(i) {
$.ajax( { url : "sales/item_search_cat?cat="+catid
, data : "GET"
// , async: "false",
, dataType : "json"
, success : function(data) {
catdata.push(data);
localStorage.setItem(catid,JSON.stringify(catdata[i]));
}
});
})(i);
}
The execution of the ajax requests are not sequentially executed, and sometimes your code is accessing an index that doesn't exist.
For example, one response arrives with index 2, the code pushes into the empty array at index 0, and catdata[i] is trying to get the index 2.
I think you have to call the ajax request using await or you can use the data directly:
localStorage.setItem(catid, JSON.stringify(data));
Possible solution (I didn't test it):
The execution is async, if you need to wait for the executions, you have to follow an async/await approach.
function callAjax(catid) {
$.ajax({
url: "sales/item_search_cat?cat=" + catid,
data: "GET",
dataType: "json",
success: function(data) {
localStorage.setItem(catid, JSON.stringify(data));
success(data);
}
});
}
let catArr = JSON.parse(localStorage.getItem('cat'));
catArr.forEach(function({id: catid, name: catname}) {
$('#topitems').prepend('<div ><a class="topitems" href="' + catid + '">' + catname + '</a></div>');
callAjax(catid);
});

How can I resolve XML Parsing Error: not well-formedLocation?

On load of my page I execute this function
function getConnection() {
$.ajax({
type: "GET",
url: "../webservice/anonymous_PS.asmx/Get",
data: { "PSname": "LISTE_CONNEXTION" },
async : false ,
success: function (response) {
var data = response.getElementsByTagName("NewDataSet")[0]
for (let i = 0; i < data.children.length; i++) {
var c1Nb = $(data.children[i]).find('c1').text()
var c2Nb = $(data.children[i]).find('c2').text()
var c1 = document.getElementById("cs" + c1Nb)
var c2 = document.getElementById("cs" + c2Nb)
var line = $("#l_" + c1Nb + "_" + c2Nb)
}
}
})
}
But when I do that I have this error on Firefox :
XML Parsing Error: not well-formed
Location:
Line Number 1, Column 131:
and on chrome sometimes I have this error :
devtools was disconnected from the page
How can I resolve my issue ?
Try parsing your response, you can use $.parseXML(response) if you want to parse your response to xml or $.parseHTML(response) if you want to parse your response to html.
Once the parsing is done then your getElementsByTagName("NewDataSet")[0] will work and you will not get any error.
The final code will look something like:
var parsedResponse = $.parseXML(response);
var data = parsedResponse.getElementsByTagName("NewDataSet")[0];

jquery length error when trying to find json file through Ajax within .Net core

I have been receiving this error within jquery:
Unhandled exception at line 422, column 4 in http://localhost:59307/lib/jquery/dist/jquery.js
0x800a138f - JavaScript runtime error: Unable to get property 'length' of undefined or null reference occurred
This is displayed within this jquery method:
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
Specifically the line:
length = elems.length
This is being caused by this Ajax statement which is trying to find a json file that is within a json folder on wwwroot:
function GetBucklingData() {
var returnData;
$.ajax({
url: "/json/BucklingData.json",
async: false
}).done(function (data) {
returnData = JSON.parse(data);
});
return returnData;
}
Here is an example grep statement from within a function:
var rods = $.grep(bucklingData, function (s) {
return (s.Bore == boreValue);
});
The statement is called like this:
var bucklingData = GetBucklingData();
PopulateBoreDropdown(bucklingData);
It seems that ajax isnt able to find the json file. The code is working outside of .net with a simple html page and a standalone folder so the json file appears to be fine.
Any ideas?
instead of using your function like this:
function GetBucklingData() {
var returnData;
$.ajax({
url: "/json/BucklingData.json",
async: false
}).done(function (data) {
returnData = JSON.parse(data);
});
return returnData;
}
var data = GetBucklingData();
change to an async logic:
function GetBucklingData(callback) {
var returnData;
$.ajax({
url: "/json/BucklingData.json",
async: false
}).done(function (data) {
callback(JSON.parse(data));
});
}
GetBucklingData(function(data) {
// here you have your data
console.log(data);
});

Cannot read property of undefined after JSON parse

I have done an ajax request in my code and it works good. After that I want to extract only the necessary info and re-post it to another script. Until now here is my code:
$.ajax({
type: "POST",
url: url,
data: {xhr_id: xhr_id},
success: function (jsondata) {
var product_data = [];
for (var i = 0; i <= 3; i++) {
//alert(jsondata.products[i].product_description.toSource());
product_data[i] = {};
product_data[i]["product" + i] = jsondata.products[i].product_description;
//alert(product_data[i]["product" + i].toSource());
}
},
dataType: "json"
});
The problem is that both the alerts work fine, displaying the information I want. However, I get an error message of "Uncaught TypeError: Cannot read property 'product_description' of undefined" which breaks the script and prevents me from doing anything else. What am I doing wrong, any ideas?
'product_description' of undefined" what it means is that your are trying to access property on undefined variable. That implies "jsondata.products[i]" resulted in undefined value which have occured due to index out of range.How many records are returned in jsondata 3 or 4,check and adjust the condition in for loop
The parameter in the success() function of $.ajax is a string. You have to put it through a parse function to make json. See your code below modified but not tested.
$.ajax({
type: "POST",
url: url,
data: {xhr_id: xhr_id},
success: function (jsondata) {
var oData;
try { oData=jQuery.parseJSON(jsondata) }
catch(err) {
alert("Problem parsing json string : " + jsondata)
return false
}
var product_data = [];
for (var i = 0; i <= 3; i++) {
//alert(oData.products[i].product_description.toSource());
product_data[i] = {};
product_data[i]["product" + i] = oData.products[i].product_description;
//alert(product_data[i]["product" + i].toSource());
}
},
dataType: "json"
});

Function as parameter in Jquery Ajax

Is it possible to put a function into a parameter for Jquery Ajax like below. dataType and data are given as functions. dataType returns a value of JSON if the returntype is JSON and text if isJson is false.
dataVal and dataVar are arrays containing the parameter names and values used to construct the data paramater. The result of the data: function would be a string as:
{dataVar[0]:dataVal[0],dataVar[1]:dataVal[1],.....,}
I'm getting an error when I try this, so, just wanted to know if this method was possible.
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
},
data: function () {
var dataString = '{';
for (var i = 0; i < dataVar.length; i++) {
dataString = dataString + dataVar[i] + ':' + dataVal[i] + ',';
}
console.log(dataString);
return dataString + '}';
},
success: function (res) {
dfd.resolve(res);
}
});
}
Edit
As per answers and comments, made the changes. The updated function is as below. This works:
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: isJson ? "JSON" : "text",
data: function () {
var dataString ="";
for (var i = 0; i < dataVar.length; i++) {
if (i == dataVar.length - 1) {
dataString = dataString + dataVar[i] + '=' + dataVal[i];
} else {
dataString = dataString + dataVar[i] + '=' + dataVal[i] + ',';
}
}
return dataString;
}(),
success: function (res) {
dfd.resolve(res);
}
});
}
And my original question is answered. But apparently, data is not getting accepted.
The return value of the data function is just treated as the parameter name and jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
So, my server is unable to pick up on the proper paramater name.
From the manual:
data
Type: PlainObject or String
So no.
Call the function. Use the return value.
data: function () { ... }();
// ^^ call the function
Not that way. But it will work with a little change:
(function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
})()
That should work. You just call the function immidiately after you created it. This way, dataType is a String and the script will work.
Same with data. Also use the (function(){})()-notation here
jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
No, your devtools display does. However, as you're data string does not contain a = sign, and you send the content as application/x-www-form-urlencoded, the whole body is interpreted as if it was a parameter name.
For sending JSON, you should:
use contentType: "application/json"
use data: JSON.stringify(_.object(dataVar, dataVal))1
to ensure valid JSON is sent with the correct header (and correctly recognised as such at the server).
1: _.object is the object function from Underscore.js which does exactly what you want, but you can use an IEFE as well:
JSON.stringify(function(p,v){var d={};for(var i=0;i<p.length;i++)d[p[i]]=v[i];return d;}(dataVar, dataVal))
You need to call the function with parenthesis like below:
function func1(){
//func1 code in here
}
function func2(func1){
//func2 code in here
//call func1 like this:
func1();
}
So, you can use like this:
data: function () {
//your stuff her
}(); // which mean you are having data()

Categories

Resources