Playing with jquery for the first time, and I’m trying to get a simple AJAX set up working so I can better understand how things work. Unfortunately, I don’t know a whole lot. Here’s the HTML with the script:
<html>
<head>
<title>AJAX attempt with jQuery</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function ajax(str){
$("document").ready(function(){
$.post("ajaxjquerytest.php",str,function(){
$("p").html(response);
});
});
</script>
</head>
<body>
<input type="text" onchange="ajax(this.value)"></input>
<p>Age?</p>
</body>
</html>
And here is the PHP it’s talking to:
<?php
$age = $_POST['age'];
if ($age < 30)
{
echo "Young";
}
else if ($age > 30)
{
echo "Old";
}
else
{
echo "you're 30";
}
?>
Not sure if the
$.post()function has access to thestrparameter. Try this instead:This attaches an
onChangehandler to the input element after the DOM is completely loaded.Your approach should also work if you omit
$(document).ready(). But attaching the JS function to the element is more the way it is done with jQuery.Besides that, you only need to wrap code into
$(document).ready()that should be executed after the whole DOM tree is built. Your case, your are defining just a function. There is no need to use document ready as the function cannot be called until the DOM is loaded anyway.Read the documentation of
.post()!