0

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:

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

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

3
  • Whats document.getElementById("centro").value point to? Commented Sep 14, 2018 at 9:08
  • Try to wrap your code in a seperate script tag. Commented Sep 14, 2018 at 9:08
  • 1
    Possible duplicate of Script tag with both external source and body Commented Sep 14, 2018 at 9:11

1 Answer 1

3

Your <script> tag has a src and a body.

Try:

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, thanks that was the problem, just a stupid error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.