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

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];

Related

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

Set Value from JSON via AJAX

I'm using Github Gists for a web playground I'm making as a side project. I load two json files into the editor. 1 handles all the libraries (jquery, bootstrap, etc:) and another for the users settings (fontsize, version, etc:)
So anyway I have this JSON named settings
var settings = gistdata.data.files["settings.json"].content
var jsonSets = JSON.parse(settings)
I parse and attempted to grab an object from the JSON and set it as a value of a input textbox.
Now console.log(jsonSets.siteTitle) works perfectly fine
but when I try to change the input dynamically...
$("[data-action=sitetitle]").val(jsonSets.siteTitle).trigger("change")
The problem is it's not actually applying the value!
The only way I've been able to successfully apply the value is...
setTimeout(function() {
$("[data-action=sitetitle]").val(jsonSets.siteTitle).trigger("change")
}, 5000)
Which is ridiculously slow.
Does anyone know why it's not applying the value?
in addition.
How can I solve this problem?
var hash = window.location.hash.substring(1)
if (window.location.hash) {
function loadgist(gistid) {
$.ajax({
url: "https://api.github.com/gists/" + gistid,
type: "GET",
dataType: "jsonp"
}).success(function(gistdata) {
var libraries = gistdata.data.files["libraries.json"].content
var settings = gistdata.data.files["settings.json"].content
var jsonLibs = JSON.parse(libraries)
var jsonSets = JSON.parse(settings)
// Return libraries from json
$.each(jsonLibs, function(name, value) {
$(".ldd-submenu #" + name).prop("checked", value)
})
// Return font settings from json
var siteTitle = jsonSets.siteTitle
var WeaveVersion = jsonSets.version
var editorFontSize = jsonSets.editorFontSize
var WeaveDesc = jsonSets.description
var WeaveAuthor = jsonSets.author
$("[data-action=sitetitle]").val(siteTitle).trigger("change")
$("[data-value=version]").val(WeaveVersion).trigger("change")
$("[data-editor=fontSize]").val(editorFontSize).trigger("change")
$("[data-action=sitedesc]").val(WeaveDesc).trigger("change")
$("[data-action=siteauthor]").val(WeaveAuthor).trigger("change")
}).error(function(e) {
// ajax error
console.warn("Error: Could not load weave!", e)
})
}
loadgist(hash)
} else {
// No hash found
}
My problem was actually related to localStorage.
I cleared it localStorage.clear(); ran the ajax function after and it solved the problem.
var hash = window.location.hash.substring(1)
if (window.location.hash) {
localStorage.clear()
function loadgist(gistid) {
$.ajax({
url: "https://api.github.com/gists/" + gistid,
type: "GET",
dataType: "jsonp",
jsonp: "callback"
}).success(function(gistdata) {
var htmlVal = gistdata.data.files["index.html"].content
var cssVal = gistdata.data.files["index.css"].content
var jsVal = gistdata.data.files["index.js"].content
var mdVal = gistdata.data.files["README.md"].content
var settings = gistdata.data.files["settings.json"].content
var libraries = gistdata.data.files["libraries.json"].content
var jsonSets = JSON.parse(settings)
var jsonLibs = JSON.parse(libraries)
// Return font settings from json
var siteTitle = jsonSets.siteTitle
var WeaveVersion = jsonSets.version
var editorFontSize = jsonSets.editorFontSize
var WeaveDesc = jsonSets.description
var WeaveAuthor = jsonSets.author
$("[data-action=sitetitle]").val(siteTitle)
$("[data-value=version]").val(WeaveVersion)
$("[data-editor=fontSize]").val(editorFontSize)
$("[data-action=sitedesc]").val(WeaveDesc)
$("[data-action=siteauthor]").val(WeaveAuthor)
storeValues()
// Return settings from the json
$(".metaboxes input.heading").trigger("keyup")
// Return libraries from json
$.each(jsonLibs, function(name, value) {
$(".ldd-submenu #" + name).prop("checked", value).trigger("keyup")
})
// Set checked libraries into preview
$("#jquery").trigger("keyup")
// Return the editor's values
mdEditor.setValue(mdVal)
htmlEditor.setValue(htmlVal)
cssEditor.setValue(cssVal)
jsEditor.setValue(jsVal)
}).error(function(e) {
// ajax error
console.warn("Error: Could not load weave!", e)
})
}
loadgist(hash)
} else {
// No hash found
}

using javascript to load json data from google maps

So, this is the code I have, console.log gives me the right value, but the function doesn't return the value, even if the return is inside the timeout. I must be doing something wrong.
function countyfinder(address){
var rr =$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + address.replace(" ", "%20")).done(function(data) {
var county = data.results[0].address_components[3].short_name;
//return county;//data is the JSON string
});return rr;};
function calculatetax(address, price){
var j = countyfinder(address);
setTimeout(function(){var k = j["responseJSON"]['results'][0]['address_components'][3]['short_name'];
console.log(k);//return k won't work in here either
}, 1000); return k
};
this is what I ended up with:
var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
function getCounty(address) {
var country;
var baseApiUrl = "https://maps.googleapis.com/maps/api/geocode/json";
var query = "?address=" + encodeURIComponent(address);
var queryUrl = baseApiUrl + query;
$.ajax({
url: queryUrl,
async: false,
dataType: 'json',
success: function(data) {
county = gmapsExtractByType(data, "administrative_area_level_2 political");
}
});
return countr.long_name;
}
function gmapsExtractByType(json, type) {
return json.results[0].address_components.filter(function(element) {
return element.types.join(" ") === type;
})[0];
}
console.log( getCounty("100 wacko lane ohio") );
I had to use a synchronous request by changing some settings in the ajax request. The drawback of this is that the browser will be locked up until you get a request response, which can be bad on a slow connection or a connection with an unreliable server. With google, most of the time, I don't think that will happen.

$.ajax fill changing objectname passed as function argument?

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

Ajax data collection - Empty Set?

I'm doing an ajax call to a php query that I know returns results. However, I'm getting an empty set ("[]"). Here's my code:
var source = [];
// Get the user data to build the sources
function getUsers() {
var data = $.ajax( {
url: '/s/calendar_userdata.php',
method: 'GET',
dataType: 'json',
success: function(userData) {
console.log(userData); // returns []
var len = userData.length;
for(var i = 0; i < len; i++)
{
source[i] = '/s/events.php?e=' + userData[i]; // error "Uncaught TypeError: Cannot set property '0' of undefined"
}
return source;
}
});
}
I've done a lot of reading of StackOverflow and several tutorials on ajax calls and callbacks specifically. However, I'm stuck. Can someone show me what I've got wrong? I've been on this topic for the past 10 hours and am no longer making progress. Thanks.
Are you sure that's returning a body?
Maybe you could first do a
curl -i {host}:/s/calendar_userdata.php
and post it as an edit.
Also, you could also get the status in the ajax call so you can assure you are not throwing useful information such as a 404 (NOT FOUND).
function getUsers() {
var data = $.ajax( {
url: '/s/calendar_userdata.php',
method: 'GET',
success: function(userData, status) {
console.log('userData: ' + userData + ', status:' + status); // returns []
var len = userData.length;
for(var i = 0; i < len; i++)
{
source[i] = '/s/events.php?e=' + userData[i]; // error "Uncaught TypeError: Cannot set property '0' of undefined"
}
return source;
}
});

Categories

Resources