sam sam - 10 days ago 5
Javascript Question

Post jQuery variable on same file and receive with PHP

How can I post jQuery data and receive on the same file without passing through the URL as a variable (eg.

test.php?data=xxx
).

For example here's the response.data that I can see in the console log.

function (response) {
console.log(response.data);
},


I want to post that data and receive on the same file. I have tried following:

function (response) {
//console.log(response.data);
$.post(window.location.href, {json_data: response.data});
},


but when in the body of same file I print

print_r($_POST);


it does not display anything.

Answer

Make sure that response.data is Type: PlainObject or String. See more here on PlainObjects

UPDATE

Here is a video that describes what this code sample does.

Code Sample

<?php
  if (empty($_POST)) :
    ?>
      Nothing was posted, please click there \/<br><br>
    <?php
  else :
    echo 'You posted: '.print_r($_POST['json_data'], 1).'<br><br>';
  endif;
?>

<a href="javascript:" onclick="fake_simple_response('simple string');">click here (simple string)</a><br>
<a href="javascript:" onclick="fake_simple_response({cat:'meow', dog:'woof'});">click here (plain object)</a>


<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function fake_simple_response (response) {
    console.log(response);
    $.post(window.location.href, {json_data: response});
}
</script>
Comments