javascript – how to query for xml attribute after select change – Education Career Blog

I have successfully loaded the xml and everything works fine if the success function runs right after loading the XML. But I wanted to get the value of the attribute after the onChange event takes place on the select box (which changes tmpproj value).
When I try to access the success function checkimgs() it says $(xml) is not defined.

This is probably pretty basic to solve but I am too blind to see it.

var tmpproj = '02064';
var fileurl = 'menu.xml';

$.ajax({
    url: fileurl,
    type: "GET",
    dataType: "xml",
    success: checkimgs,
    error: error_func
 });


// Callback results if error
function error_func(result) {
    alert(result.responseText);
}

// Callback if Success
function checkimgs(xml) { 
    $(xml).find("itemprojn="+tmpproj+"").each(function()
    {           
        alert ($(this).attr("projn"));
    });
} 

The XML looks like this:

<menu nome="stuff" tag="ldol">
  <item projn="02064" nome="asdf" msg="ggg">
   <foto nome=""/>          
  </item>
  <item projn="06204" nome="xxx" msg="xxxd" />
</menu>

Calls to the onchange event:

$('#selctbox').change(function () {
    tmpproj = $('#projlist option:selected').val();
    checkimgs();
})

,

In this event handler:

$('#selctbox').change(function () {
    tmpproj = $('#projlist option:selected').val();
    checkimgs();
});

You are calling the checkimgs function directly without passing in any XML data as a parameter, which is why you are getting the $(xml) is not defined error. You need to call the $.ajax function in your change event handler:

$('#selctbox').change(function () {
    tmpproj = $('#projlist option:selected').val();
    $.ajax({
        url: fileurl,
        type: "GET",
        dataType: "xml",
        success: checkimgs,
        error: error_func
    });
});

Edit: In response to your comment—to avoid retrieving the file on every change, just store the XML response in a variable the first time you retrieve it:

var tmpproj = '02064';
var fileurl = 'menu.xml';
var xmlContent = '';

$.ajax({
    url: fileurl,
    type: "GET",
    dataType: "xml",
    success: checkimgs,
    error: error_func
 });


// Callback results if error
function error_func(result) {
    alert(result.responseText);
}

// Callback if Success
function checkimgs(xml) { 

    // Store the xml response
    if(xmlContent == '')
        xmlContent = xml;

    $(xml).find("itemprojn="+tmpproj+"").each(function()
    {           
        alert ($(this).attr("projn"));
    });
}

Then in your select change handler:

$('#selctbox').change(function () {
    tmpproj = $('#projlist option:selected').val();
    checkimgs(xmlContent);
});

Leave a Comment