Send variable to PHP file

Elvo

New Member
#1
In a WordPress post I'm trying to send data to a PHP file stored in the root folder of my website with this code:
Mã:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript">
console.log('hi');
var cen = document.getElementById("centro").value;
$.ajax({
        url: 'centroUser.php',
        type: "POST",
        data: { 'cen': cen },
        success: function(data){
            console.log(data);
        }
});
</script>
centroUser.php:
Mã:
<?php
   $uid = $_POST['cen'];
   echo($uid);   
?>
The problem is that I can't get it to work, the variable $uid doesn't get echoed and even the console.log('hi') doesn't get called. I'm new to AJAX so I don't really know what I'm doing wrong, I have tried looking for other answers but I couldn't find something that worked.
 

Admin

Administrator
Thành viên BQT
#2
Your <script> tag has a src and a body.

Try:

Mã:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

console.log('hi');
var cen = document.getElementById("centro").value;
$.ajax({
        url: 'centroUser.php',
        type: "POST",
        data: { 'cen': cen },
        success: function(data){
            console.log(data);
        }
});
</script>
If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI - see here.
 
Top