-1

I'm trying to pass an array from JavaScript to PHP using JSON. I created a JSON using JSON.stringify and I know to decode it in PHP using json_decode but how can I pass it? To be clear, those variables are in a one php file.

I want to use it like this:

<script>
var arr = getArray();
var myJSON = JSON.stringify(arr);
... passing myJSON to PHP ...
</script>
<?php
$arr = //get myJSON
?>

I tried this:

     <script>
        var signalff = ff(signal);
           request = $.ajax({
                type: "POST",
                url: "ecg_database.php",
                data: {myData:JSON.stringify(signalff)}
        });
    request.done(function (response, textStatus, jqXHR){
        console.log("Hooray, it worked!");
    });

    request.fail(function (jqXHR, textStatus, errorThrown){
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });
   </script>
   <?php
        $obj = $_POST["myData"];
        echo $obj;
   ?>

And in console I have a message "Hooray, it worked!", but it doesn't write anything by echo from $obj.

mrWalker
  • 1
  • 3

1 Answers1

0

You can't do it like that. This is what happens with your code:

  1. The user goes to the URL
  2. The browser requests the page
  3. The server runs the PHP. $_POST["myData"] isn't set.
  4. The server sounds the result to the browser
  5. The JavaScript in the page sends the data to the URL
  6. The server runs the PHP again. This time $_POST["myData"] is set.
  7. The result is available in response

You have two different requests and two different responses.

The request you send in step 5 doesn't travel back in time and retroactively change the request you sent in step 2.

Separate out your PHP so you have one URL to generate the original page and another to deal with the data you send with JavaScript.

Then use JavaScript to do something with the data in the response variable.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335