-1

I have this function:

    function getNamep(id_user) {
    $.post('php/back.php', {
        id: id_user,
        f: "getName"
    }, function (data) {
        data = jQuery.parseJSON(data);
        if (data[0] == 1) {
            console.log(data)
        }
        else {
            console.log(data)
        }
    });
}

I want to get the result here:

var name = getNamep(2);

How i can do this? Returning data from $.post()

Thanks!

Gustavo Henrique
  • 138
  • 1
  • 14

1 Answers1

0

You can use callback.

function getName(id_user, cb) {
    $.post('php/back.php', {
        id: id_user,
        f: "getName"
    }, function (data) {
        data = jQuery.parseJSON(data);
        if (data[0] == 1) {
            console.log(data)
        }
        else {
            console.log(data)
        }
      if(cb) cb(data);
    });
}

function getResponse(name){
  console.log(name);
  htmlList = '<div class="desc">' + '<div class="thumb">' + '</div>' + 
             '<div class="details">' + "<p><a href=\"#\" onclick=\"messageCamp('" + v + "')\">" 
             + name + "</a><br/>" + '<muted>Available</muted>' + '</p>' + '</div>' + '</div>';
}
getName(1, getResponse);
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60