Dave Clarke
Dave Clarke

Reputation: 2696

AJAX load doesn't run javascript

I have a main page with a graph on, a dropdown box allows the user to select which graph they want to see.

When the dropdown gets changed I want AJAX to load the correct graph from my file, graphmaker.php. This file has all the graphs in appropriate DIVs, i.e graph1, graph2 etc.

These graphs are generated using Google Charts Visualisation.

However, when I do this AJAX just loads an empty box and from what I have researched this is because the script on the page doesn't get executed.

In essence, I want Ajax to:

My code:

function switchgraph(graph) {
var switchto = $("#graph"+graph+"_dd").val();
$('#graph'+graph).load('graphmaker.php #'+switchto);
}

Any suggestions?

Dave

Upvotes: 1

Views: 263

Answers (3)

Gijs
Gijs

Reputation: 5262

Instead of using a selector with load, which removes the scripts, select the relevant graph once the AJAX call has finished:

function switchgraph(graph) {
    var switchto = $("#graph"+graph+"_dd").val();
    $('#graph'+graph).load('graphmaker.php', function onComplete() {
       function doMoveGraph() {
           $('#graph' + graph).empty().append(toBeUsed);
       }
       function checkMoveGraph() {
            if (!toBeUsed.is(":empty")) {
                doMoveGraph();
            } else {
                setTimeout(checkMoveGraph, 100);
            }
       }
       var toBeUsed = $(this).find('#'+switchto);
       setTimeout(checkMoveGraph, 100);
    });
}

Upvotes: 2

JanHocevar
JanHocevar

Reputation: 199

Instead of $.ajax I suggest you using $.post function, so try something like this:

$.post('graphmaker.php', { data : dataSource },
  function(data) {
    //On Success
  }
)

Upvotes: 0

Nick
Nick

Reputation: 1869

I think you need to use

$.getScript() 

Or You can try

$.ajax({
 url: url,
 dataType: "script",
 success: success
});

Please check the API

Upvotes: 0

Related Questions