Using jQuery AJAX to fetch data from a database via a web service

I am trying to get values ​​from a database using JQuery Ajax to call a web service procedure. The webservice rule is set up correctly and returns the required value, however I am confused about how jquery ajax works ... I don’t know how to get 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); }
    });

      

This way, on success, I can access the data returned by this function (I checked and returned the correct data), but what if I want to use the data outside of this function?

Does $.ajax

it return anything where I could get the data I need? such as...

data = $.ajax({...all the settings...});

      

or...

data = $.ajax({...settings...}).responseText;

      

Any ideas?

+1


source to share


2 answers


The problem with what you're suggesting to do is that AJAX is an asynchronous process and tries to assign the result of the AJAX call to a variable like the one that assumes the code should hang there until the result is returned. This is not how Javascript is done. Most of the time, I do whatever I need to do with my data in the callback itself. If that's not enough, the way to do it should be to have a function that takes data as an argument and call it when you're done. This may seem strange to you if you are switching from other languages, but Javascript is much more event-driven ("do it when it happens"), so you need to adjust 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); }
});

      

+3


source


Please find a better example using xml in JQuery http://codernd.com/DevelopersFile/Reading-XML-file-using-JQuery.aspx



0


source







All Articles