views:

587

answers:

1

Hi,

I am trying to retrieve values from a database by using JQuery Ajax to call a web service routine. The web service routine is set up properly and returns the value I require, however I'm confused about how the jquery ajax works... I don't know how to retrieve the value

$.ajax({
        type: 'POST',
        url: 'myservices.asmx/getRowName',
        dataType: 'xml',
        data: ({ param1: someData, param2: someData }),
        success: function(data) {
            alert( data.getElementsByTagName("string")[0].firstChild.data );
        },
        error: function(msg) { alert(msg.statusText); }
    });

So on the success, I can access the data returned through that function (I've checked and it is returning the right data), but what if I want to use the data outside of that function?

Does $.ajax return anything where I could retrieve the data I need? such as... data = $.ajax({...all the settings...}); or... data = $.ajax({...settings...}).responseText;

Any ideas?

+2  A: 

The problem with what you're suggesting you'd like to do is that AJAX is an asynchronous process and trying to assign the result of the AJAX call to a variable like that would suggest the code would need to "hang" there until the result comes back. That's not how things are done with Javascript. Most of the time I do whatever I need to do with my data in the success callback itself. If that's not enough, the way to do it would be to have a function that accepts the data as an argument and call it when you are done. This may seem weird to you if you're coming from other languages, but in Javascript things are a lot more event based ("do this when this happens"), so you have to setup your code accordingly:

function doStuffWithData(data) {
    // do whatever you want here
}

$.ajax({
    type: 'POST',
    url: 'myservices.asmx/getRowName',
    dataType: 'xml',
    data: ({ param1: someData, param2: someData }),
    success: function(data) {
        doStuffWithData(data);
    },
    error: function(msg) { alert(msg.statusText); }
});
Paolo Bergantino