0

I am trying to get some data through the database in jquery. I doing this through ajax, the ajax code returns the value fine. I then set a variable with the data comment.

The comment variable is then used to insert html into an element. However, it would appear that this variable is not set, because it is not being passed through the ajax function. How do I achieve that?

$(document).on('click', '.customer_progress_edit', function(){
   timeline_id = $(this).attr('data-timeline');
    $.ajax({ 
       type : 'POST',
       url      : '//'+base_url+'/ajax2/timeline-comment.php',
       data : 'timeline_id='+timeline_id,
       success  : function(data) {
           comment = data;
       }
   });
   $('#customer_pop_edit_comment').val(comment);
}); 

Yes, I am aware I could simply have the html() function within the ajax function, but I have simplified the code to give an easier idea of what I am trying to achieve, there is more to it than just this.

Source
  • 1,026
  • 4
  • 11
  • 23
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – freedomn-m Nov 25 '19 at 21:30
  • no thats different – Source Nov 25 '19 at 21:31
  • "*because it is not being passed through the ajax function*" no - because the ajax callback runs **after** the `.val()` line. *"the comment variable is **then** used"* - again, no, because the `comment=data` hasn't run yet, it runs later. – freedomn-m Nov 25 '19 at 21:31
  • Read the answer, not the question. It's the issue you have. – freedomn-m Nov 25 '19 at 21:32
  • Essentially you have this: set timeline_id, initiate an ajax call, set .val(comment), receive the response of the ajax call. It's the equivalent of putting `$("#customer").val(comment)` as the *second* line - it runs before the `success:` callback (as explained in the duplicate). – freedomn-m Nov 25 '19 at 21:33
  • 1
    oh, sorry, thanks, I will look into it – Source Nov 25 '19 at 22:35

1 Answers1

1

try this

var get_data = $.ajax({
type : 'POST',
url  : '//'+base_url+'/ajax2/timeline-comment.php',
data : 'timeline_id='+timeline_id
});
get_data.done(function(html){
    comment = html;
});