How to I send data from JavaScript to PHP and vice versa? [duplicate]

If you wish to submit this data via a form, you don't need to create the form with Javascript. Simply create an invisible form with HTML, populate the hidden field with Javascript, and automatically submit whenever you're ready.

  <form method="post" action="process.php">
    <input type="hidden" name="data" id="data" />
  </form>

  document.getElementById("data").value = "foo";

If you want to send this in an ajax-style fashion, I would suggest implementing jQuery, which makes this extremely easy. Note the previous case converted to a jQuery solution:

$.post("process.php", {data:"foo"}, function(results){
  // the output of the response is now handled via a variable call 'results'
  alert(results);
});

Following code shows a ajax request which submits a form from your page in background using jquery ajax. I hope it makes sense.

<html>
<head><title>Sample</title></head>
<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script language="javascript">
    function submitMe()
    {
       variableString = 'name='+$("#name").val()+'&location='+$("#location").val();
       jQuery.ajax({
       type: "POST",
       url: "http://google.com/some.php",
       data: variableString,
       success: function(msg){
         alert( "Data Saved: " + msg );
       }
     });
    }
</script>
<body>
    <form id="xyzForm">
       <input type="text" id="name" name="name"/>
       <input type="text" id="location" name="location"/>
       <input type="button" value="submit" onClick="submitMe();"/>
    </form>
</body>
</html>

First, you need to understand that php and javascript are running on different computers.

Php runs on the server whereas javascript runs on the client computer. That makes things a little bit nondirect. I mean, php and javascript cannot change variables directly, because they dont run at the same time. First php runs at the server, prepares the HTML and js and gives it to the client, then at clients computer javascript runs, if javascript needs something from server, it calls the server again (either post, get or ajax doesnt matter, it is still a http request).

So from php to javascript,you can pass the variable while preparing the javascript, at which pont only php runs and javascript not, and from javascript to php, you can pass the variable by making a request from clients computer to your php server with some variables.