0

clearly i must have overlooked something. here is my script, and below that is the data.

 $("#kenteken").blur(function(){

  var sRegistrationNr = $(this).val();
  var sChassisNumber = false;

  $.ajax({
   type: "GET",
   url: "/activeContent/warrantyClaim/ajax-xml-response.php",
   data: "return=auto&kenteken="+sRegistrationNr,
   dataType: "xml",
   success: function(xml) {
    $(xml).find("xmlresponse").each(function(){
     $(this).find("data").each(function(){
      var sChassisNumber = $(this).find("chassisnummer").text();
     });
    });
   }
  });

  alert(sChassisNumber);

 });

here is the data from the xml file (responding fine)

- <xmlresponse>
  <result>GPZB89</result> 
- <data>
  <kenteken>GPZB89</kenteken> 
- <chassisnummer>
- <![CDATA[ KNEFA2253N5000176
  ]]> 
  </chassisnummer>
  </data>
  </xmlresponse>

Where does this go wrong?

2 Answers 2

1
$.ajax({
    ...
    success: function(xml) {
        var sChassisNumber= $(this).find("chassisnummer").text();
    }
});
alert(sChassisNumber);

You are reading the results of the callback function before the AJAX request completes and calls the function back.

The ‘A’ in AJAX stands for asynchronous. The operation is still ongoing when the script gets to the line following the $.ajax() call. That's why you have to pass a callback function in to execute when it's finished.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! that got me going. putting the alert inside the success function worked. But is there a way to get the data from the success callback function outside that ajax call? (just curious) or should everything be handled within the success calback? It would be great to have a function outside the call that could handle the data coming back from the success call
Everything has to be handled in or after the callback, sure. You can set a global variable in the callback that can be read later if you want. Or if you just want to avoid having the handling code inline, you can can define a top-level function chassisFound() { ... } and just pass that as success: chassisFound. Incidentally, avoid constructing key=value query strings manually without escaping. You can use 'kenteken='+encodeURIComponent(sRegistrationNr) or, probably better, let jQuery do it for you: data: {'return': 'auto', 'kenteken': sRegistrationNr}.
1

Install firebug and see what is being returned in detail:

console.log(xml);
console.log($(xml)); //this will be clickable in console.

click and explore the object. maybe the $(xml) is already the xmlresponse node and You try to find another in it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.