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?
Tell us you, any error on the console?
– BrTkCa
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?
– Woss
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.
– Guilherme
How did you verify that?
– Woss
"prints the value of the variable" can you explain that phrase better? And, as @Andersoncarloswoss said, you are missing
function(){}
at the$.post
– Sergio
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
– Guilherme
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...– Sergio
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.
– Guilherme