Ulysnep
Ulysnep

Reputation: 405

XMLHttpRequest With Canvas on Loading Page

I'm trying to load a page with a canvas via XHR and the canvas is not displaying. I believe the issue is due to the fact that I'm not appending it to the XHR response.

Main Page

<script type="text/javascript">

function LoadContent1()
{
var LoadContent1;

if (window.XMLHttpRequest)
{
    LoadContent1 = new XMLHttpRequest();
}

LoadContent1.onreadystatechange = function()
{
    if (LoadContent1.readyState == 4 && LoadContent1.status == 200)
    {           
        document.getElementById("loadContent1").innerHTML = LoadContent1.responseText;
        document.getElementById("loadingImageContent1").src = "1-pixel.gif";
        $("#loadContent1Parent").hide();
        $("#loadContent1Child").hide();
    }
}

LoadContent1.open("GET", "page.php", true);
LoadContent1.send();
}

</script>

Page Loaded Via XHR (Page.php)

<canvas id="mycanvas_pie" height="290" width="290"></canvas>
<canvas id="mycanvas_pie2" height="290" width="290"></canvas>

<script>
    var myPie = new Chart(document.getElementById("mycanvas_pie").getContext("2d")).Pie(pieData1,opts);
    var myPie2 = new Chart(document.getElementById("mycanvas_pie2").getContext("2d")).Pie(pieData3,opts);
</script>

Upvotes: 1

Views: 762

Answers (1)

SalDev
SalDev

Reputation: 388

First of all, you need to make sure that your AJAX call is running, and it returns with the correct HTML code. You can easily find out this in any modern browser by using breakpoints for example, or by using the console.log() method.

You also need to make sure that the element - which you are trying to fill with the response - is already exists in the DOM. In your case it's ID is "loadContent1".

Other Recommendations:

  • I don't recommend you to use (almost) the same name in variable/function/object names, and for DOM elements. Try to use descriptive names because your code can be easily confusing, even in this tiny snippet
  • if it's not a must, try to avoid running javascript codes automatically when receiving and displaying an HTML code, because of security reasons. You can put that javascript code into your callback function for example, or more better if you organize those lines into a separate object.

Upvotes: 1

Related Questions