Error in $.post method

Asked

Viewed 35 times

0

The index.html page contains:

<!DOCTYPE html>
<html>
<head>
    <title>teste</title>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
<a href="teste.php"><img id="adicionar" src="aceitar.jpg" alt="aceitar" style="height: 75px"></a>
</body>
</html>

The script.js contains:

$(document).ready(function(){
    $("#adicionar").click(function(){
        alert ("A imagem foi clicada");
        $.post( "teste.php", {name: "John"} );
    });
});

And finally test.php:

<?php
if(isset($_POST['name'])){
    $name=$_POST['name'];
    echo $name;
} else {
    echo "O método POST falhou!";
}
?>

What is the error in this basic example of the $.post method?

  • 1

    Tell us you, any error on the console?

  • What did you expect to happen and what actually happened? You didn’t even handle the POST request response, so how did you conclude that it doesn’t work? Error?

  • I expected the post method to send the 'name' variable with 'John' value to the test.php page, which I recovered with the $_POST global variable and print the value of the variable. Instead, the variable 'name' is not in the global variable, and the Else of the if conditional is printed.

  • How did you verify that?

  • "prints the value of the variable" can you explain that phrase better? And, as @Andersoncarloswoss said, you are missing function(){} at the $.post

  • I expected the if parole to go to echo $name and entered echo "The post method failed". I didn’t put any Function in ajax because my interest is to perform php-database functions with the variable I want to pass by $.post

  • But how do you see O método post falhou? With ajax if you do not listen the answer does not happen anything on the page, ie PHP does not run on the page that is in the browser...

  • I see that it failed because there is no variable that the method should create. When invoking the method, I redirect to the url that should receive the post data.

Show 3 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.