Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I go about passing data from JavaScript code to PHP and back. Right now, I do this is a round about way:
PHP to JavaScript: I would simply use the inline echo to send the data:

<script type="text/javascript">
    var data = <? echo $target_variable ?>
</script>

OR

<script type="text/javascript">
    var data = <?= $target_variable ?>
</script>

JavaScript to PHP: I would create a form element in the JavaScript that would sumbit the data for me to the php file:

<script type="text/javascript">
    var data = targetData;
    document.write("
        <form method=\"post\">
            <input type=\"hidden\" value=\""+target_value+\""></input>
        </form>
    ");
</script>
</script>

Are there any better ways to do this? Best practices sort of thing.

like image 799
chustar Avatar asked Dec 10 '22 18:12

chustar


1 Answers

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);
});
like image 101
Sampson Avatar answered Dec 13 '22 23:12

Sampson