0

I known that ajax success function is can't return data,so I had tried by call back function,but it still there getting undefined return.I have done by variable responseText ,but I'm not want to do by that.So help me with callback function return data!!!

HTML

<div id="address">
        <table>
        <thead>
        <th>Department</th><th>Name</th><th>Age</th><th>Address</th>
        </thead>
        <tbody>
        </tbody>
</div>

JS

getAddress callback() is return null

 $(document).ready(function(){
        $.ajax({
            url : "header.php",
            dataType : "json",
            success : function (d) {
            var temp = getAddress(callback); 
            console.log(temp)   // undefined
            var data = JSON.parse(temp);
            $.each(data,function(i,d){
                $("#address tbody").append("<tr><td>"+d[i].dept_name+"</td><td>"+d.Name+"</td><td>"+d.Age+"</td><td>"+d.Address+"</td></tr>");
            });         
            }
        });                     
    });    

     function callback(result){
        return result;
     }
    function getAddress(callback){
           $.ajax({
           url: 'address.php',
           async : false,
           dataType : 'json',       
           success: function(result){
            callback(result);
           }
           });          
    }
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52

1 Answers1

2

You are using the callback in a wrong way. The logic working with the value returned by the ajax call should be within the callback

$(document).ready(function() {
  $.ajax({
    url: "header.php",
    dataType: "json",
    success: function(d) {
      getAddress(function(data) {
        console.log(data) // undefined
        //var data = JSON.parse(temp); not required as you have `dataType: 'json'
        $.each(data, function(i, d) {
          $("#address tbody").append("<tr><td>" + d[i].dept_name + "</td><td>" + d.Name + "</td><td>" + d.Age + "</td><td>" + d.Address + "</td></tr>");
        });
      });
    }
  });
});

In your code, you are calling getAddress with the callback, but since the getAddress method is not returning anything the value of temp will be undefined.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531