Pon Somean
Pon Somean

Reputation: 143

How to pass values from AJAX and JQuery to PHP in the same file

I am current have the following script. I want pass a value from javascript to php by using AJAX. What's wrong with my code?

<script type=" text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
      $.post("index.php",{host:document.referrer},function(data){});  
    });
</script>
<?php
$dataString=$_POST['host'];
echo $dataString;
?>

Upvotes: 0

Views: 219

Answers (1)

afuzzyllama
afuzzyllama

Reputation: 6548

Since the PHP is executed first, you will never see the echo $dataString from your AJAX request. This code will post your request to the server, but you'll never see the result.

Right now here is what is happening:

  1. Your web server renders out your page.
  2. Your browser posts a request to index.php, and ignores the result

From the docs you can see this:

$.post('index.php', function(data) {
  $('.result').html(data);
});

The data in that function will return what echo $dataString; outputs from your script.

Also, your post isn't configured correctly. You need to put data: before {host:document.referrer}

Upvotes: 2

Related Questions