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?

2
  • A better practice would be to output in JSON format from PHP. Commented Sep 9, 2016 at 18:10
  • 1
    Your alert is running before the response is received. You need to put it in the success callback if you want to use the value returned in the response. Commented Sep 9, 2016 at 18:10

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.