-2

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
Atomzwieback
  • 585
  • 6
  • 18
  • 1
    Have a read up on "variable scope" - the variable only exists inside the function. – droopsnoot Jul 21 '20 at 09:56
  • 1
    the variable `open` in the success callback is not the same as the variable `open` defined in line 2. Remove the `var` keyword in `var open =$(this)...` so that you're not initialized a new variable `open` which is limited to the scope of the callback. – dikuw Jul 21 '20 at 09:58

1 Answers1

0

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);
}
   
Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
  • Thanks , I have removed var , but I have again undefined in my console – Djamel LD Jul 21 '20 at 13:04
  • your console is printing before response receive from ajax call. Try to use call back function from ajax success and then print. Find my edited answer. – Vivek Jain Jul 21 '20 at 13:30