Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Cách truyền biến JavaScript sang PHP

JavaScript chạy phía client, PHP chạy phía server – không thể truyền biến trực tiếp trong cùng một tải trang. Cần gửi dữ liệu qua HTTP request (AJAX, form submit, URL parameter).

Cách phổ biến

1. AJAX (fetch / jQuery)

<script>
// JavaScript
const res = "success";
fetch('process.php', {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: 'data=' + encodeURIComponent(res)
});
</script>

PHP (process.php):

<?php
$data = $_POST['data'] ?? '';
echo "Received: $data";
?>

2. Form ẩn

<form id="myForm" action="process.php" method="POST">
    <input type="hidden" name="js_data" id="js_data">
</form>

<script>
document.getElementById('js_data').value = "success";
document.getElementById('myForm').submit();
</script>

3. Query String (chuyển trang)

<script>
window.location.href = 'process.php?data=' + encodeURIComponent("success");
</script>

Lưu ý: Code ví dụ gốc <?php echo "<script>document.writeln(res);</script>"; ?> không hoạt động vì PHP chạy trước, JavaScript chạy sau – biến JS chưa tồn tại khi PHP xuất ra.