Hey all, I cannot seem to get a simple ajax working between a php page and jquery. I have followed a few tutorials. but having trouble actually understanding what is actually going on.
Javascript (JQuery)
$(function(){
$('#trigger').click(function(){
askajax;
});
function askajax(){
$.post("ask.php",{ question: "canuseeme" } ,function(data)
{
if(data=='yes')
{
alert("answer is yes");
}
else
{
alert("answer is no");
}
});
}
});
The PHP:
if($_POST['question']){
echo "yes";
} else {
echo "no";
}
Any ideas guys?
EDIT: THANKS TO @Jacob
$('#trigger').click(function(){
alert("doing ajax"); // THIS SHOWS
$.post("as开发者_Python百科k.php",{ question: "canuseeme" }, function(data)
{
if(data=='yes')
{
alert("answer is yes"); // THIS DOESNT
}
else
{
alert("answer is no"); // THIS DOESNT
}
});
});
This'll work:
$('#trigger').click(askajax);
Or this:
$('#trigger').click(function() {
askajax();
});
But I prefer to do it this way:
$(function(){
$('#trigger').click(function(){
$.post("ask.php",{ question: "canuseeme" } ,function(data)
{
if(data=='yes')
{
alert("answer is yes");
}
else
{
alert("answer is no");
}
});
});
});
Reason being that you don't ever use the askajax
function again, and it will only be defined in the ready
function's scope, so why even bother with a standalone function definition? Just use an anonymous function and be done with it. :)
On line 3, change askajax;
to askajax();
精彩评论