0

I want to open xml file with jquery , but when I want to display the value of open outside the function , I have an undefined error .

Here 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 () {
            open=($(this).find("nbopenTickets").text());
            console.log(open);//It works
            
        });
      }

    })

    console.log(open);//undefined
  • This is how AJAX work. Javascript (or JQuery) calls the URL and continues with processing the rest of the code. Few moments later the result comes back from server and the success function is called. You are reading the value outside success when it is not yet returned. Read it inside success. – Nawed Khan Jul 21 '20 at 14:11
  • Does this answer your question? [How to return an Ajax result using async/await?](https://stackoverflow.com/questions/48506445/how-to-return-an-ajax-result-using-async-await) – Reyno Jul 21 '20 at 14:35

1 Answers1

0

That is what Ajax does, the processed data will be handled in the success handler.
What you can do if you really want to is create another function where you can process your data.

    $(document).ready(function () {
        var open = null;
        $.ajax({
            type: "GET",
            url: "../build/js/openTickets.xml",
            dataType: "xml",
            success: nv = function (xml) {
                $(xml).find("mestickets").each(function () {
                    open = $(this).find("nbopenTickets").text();

                    openData(open);

                });
            }

        });

        function openData(open) {
            console.log(open);
        }
    });
Thrallix
  • 699
  • 5
  • 20