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);
});

Leave a Comment