“Undefined” error response from AJAX JQUERY call to XML file [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I want to open an XML file using jQuery, but I have an undefined error when I want to display the value of open outside the function.
Here is the code :
$(document).ready(function () {
var open ;
$.ajax({
type: "GET",
url: "../build/js/openTickets.xml",
dataType: "xml",
success: nv =function(xml) {
$(xml).find("mestickets").each(function () {
var open =$(this).find("nbopenTickets").text();
console.log(open); // it works
});
}
})
console.log(open);//undefined

remove var from
var open = $(this).find("nbopenTickets").text();
just do
open = $(this).find("nbopenTickets").text();
And then use call back function like below.
var open;
$(document).ready(function() {
$.ajax({
type: "GET",
url: "../build/js/openTickets.xml",
dataType: "xml",
success: nv = function(xml) {
$(xml).find("mestickets").each(function() {
var open = $(this).find("nbopenTickets").text();
console.log(open); // it works
ajexSuccessCallBack();
});
}
});
});
function ajexSuccessCallBack() {
console.log(open);
}

Related

JavaScript undefinded variable after refresh [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
Since I loaded a project to the web server I am getting this error message after the first refresh:
TypeError: oModel.responseJSON is undefined
Although the variable exists and AJAX succeed. The error refers to this line:
<body onload="displayEntries(oModel.responseJSON.results);">
I load before the body close tag the following JS:
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="js/user.js"></script>
JS runs in strict mode and in the "user.js" I have this code:
let oModel = $.ajax({
url: 'data.php',
dataType: 'json'
});
function displayEntries(entries) {
$("#div").empty();
let html = "";
jQuery.each(entries, function(i, entry) {
html = '<div id="cid-' + i + '" class="entry">' + entry.name + '</div>';
$("#div").append(txt);
});
}
When I enter "oModel.responseJSON.results" into the console, it is displayed correctly.
Ajax is asynchronous
Get rid of onload="displayEntries and just call the function in succcess callback of $.ajax
$.ajax({
url: 'data.php',
dataType: 'json'
}).then(displayEntries);
This happens because you're trying to access value of a variable before the AJAX call is over.
Call the displayEntries() function after the AJAX call is over like so:
$.ajax({
url: 'data.php',
dataType: 'json'
}).done(function(data) {
displayEntries(data)
});

Set tooltip text with jQuery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have the following code:
var text = "";
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: DataReview.BASE + "/Encryption/FetchLatestEditBy",
data: JSON.stringify({
"ExtendedReport_id": dataRow["ExtendedReport_id"],
"Report_id": dataRow["Report_id"]
}),
success: function (data) {
text = data.ResultData;
},
error: function (data) {
console.log(data);
}
});
setTimeout(function () {
console.log(text); //This displays the value
$(this).attr('data-toggle', 'tooltip');
$(this).attr('title', text);
}, 1000);
As you can see, I'm trying to set the tooltip-text in the setTimeout-function. But It will not show up. When I replace text-variable with some dummy-text, it works. But the variable value does not work.
When you use timeout, the this will be in window scope and not with the element. So you are actually adding attributes to the window.
Secondly there is no guarantee that ajax call will be done or you might be waiting too long after the Ajax call by using a timeout. You should be setting the attributes in the success callback of the Ajax call.
Thirdly you probably need to get trigger the tooltip manually so it gets the updated data.
var elem = $(this);
$.ajax({
/* your code here, removed to simplify answer*/
success: function (data) {
elem.attr('data-toggle', 'tooltip');
elem.attr('title', text);
elem.tooltip().tooltip("show"); // might need to change this line based on actual library
}
});
I am assuming your ajax success is taking more time and thus the setTimeout function is called first before the "text" variable value is set in the success function. Try calling a function in onsuccess ajax function.
var text = "";
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: DataReview.BASE + "/Encryption/FetchLatestEditBy",
data: JSON.stringify({
"ExtendedReport_id": dataRow["ExtendedReport_id"],
"Report_id": dataRow["Report_id"]
}),
success: function (data) {
text = data.ResultData;
settooltiptext();
},
error: function (data) {
console.log(data);
}
});
function settooltiptext()
{
console.log(text); //This displays the value
$(this).attr('data-toggle', 'tooltip');
$(this).attr('title', text);
}

Issues calling a method after making an ajax call [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
Once a checkbox is ticked on a form, I am calling a function that performs certain checks and enables a previously disabled button.
My js code has the following:
$('#default_address').change ->
id = $('#default_address').val()
if(this.checked)
$.ajax({
url: '/shipments/' + id + '/get_address',
dataType: "JSON",
success: (data) ->
$('#billing_address_address_line1').val(data[0])
$('#billing_address_address_line2').val(data[1])
$('#billing_address_phone_number').val(data[2])
}).done
checkPlaceOrderValidity()
The checkPlaceOrderValidity() method is as shown below:
#checkPlaceOrderValidity = ->
// some code
else
place_order_btn.attr 'disabled', false
place_order_btn.removeClass 'disabled'
If I add an alert just before calling the checkPlaceOrderValidity() method, it works fine(which I found really strange). I m unable to find the cause even after debugging my code.
Try this,
$.ajax({
url: '/shipments/' + id + '/get_address',
dataType: "JSON",
success: (data) - >
$('#billing_address_address_line1').val(data[0])
$('#billing_address_address_line2').val(data[1])
$('#billing_address_phone_number').val(data[2])
}).done(checkPlaceOrderValidity);

Trying to use a callback with .ajax call to assign value to a variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm trying to use a .ajax call, to assign the value from an xml document, to a variable in javascript. I can't quite figure out how to use a callback, I know this topic is well discussed on forums, but I haven't been able to find an example out there that does what I am trying to do. The example below makes a call to Google Maps, and gets a string "Central Standard Time" back. I can use .ajax calls to move the text to a div. But I can't figure out how to assign this to a variable, my_zone, and move that value to a div.
Anyone able to help me out? Please? If someone can do a rewrite of the code here, thanks....
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='//code.jquery.com/jquery-2.0.2.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
//this works great, we get the value and it goes to the 'zzz' div, asynchronously
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/timezone/xml",
data: {
location: '35.129186,-89.970787',
timestamp: '1389006000',
sensor: 'false'
},
dataType: "xml",
success: function(xml) {
var val = $(xml).find('time_zone_name').text();
$( "#zzz" ).empty().append( val ); //want to return val
}
});
//this is what I am trying to do, get the return'd value, and put it into a variable
var my_zone = getZone(); //just want to get the value into a variable
$("#xxx").empty().append(my_zone); //do something with it, maybe display it
function getZone() {
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/timezone/xml",
data: {
location: '35.129186,-89.970787',
timestamp: '1389006000',
sensor: 'false'
},
dataType: "xml",
success: function(xml) {
var val = $(xml).find('time_zone_name').text();
console.log(val);
return val; //needs to be part of a Callback
}
});
}
///////////
});
</script>
</head>
<body>
<div id="xxx">some output here....</div>
<div id="zzz">some output here....</div>
</body>
</html>
You can't do that, instead you can pass a callback function to getZone() which will get called once the request is completed with the desired parameter
//pass a callback function which will get called when the ajax request is completed
getZone(function (my_zone) {
$("#xxx").empty().append(my_zone); //do something with it, maybe display it
});
function getZone(callback) {
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/timezone/xml",
data: {
location: '35.129186,-89.970787',
timestamp: '1389006000',
sensor: 'false'
},
dataType: "xml",
success: function (xml) {
var val = $(xml).find('time_zone_name').text();
console.log(val);
callback(val); //call the callback with the value
}
});
}

Returning values from XML file with $.ajax()

Just trying to read an XML file using a Jquery ajax function and then using a callback function, store the text in the URLS var
It isn't working, so here is the code, any tips?
$(document).ready(function(){
var URLS = []
function get_xml(){
var XML_FILE = "file:///home/lwm/repos/get-hyped/resources/data.xml"
$.ajax({
type: "GET",
url: XML_FILE,
dataType: "xml",
success: function(data){
xml_to_data(data);
},
error: function(){
console.log("Can't read the XML file!");
}
});
}
function xml_to_data(data){
// get all urls
$(data).find('links video').each(function() {
URLS = $(this).find('url').text().split(" ");
});
}
get_xml();
console.log(URLS.length);

Categories

Resources