0
  // AjaxHandler
  function AjaxHandler(url, dataContent){
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: dataContent,
        async: true,
        cache: false,
        success: function(obj){
          console.log(obj);
          return obj;
        }
    });
  }

    $("#button").click(function(){
        AjaxHandler( "http://xxxxxx/yyyyyy.api", "some data" );
        alert(obj);
     });

If I can get object data from called function "AjaxHandler". How do I use this object data??I try to alert obj but show not define.

I can print obj data in console in function AjaxHandler. So the data is there. I just don't know how to use it after called function.

Dreams
  • 8,288
  • 10
  • 45
  • 71
  • You can't do it that way. AJAX is asynchronous so it won't return anything straight away. You need a callback function or something like that. Even if it would work, `obj` would only be a local variable inside `success` function, not in your click handler. – putvande Aug 08 '15 at 12:09

3 Answers3

0

Since AJAX is asynchronous, you cannot "return" a variable. You can however send it to the next function to process the data.

function AjaxHandler(url, dataContent){
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: dataContent,
        async: true,
        cache: false,
        success: function(obj){
            console.log(obj);
            processAjax( obj );
        }
     });
}

function processAjax( obj ) {
    alert(obj);
}

$("#button").click(function(){
    AjaxHandler( "http://xxxxxx/yyyyyy.api", "some data" );
});
Jeffrey
  • 1,766
  • 2
  • 24
  • 44
0

Try by success in ajax:

// AjaxHandler
  function AjaxHandler(url, dataContent){
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: dataContent,
        async: true,
        cache: false,
        success: function(obj){
          console.log(obj);
          return obj;
        },
    success(function() {
    (function() {
    alert( "success" );

      })
  })
        });
      }
$("#button").click(function(){
    AjaxHandler( "http://xxxxxx/yyyyyy.api", "some data" );   
 });
Siamak Ferdos
  • 3,181
  • 5
  • 29
  • 56
0

As the $.ajax method returns a promise, you can do the following:

function AjaxHandler(url, dataContent){
    return $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: dataContent,
        async: true,
        cache: false,
        success: function(obj){
            return obj;
        }
     });
}

$("#button").click(function(){
    AjaxHandler( "http://xxxxxx/yyyyyy.api", "some data" )
      .then(function (obj) {
        console.log(obj);
      });
});
Benoit
  • 751
  • 5
  • 8