0

Hi i need a way to pass PHP value to processing.js how can i do this. I know that i got to use AJAX but i don't know what to do to recive value in processing.js. I've tryed something like that

<script type="text/javascript">
function go(){
        var s;
    var variable = 5;
    $.ajax({
        method:"POST",
        tupe:"POST",
        url: "take.php",
        data:({val:variable}),
        success: function(data){
            //$('#msg').html(data);  
                            var b = data;
                            s=b;
        }

    });
            alert (s);
    }
</script>

and my PHP is:

<?php
if($_POST){
    $img = "index.jpg"  ;
    echo $img;

}
?>

but when i alert 's' it is undefined and i dont know how to pass it to processing code to show image in to a canvas. Can someone felp me?

Mimi Chan
  • 111
  • 8

2 Answers2

2

Ajax is asynchronous. That means that while the ajax call executes, the script continues.

Your s variable is not defined until after the ajax call finishes, in the success function. Right after the ajax call in the script - but not in time - it is not defined yet.

To access the variables returned by the ajax call, you need to put your logic in the success function.

jeroen
  • 91,079
  • 21
  • 114
  • 132
0

The other answer is correct, but another option is to use a synchronous call, which will block the call to ajax() until the data returns. This is how it looks like you assumed it worked.

To make a synchronous call, just pass the async:false parameter into the ajax() call, like this:

$.ajax({
        method:"POST",
        tupe:"POST",
        url: "take.php",
        data:({val:variable}),
        success: function(data){
            //$('#msg').html(data);  
                            var b = data;
                            s=b;
        },
        async: false
    });

More info here: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

And in the JQuery documentation.

Community
  • 1
  • 1
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107