Konservin
Konservin

Reputation: 1017

Executing Javascript in Ajax-called page

I need to send some data with Ajax call to a PHP file that parses it, renders a graph with d3js (thus having some Javascript in it), extracts resulting SVG (more JS) and saves it to an SQL (via another ajax call). So it's like a sequence of 3 pages/files: data manipulation page --> graph/svg renderer --> SQL upload with PHP

The problem is, if I submit 1st page, the Javascript of 2nd page is not executing. If I copy the request of 1st page to another window, it works fine.

Simplified, the files are like this:

test_ajax_1.php:

<html>
  <head>
    <script type="text/javascript" src="../addons/jquery-1.10.2.min.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      $(document).ready( function() {
        var request = $.ajax({
          url: "test_ajax_2.php",
          type: "get",
          data: {
            graph : '123'
          }
        });
      });
    </script>
  </body>
</html>

test_ajax_2.php:

<html>
  <head>
    <script type="text/javascript" src="../addons/jquery-1.10.2.min.js"></script>
  </head>
  <body>
    <script type="text/javascript">
      $(document).ready( function() {
        var renderedGraph = "<svg><? echo $_GET['graph']; ?></svg>";
        var request = $.ajax({
          url: "test_ajax_3.php",
          type: "get",
          data: {
            newGraph : renderedGraph
          }
        });
      });
    </script>
  </body>
</html>

test_ajax_3.php:

<?php
  $renderedGraph = $_GET['newGraph'];
  $connect_db=mysqli_connect('localhost', 'this', 'that', 'whatnot');
  $result = $connect_db->query("UPDATE the_table SET svg='$renderedGraph' WHERE id = '1'");
?>

If I go to www.mysite.com/test_ajax_1.php, nothing happens

If I go to www.mysite.com/test_ajax_2.php?graph=123, if works fine.

The actual question is, is it possible to have Javascript executed on Ajax-called page, or should I find some other approach?

Upvotes: 3

Views: 1773

Answers (1)

Kippie
Kippie

Reputation: 3820

You're not actually doing anything with the response you're getting from your ajax call. An easy way to run the script would be to create a hidden iframe and add the result html into it.

  $(document).ready( function() {
    var request = $.ajax({
      url: "test_ajax_2.php",
      type: "get",
      data: {
        graph : '123'
      },
      success: function(data) {
          var iframe = $("<iframe>").html(data).hide();
          $("body").append(iframe);
    });
  });

Upvotes: 3

Related Questions