1

I'm trying to use jsFiddle to simulate an ajax response but I'm getting an undefined value. Does anyone know how to do this? My fiddle is here:

http://jsfiddle.net/heaversm/v75vN/10/

and to see the problem click on "login" from the result box

animuson
  • 53,861
  • 28
  • 137
  • 147
mheavers
  • 29,530
  • 58
  • 194
  • 315
  • You have your `return` statements inside the success and error functions. The loginUser function itself has no return statement, which is why you are getting undefined. – Brian Glaz Sep 01 '11 at 22:14
  • possible duplicate of [jquery.form and cross-domain requests](http://stackoverflow.com/questions/5066213/jquery-form-and-cross-domain-requests) – animuson Dec 19 '11 at 04:46
  • Here is an example I have in jsFiddle of working with /echo/: http://jsfiddle.net/djlerman/bbj8k9pe/ – Donavon Lerman Feb 16 '16 at 21:59

2 Answers2

2

You are returning from $.ajax's callbacks (success and error). Since the $.ajax method give you callback hooks, you should provide the same in the loginUser function

loginUser: function(cidVal, midVal, surveyVal, callback) {

    $.ajax({
        // ...
        success: function(data) { callback(true); },
        error: function(data){ callback(false);},
    });
}

And then use that callback to know when the operation has completed:

loginUser('foo', 'bar', 'far', function (result) {
    alert(result);
});
Bryan Menard
  • 13,234
  • 4
  • 31
  • 47
2

Your alert statement runs before the Ajax request has completed. You need to pass in a callback to updateUser to set loginResult:

updateUser: function(cidVal,aidVal,sidVal,surveyVal, onSuccess){
    $.ajax({
        url: wsURL,
        type: 'POST',

        //data: { Function: "UpdateConsumer", ConsumerId: cidVal, ActivityId: aidVal, SurveyId: sidVal, Survey: surveyVal }
        //Sample XML Data for the Purpose of Testing in JS Fiddle:
        data: { xml: '<UpdateConsumer><Status>OK</Status></UpdateConsumer>' },
        success: function(data) {
            if (onSuccess) {
                onSuccess(data);
            }
        },
        error: function(data){
            //Error in data or unable to connect
            return ("error");
        },
        dataType: "xml" //We're expecting XML back from the server
    });

Then to call it:

loginResult = c.loginUser(cid,mid,survey, function (result) { alert(result); } );
Tuan
  • 5,382
  • 1
  • 22
  • 17