PHP Javascript variable help
Is there any way to pass a javascript variable to a php function or simply assign a js variable to a php variable....???
test("asdas"); I need to update "asdas" to a dynamic value, i.e o开发者_StackOverflow社区f the form,
you can't
You can pass value from js to PHP using ajax request or add js value to URL and then reload page.
Variant #1 (using ajax):
JS side (jquery)
var js_var = 'hello';
$.ajax({
type: "POST",
url: "some.php",
data: "js_var="+js_var,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
PHP side
$js_var = isset($_POST['js_var']) ? $_POST['js_var'] : '';
Variant #2 (with page reload):
JS side
<script type="text/javascript"> <!-- var js_var = 'hello'; window.location = "http://www.yoursite.com/?js_var="+js_var; //--> </script>
PHP side
$js_var = isset($_GET['js_var']) ? $_GET['js_var'] : '';
When you want to send something from JS to PHP or from PHP to JS, use Ajax. If PHP already knows the value it wants to send to JS when it's delivering the page, you can also embed it in JS:
<script>
var name="$name";
</script>
Edit: As porneL said, you should not put data in the page that way without escaping it to avoid opening XSS holes.
Oh, and if you use AJAX, also pay attention on not making ajax data text/html
or so
to avoid XSS, too.
精彩评论