JDB
JDB

Reputation: 73

Ajax POST to PHP var and return

I'm developing a web app where I want to pass the checkbox value to a PHP variable without submitting. Therefore I'm using Ajax to pass the value.

Code page 1:

<div class="sliderWrapper">
     input type="checkbox" name="val1" id="val1" value="Value 1">
 </div>
 <div class="sliderWrapper">
     input type="checkbox" name="val2" id="val2" value="Value 2">
 </div>

 <p id="test"></p>

<script>
 $("input[type=checkbox]").on("change", function () {
        var ids = [];
        $('input[type=checkbox]:checked').each(function () {
            ids.push($(this).val());
        });
        $.ajax({
            url: "page2.php",
            type: "POST",
            async: true,
            cache: false,
            data: ({value: ids, semester}),
            dataType: "text",
            success: function (data) {
                //alert(data)
                $("p#test").html(data);
            }
        });
    });
 </script>

Code page 2:

if(isset($_POST['value'])) {
    $values = $_POST['value'];

    foreach($values as $value){
        echo $value;
    }
}

So I'm passing the value back to an HTML

tag and I want to use it back on page 1 as a PHP variable. Is this possible?

Upvotes: 0

Views: 170

Answers (1)

Quentin
Quentin

Reputation: 943510

No.

Look at the order of events:

  1. Page 1 PHP runs on the server
  2. The server sends the result to the browser
  3. The browser loads the page and runs the Ajax
  4. The browser makes the Ajax request
  5. The browser gets the response

You can't use the response as a PHP variable in page 1 because:

  • PHP variables exist on the server and the data is now in the browser
  • The PHP script finished after step 1, so the program isn't running any more, and there would be nowhere to put the variable

If you want to do something with the data on the server, then do it in page 2. (You can put a function in a different PHP file and include it on both pages if you want to share logic between them).

If you want to change what is displayed in the browser in response to that then:

  • Have page 2 return the information needed to determine what should be shown
  • Write JavaScript that reads the data and makes the desired changes to the DOM

Upvotes: 2

Related Questions