-1

I would like to know how can I pass ajax variable to javascript, I an working on this example of code. Notice: append is work but it is not the best solution

$.ajax({
             type: "POST",
             dataType: "json",
             url: "get_promesse_done.php",
             data: {num : num,prmaff : prmaff},
             success: function(data1) {
                        var f= '<td >'+data1[0]+'</td>';
                        var y = '<td >'+data1[1]+'</td>';
                        var x = '<td >'+data1[2]+'</td>';
                        var  tab9='<tr>'+f+y+x+'</tr>';

                                  // $('#testb').append(tab9);
             }
            });

        ss1='<td bgcolor=#27ec04><table id="testb">'+tab9+'</table></td>';
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
freddy
  • 13
  • 3
  • "pass ajax variable to javascript" That does not make any sense. AJAX is just a way of requesting data from a server. – Mike Cluck Nov 21 '16 at 17:56
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. – Zakaria Acharki Nov 21 '16 at 17:56

1 Answers1

1

The problem is with JavaScript closures because tab9 is undefined the parent scope of $.ajax. All variables defined in success scope are inaccessible from the global. Another is that $.ajax is asynchronous (non-blocking) and allows the execution of code after it, and you assume that ss1 will have the value of tab9 from AJAX, but in fact, it does not.

You could define tab9 in the parent scope of $.ajax success, and update that. Another thing is to keep your code more readable, is wrapping what you want to happen in a function that would be called after AJAX is completed.

// define these in advance.
var ss1,
    tab9;

$.ajax({
    /* settings */
    success: onSuccess // set callback to onSuccess;
});

// this will be called with all arguments of $.ajax.success
function onSuccess(data){

         var f= '<td >'+data1[0]+'</td>';
         var y = '<td >'+data1[1]+'</td>';
         var x = '<td >'+data1[2]+'</td>';
         tab9='<tr>'+f+y+x+'</tr>'; // update tab9

         ss1='<td bgcolor=#27ec04><table id="testb">'+tab9+'</table></td>'; // update ss1

         // append to dom or whatever you want.

}
Community
  • 1
  • 1
Adam Azad
  • 11,171
  • 5
  • 29
  • 70