0

I cant understand why this happens. I am writing a jquery plugin to fetch records from my database(Mongo) to return back the data. This is how the code looks...

(function() { 
var result1;
var image1;

$.fn.showRecs = function() {

        var loadData = randomShow();
        var result = loadData.complete(  function(data) {  

            $.each(eval(data), function(i,item){    
            result1  = item.name;
            image1 = item.pic1;  
            if ( image1 == undefined) { image1 = "face_unknown.png"; }  

        });

        }); 

        alert(result1);

        this.html("<img src='http://localhost/uploads/" + image1 + "'></img>" + "&nbsp;" + result1);


} 



function randomShow() { 

 return $.ajax({
       type: "POST",
       url: "http://localhost/action.php", 
       data: {'showProf' : 1,  'random' : 1 , 'limit2Show' : 1},
       datatype : "json",
       });

}

}(jQuery) );

Line that shows "this.html" does not show the values unless an alert is prepended before. Why does this happen ? Please let me know to get rid of it.

Also, I am looking to attach a timer to it so that this gets triggered every n seconds, where do i attach it ? Thanks for the help.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Param
  • 137
  • 1
  • 3
  • 13
  • you need to wrap that `this` in `$()` ie `$(this)` – Derek Apr 12 '14 at 05:01
  • Nope that did not help. I call this plugin fn as $("div").showRecs(); from my main script. Having $(this) just works the same way as without. – Param Apr 12 '14 at 05:30
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Liam Apr 30 '14 at 11:48

1 Answers1

0
 try to change your ajax like:

function randomShow() { 

 return $.ajax({
   type: "POST",
   url: "http://localhost/action.php", 
   async:false,
   data: {'showProf' : 1,  'random' : 1 , 'limit2Show' : 1},
   datatype : "json",
   });

}

}(jQuery) );

Please note that the "async:false" will ensure you to get return the ajax response when it has been executed succesfully. In your case here it is skiping the ajax, as it behaves asynchronous.

Naveen Chandra Tiwari
  • 5,055
  • 3
  • 20
  • 26
  • I really do not wanna use "ajax:false" that breaks the whole purpose of my plugin since it must load them asynchronously without affecting rest of their functionality in the page. What gives ? – Param Apr 12 '14 at 05:49
  • In simple terms, facebook/g+ have plugin's that load the share counts in ajax asynchronously. My plugin would be something like that so it should not interrupt any of the things in the page as it loads them seamlessly. How is this achieved ? – Param Apr 12 '14 at 05:53