-2

Hi I am trying to get a php var from another page via ajax into javascript and it alerts nothing

PHP on getposY

<?php include"connectdatabase.php";
$posYquery=mysql_query("Select posY FROM multiplayer WHERE game = '1'");
$posY = mysql_fetch_array($posYquery);
$posY2 = $posY['posY']; 
?>

Javascript

function phpmove(){ 
$("#div1").load("getposY.php");
};
setInterval("phpmove()", 1);
var move = function(){
    canvasContext.clearRect(posX, posY, sizew, sizeh);
    var posY = "<?php echo $posY2; ?>";
    alert(posY);
    canvasContext.drawImage(player, posX, posY, sizew, sizeh);
};
setInterval(move, 1);

I do have a div with an id of div1 Thanks in advance

codingrose
  • 15,563
  • 11
  • 39
  • 58
Imad_bush
  • 3
  • 1
  • 3
  • Well, consider learning the difference between client and server side first. – idmean Jan 12 '14 at 09:56
  • thats not how ajax works. your page is rendered first var posY = ""; is "" at this moment see http://stackoverflow.com/questions/15964734/store-ajax-result-in-jquery-variable – Roman Pickl Jan 12 '14 at 09:59
  • 1
    possible duplicate of [PHP variable in JAVASCRIPT not working](http://stackoverflow.com/questions/21073130/php-variable-in-javascript-not-working) - Never ever duplicate your own questions. – hakre Jan 12 '14 at 10:02

1 Answers1

0

thats not how ajax works. your page is rendered first var posY = ""; is "" at this moment

see Store ajax result in jQuery variable

so it should be more like (not tested):

your php file

<?php include"connectdatabase.php";
$posYquery=mysql_query("Select posY FROM multiplayer WHERE game = '1'");
$posY = mysql_fetch_array($posYquery);
echo $posY;
?>

your javascript file

var posY;
var move = function(){
    canvasContext.clearRect(posX, posY, sizew, sizeh);
    $.get("getposY.php", function (data) {
      posY=data;
    });
    alert(posY);
    canvasContext.drawImage(player, posX, posY, sizew, sizeh);
};
setInterval(move, 1);
Community
  • 1
  • 1
Roman Pickl
  • 635
  • 8
  • 20