0

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.

1
  • please add here the value that you have in response.data which you see in the console. when i test this, i am able to see $_POST['json_data'] just fine, but i am putting a simple value in where you have response.data. Commented Nov 22, 2016 at 23:29

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

You wrote above that you tested and it works. Can you post the full example?
Sure i'm updating my answer now.
0

If you want to use POST, one way is to create a form and submit it with jQuery.

<form id="form-id" method="post" action="">
    <input type="hidden" value="hello world" />
</form>

<script>
$('#form-id').submit();
</script>

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.