0

This AJAX call is returning "undefined". I'm not sure what I'm doing wrong and why this isn't working:

var xmlfile;

 $.ajax({
    type: 'GET',
    url: 'sample.xml',
    dataType: 'xml',
    success: function(data){
    xmlfile = $(data);}
    });

console.log(xmlfile);
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
ram_c
  • 87
  • 2
  • 11

3 Answers3

3

This is likely to be a timing issue since you're referring to the xmlFile variable before the call returns. Instead you have to move the reference into the success callback.

 $.ajax({
    type: 'GET',
    url: 'sample.xml',
    dataType: 'xml',
    success: function(data){
    xmlfile = data;
    console.log(xmlfile); 
    }
    });

Try the above.

TGH
  • 38,769
  • 12
  • 102
  • 135
1

you can do this by

$.ajax({
    type: 'GET',
    url: 'sample.xml',
    dataType: 'xml',
    success: function(data){
    xmlfile =  data ;}
 });

or set the async : false,

you can detect error/problem by debugging so you can see where are you doing wrong

like see alert(data) it it does it mean you are getting successful response by ajax call

mac mohan
  • 165
  • 1
  • 9
0
var xmlfile;

 $.ajax({
    type: 'GET',
    url: 'sample.xml',
    dataType: 'xml',
    async : false,
    success: function(data){
    xmlfile = $(data);}
    });

console.log(xmlfile);

try This, you are getting undefined due to asyn call, your log executes before you got result from server

muneebShabbir
  • 2,500
  • 4
  • 29
  • 46