Jump to content


Photo

Load canvas after ajax call


  • Please log in to reply
5 replies to this topic

#1 KillGorack

KillGorack
  • Members
  • PipPipPip
  • Advanced Member
  • 33 posts

Posted 16 April 2018 - 03:07 PM

Page load I think calls the stuff like drawing canvas and the like, the problem here is that I don't know how to call the canvas to load after an ajax call. I can create the data I need, and see exactly what is expected, it's just the canvas isn't loading.

 

<edit>The canvas div is visible, it's just not drawing what is within.</edit>

 

 

Form

<form METHOD="POST" ACTION="">

	Project
	<select name="fm_project" onchange="showdata(this.form)" id="fm_project">
	<option value="2">Project A</option>
	<option value="1">Project B</option>
	<option value="3">Project C</option>
	<option value="0" SELECTED>Select One</option></select>

	Module
	<select name="fm_module" onchange="showdata(this.form)" id="fm_module">
	<option value="194">B</option>
	<option value="195">C</option>
	<option value="197">D</option>
	<option value="196">E</option>
	<option value="0" SELECTED>Select One</option></select>

	Stage
	<select name="fm_stage" onchange="showdata(this.form)" id="fm_stage">
	<option value="201">stagea</option>
	<option value="202">stageb</option>
	<option value="203">stage3</option>
	<option value="0" SELECTED>Select One</option></select>

	Part
	<select name="fm_part" onchange="showdata(this.form)" id="fm_part">
	<option value="1">Part1</option>
	<option value="2">Part2</option>
	<option value="3">part3</option>
	<option value="0" SELECTED>Select One</option></select>

</form>

<div id="graph_field">Start by choosing some filters above..</div>

JS

      <script>
        function showdata(form){
          var xhttp,
              project = form.fm_project.value,
              module = form.fm_module.value,
              stage = form.fm_stage.value,
              partno = form.fm_part.value;
              
          if (project == "") {
            document.getElementById("graph_field").innerHTML = "";
            return;
          }
          if (module == "") {
            document.getElementById("graph_field").innerHTML = "";
            return;
          }
          if (stage == "") {
            document.getElementById("graph_field").innerHTML = "";
            return;
          }
          if (partno == "") {
            document.getElementById("graph_field").innerHTML = "";
            return;
          }

          xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
              document.getElementById("graph_field").innerHTML = this.responseText;
            }
          };
          xhttp.open("GET", "printme.php?app=projects&ala=csajax&fm_project="+project+"&fm_module="+module+"&fm_stage="+stage+"&fm_part='"+partno+"'", true);
          xhttp.send();
        }
      </script>

canvas in the Ajax call refereed in the xhttp.open line above.

<canvas id="myCanvas" width="970" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
						

  do stuff...
						
						
</script>

Thanks!


Edited by KillGorack, 16 April 2018 - 03:13 PM.


#2 dalecosp

dalecosp
  • Members
  • PipPipPip
  • Advanced Member
  • 446 posts
  • LocationMissouri

Posted 16 April 2018 - 03:53 PM

In over my head here ... did you "blank" the canvas first? If it had anything in it, it would need to be erased and then redrawn, as I understand it.

Edited by dalecosp, 16 April 2018 - 03:54 PM.

"God doesn't play dice" --- Albert Einstein
"Perl is hardly a paragon of beautiful syntax." --- Weedpacket

#3 KillGorack

KillGorack
  • Members
  • PipPipPip
  • Advanced Member
  • 33 posts

Posted 16 April 2018 - 04:06 PM

I can foresee this being an issue when/if I get anything to draw in there to begin with. I'm not sure how to call a blanking of the canvas with an ajax call. Perhaps answering that question  will result in a way to also draw with t he ajax function.



#4 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,110 posts

Posted 16 April 2018 - 07:58 PM

In your printme.php, build the <canvas>...</canvas> element as a string then output the string.

 

I have never used canvas, but here is an example using SVG, which is fairly similar.

 

SAMPLE.HTML

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample SVG with AJAX</title>
<style type='text/css'>
div {
    width: 40%;
    height: 150px;
    margin: 20px;
    padding: 20px;
    border: 1px solid gray;
    float: left;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
    function draw()
    {
        var color = $("#colorselect").val();
        var sides = $("#sideselect").val();
        
        $.get (
            "sample_svg.php",
            { "color" : color ,
              "sides" : sides
            },
            function(resp) {
                $("#graphics").html(resp);
            }
        )
    }
    
    $().ready( function() {
        
        $("#colorselect").change( function() { draw(); })
        $("#sideselect").change( function() { draw(); })
    })
</script>
</head>
<body>
<div>
    Color: <select id='colorselect'>
               <option value='0'>- choose -</option>
               <option value='red'>Red</option>
               <option value='blue'>Blue</option>
               <option value='green'>Green</option>
            </select>
    <br><br>
    Sides: <select id='sideselect'>
               <option value='0'>- choose -</option>
               <option value='3'>Three</option>
               <option value='4'>Four</option>
               <option value='5'>Five</option>
               <option value='6'>Six</option>
               <option value='7'>Seven</option>
               <option value='8'>Eight</option>
            </select>
</div>  
<div id="graphics">
    <!-- graphic goes here -->
</div>  
</body>
</html>

 

SAMPLE_SVG.PHP (called via ajax)

<?php

$color = isset($_GET['color']) ? $_GET['color'] : '#888';
$sides = isset($_GET['sides']) ? $_GET['sides'] : 0;

exit( writeSVG($color, $sides) );            //output the SVG code

function writeSVG($color, $sides) {
    $svg = "<svg width='100' height='100' viewBox='0 0 100 100'>
        <rect x='0' y='0' width='100' height='100' fill='#CCC'/>\n";
    if ($sides < 3 || $sides > 8)  {
        $svg .= "<circle cx='50' cy='50' r='50' stroke='black' fill='$color'/>\n";
    }
    else {
        $path = "M 100 50 ";
        $theta = 2 * M_PI / $sides;
        $svg .= "<circle cx='50' cy='50' r='50' stroke='black' fill='none'/>\n";
        for ($i=1; $i<$sides; $i++) {
            $x = 50 + 50 * cos($i * $theta);
            $y = 50 - 50 * sin($i * $theta);
            $path .= "L $x $y ";
        }
        $path .= "z ";
        $svg .= "<path d='$path' fill='$color' />\n";
    }    
    $svg .= "</svg>\n";
    return $svg;
}
?>

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#5 maxxd

maxxd
  • Members
  • PipPipPip
  • Advanced Member
  • 743 posts
  • LocationNorth Carolina

Posted 16 April 2018 - 11:04 PM

I may be missing something here, but it looks like you're trying to draw in the canvas on the currently loaded page from the remote AJAX target script? It looks to me like all you're doing in the onreadystatechange() handler is updating the contents of the #graph_field div, which isn't a canvas element to begin with.

 

You'll need to apply the data returned from the AJAX call to the canvas on the currently loaded page. Whether that's - as Barand suggests - an html string that you replace the entire canvas contents with or a dataset you manipulate in JS to draw into the element, the modifications have to be made on the currently loaded page.

 

Basically, you're not loading the canvas element after the AJAX payload has been received (although you could, of course, dynamically create a new canvas element which you then append to the currently loaded page) you're manipulating the canvas element that's already there. That manipulation can happen at any time.



#6 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,110 posts

Posted 17 April 2018 - 08:22 AM

Further to maxxd's reply, here is an expansion of the above code.

The additional items (transparency and size) manipulate the elements of the current drawing directly, whereas the the first two, as before, cause a complete redraw of the image.

 

SAMPLE.HTML

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample SVG with AJAX</title>
<style type='text/css'>
div {
    width: 40%;
    height: 150px;
    margin: 20px;
    padding: 20px;
    border: 1px solid gray;
    float: left;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
    function draw()
    {
        var color = $("#colorselect").val();
        var sides = $("#sideselect").val();
        
        $.get (
            "sample_svg.php",
            { "color" : color ,
              "sides" : sides
            },
            function(resp) {
                $("#graphics").html(resp);
                $("#sizeselect").val('100');    // reset to default
                $("#transelect").val('1.0');    // reset to default
            }
        )
    }
    
    $().ready( function() {
        
        $("#colorselect").change( function() { draw(); })
        $("#sideselect").change( function() { draw(); })
        
        $("#sizeselect").change( function() {
            var sz = $(this).val();
            $("#drawing").attr({"width":sz, "height":sz});
        })
        
        $("#transelect").change( function() {
            var tr = $(this).val();
            $("#target").attr("fill-opacity", tr);
        })
    })
</script>
</head>
<body>
<div>
    Color: <select id='colorselect'>
               <option value='0'>- choose -</option>
               <option value='red'>Red</option>
               <option value='blue'>Blue</option>
               <option value='green'>Green</option>
            </select>
    <br><br>
    Sides: <select id='sideselect'>
               <option value='0'>- choose -</option>
               <option value='3'>Three</option>
               <option value='4'>Four</option>
               <option value='5'>Five</option>
               <option value='6'>Six</option>
               <option value='7'>Seven</option>
               <option value='8'>Eight</option>
            </select>
    <br><br>
    Transparency: <select id='transelect'>
            <option value='1.0'>None</option>
            <option value='0.5'>Medium</option>
            <option value='0.1'>High</option>
            </select>
    <br><br>
    Size: <select id='sizeselect'>
            <option value='100'>100 pixel</option>
            <option value='50'>50 pixel</option>
            <option value='150'>150 pixel</option>
            </select>
</div>  
<div id="graphics">
    <!-- graphic goes here -->
</div>  
</body>
</html>
 

 

SAMPLE_SVG.php

<?php

$color = isset($_GET['color']) ? $_GET['color'] : '#888';
$sides = isset($_GET['sides']) ? $_GET['sides'] : 0;

exit( writeSVG($color, $sides) );            //output the SVG code

function writeSVG($color, $sides) {
    $svg = "<svg id='drawing' width='100' height='100' viewBox='0 0 100 100'>
        <rect x='0' y='0' width='100' height='100' fill='#CCC'/>\n";
    if ($sides < 3 || $sides > 8)  {
        $svg .= "<circle id='target' cx='50' cy='50' r='50' stroke='black' fill='$color'/>\n";
    }
    else {
        $path = "M 100 50 ";
        $theta = 2 * M_PI / $sides;
        $svg .= "<circle cx='50' cy='50' r='50' stroke='black' fill='none'/>\n";
        for ($i=1; $i<$sides; $i++) {
            $x = 50 + 50 * cos($i * $theta);
            $y = 50 - 50 * sin($i * $theta);
            $path .= "L $x $y ";
        }
        $path .= "z ";
        $svg .= "<path id='target' d='$path' fill='$color' />\n";
    }    
    $svg .= "</svg>\n";
    return $svg;
}
?>

 

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users