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.
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: