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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With