Oliver Houston
Oliver Houston

Reputation: 323

using d3.queue to wait for AJAX response

TL;DR: Any good examples of using AJAX, d3 and PHP to get data from a database and produce graphs from it would be greatly appreciated.

So I'm using d3 to create a force chart based on data pulled from a database using AJAX and PHP, I think there's a few ways to do this, either binding the data to a DOM element, or using D3.queue seem to be the most logical ways to do it, but I'm struggling to find simple examples of using all these bits together.

So my working AJAX request looks like this:

$(document).ready(function() {
        $('select[name="locations"]').change(function(){
            var location = $(this).val();
            $.ajax({
                    type: 'POST',
                    url: 'dataselect.php',
                    data: { l_id: location },
                    success: function (response) {
              console.log(response);
            },      
             });
        });
    });

I've tried passing the JSON to a DOM element, but no luck extracting it and some people seem to dislike this approach.

The d3 that works looks like this:

d3.json("test.php", function(error, graph) {
  if (error) throw error;... Lots more d3 that I don't think is relevant.

test.php and dataselect.php are identical except dataselect has a variable for the AJAX request and the d3 doesn't like it as it is.

So, my question is what is the smoothest way for d3 to "wait" for the data from the AJAX request before running?

I'm guessing I need to wrap some stuff in functions and queue it into some kind of order, but I'm really struggling to tie it together.

Finally, sorry I feel like this should be fairly trivial, but I have read a lot of questions and haven't managed to implement any solutions so far.

EDIT: So following the d3.request route, I've figured out how to send the data without AJAX:

d3.selectAll("#onploc")
.on('change', function() {
    var location = eval(d3.select(this).property('value'));
console.log(location);//gets value property of selected menu item.


d3.json("dataselect.php?l_id="+location,function(error, data) {
console.log(data);//sends location variable to php to get data back.
})
});

Upvotes: 0

Views: 636

Answers (1)

thedude
thedude

Reputation: 9812

This could go either way - you could either call the d3 drawing code from your success callback, e.g.

...
success: function(response) {
    var data = JSON.parse(response) // maybe, if you need to convert to JSON
    d3RenderFunction(data);
}

or you could pass the parameters using d3.request:

d3.request('dataselect.php')
  .mimeType("application/json")
  .response(function(xhr) { return JSON.parse(xhr.responseText); })
  .post({ l_id: location }, function(error, graph) { ... })

Upvotes: 1

Related Questions