0

I am creating a jquery plugin. I want to get data from back end and send as options to the plugin.

  function getData(){
     $.when(http_get('../list/')).then(function(response){
        students = response;
        return students;
        console.log(response);
     }, function(response){
        console.log('get failed');
     })
  }
  $('#element').pluginSmart({
    data: getData()
  });

Here I am getting the data from backend but it is not assigned to the data option of the plugin.

I know the data is assigned before the ajax returns. How to wait till the ajax returns and then assign?

I want to keep it plugin initialization simple. otherwise I would have initiated the plugin inside the then function.

Abel D
  • 1,040
  • 1
  • 18
  • 30

2 Answers2

0

You have to retrieve the data before initializing the plugin. Put your initialization code in the callback for your AJAX request, for example like this:

$.get('../list/', function(response){
    students = response;
    console.log(response);
    $('#element').pluginSmart({
        data: students;
    }); 
}).fail({
    console.log('get failed');
});

Alternatively, you can perform a synchronous request but that's horrible practice (see: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?)

Community
  • 1
  • 1
Petko Bossakov
  • 510
  • 2
  • 10
  • Like i said this plugin should be initialized as simple as possible. So i cant use it inside another ajax call. – Abel D Dec 22 '15 at 14:22
  • "simple" is a subjective measure. I do not think that there is anything complicated in this approach. In any case, I am glad that you managed to resolve your problem. – Petko Bossakov Dec 22 '15 at 16:22
  • I want to publish my work as plugin. So I want to make sure that non programmers can use this in ease. – Abel D Dec 23 '15 at 01:39
0

I found a better way of handling this situation. Since my goal is to keep the plugin initialization simple. I just pass the url into the plugin and get the data from inside the plugin.

Abel D
  • 1,040
  • 1
  • 18
  • 30