1

This is my custom jQuery function:

(function($){
    $.fn.NotYet = function(arti_id) {
        this.append(function() {
            var result = 0;
            $.post("comment_load.php", {arti_id:arti_id, status:1}, function(data){
                console.log(data);          // Returns data from POSTed PHP file
                console.log(result);        // Returns 0
                //$(this).append(result);   // Not Working
                result = data;
                console.log(result);        // Returns data from POSTed PHP file
            });
            console.log(result);            // Returns 0
            return result;                  // Returns 0
        });         
        return this;                        // Returns 0
    };
})(jQuery);

I am calling the function like this:

$("div#Comments").NotYet(15);

I am trying to make a jQuery function, but I am unable to return the posted php file data back to into the <div> container.

Any suggestions?

FYI: This question is similar, but I could not understand what is happening and I needed a simple method. How do I return the response from an asynchronous call?

jkdev
  • 11,360
  • 15
  • 54
  • 77
Ramyz
  • 423
  • 6
  • 12

1 Answers1

1

$.post is async method its cant return anything. And your problem is result value set before ajax call end.That why the console.log value as 0.

  1. so you need to set inside the callback of success function.
  2. And inside the call back this element as invalid one.So you need declare some another variable before pass to the success function like var that = this

Code:

(function($) {
      $.fn.NotYet = function(arti_id) {
        this.append(function() {
         var that = this;
          var result = 0;
          $.post("comment_load.php", {
            arti_id: arti_id,
            status: 1
          }, function(data) {
            console.log(data); // Returns data from POSTed PHP file

            $(that).append(data);   //its work
            result = data;

          });
          console.log(result); // Returns 0 //its excute before ajax call
          return result; // its not possible
        });
      };
    })(jQuery);
prasanth
  • 22,145
  • 4
  • 29
  • 53