1

First time function is return Undefined, every other time it works and return object ....

Basically, the first time that var _d is stored, it is an undefined value.

the first time that it stores its value click is "undefined" and every other time it stores the appropriate value.

// jscript.js

function getDataById(This,table,Url)
{
    var Id = table.row(This.parent().parent()).data().id;
    $.ajax({
        url: Url + "/" + Id,
        type: "GET",
        dataType: 'json',
        success: function (Data) {
            var _d = Data;
            return _d;
        },
        error: function () {
            sweetAlert("Oops...", "Something went wrong!", "error");
        }
    });
    
}

/***********************/

$(document).ready(function () {

    $("#test tbody").on('click', '#aff', function () {
        console.log(  getDataById($(this),table,"test/email") );
    });

)};

/*****************/

// undefined
  • Is this a direct copy/paste of your code? Because at the ending braces of the `$(document).ready`, you have switched the 2 braces. – Loyalar Oct 29 '15 at 12:28

1 Answers1

0

$.ajax() is asynchronous and success is just a callback. The function getDataById must have a callback that will be called after ajax request

// jscript.js

function getDataById(This, table, Url, callback) {
  var Id = table.row(This.parent().parent()).data().id;
  $.ajax({
    url: Url + "/" + Id,
    type: "GET",
    dataType: 'json',
    success: function (Data) {
      callback(Data);
    },
    error: function () {
      sweetAlert("Oops...", "Something went wrong!", "error");
    }
  });
}

/***********************/

$(document).ready(function () {
    $("#test tbody").on('click', '#aff', function () {
      getDataById($(this), table, "test/email", function (data) {
        console.log(data);
      });
    });
  )
};
/*****************/
Arnaud Gueras
  • 2,014
  • 11
  • 14