javascript - Retrieving php variables from ajax call but not working
960
when I use this code nothing and call the ajax nothing happens and I was looking at some online forums saying I need to use json encode to pass variables over ajax but it just echos it at the top of the webpage.
AjaxTesting
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#test").click(function(){
$.ajax({
event.preventDefault(),
url:'ajaxUser.php',
type:'POST',
dataType: 'json',
success:function(data){
alert(data.id);
}
)};
});
</script>
</head>
<body>
<form method="post">
<input name="userName">
<input name="submit" type="button" value="Submit" id="test">
</form>
</body>
</html>
ajaxUser
<?php
echo json_encode(array('id' => 123, 'messageid' => "test"));
?>
Answer
Solution:
You don't have
event
parameter called in click function. Don't callpreventDefault()
within ajax function ,also you need to code your js withindocument.ready()
if you want to write in header element !!Should work
Answer
Solution:
The php code needs to be in a different file named
AjaxTesting.php
and you never call the functionpost()
in the javascript. So we can call it inside a form submit event handlerTry adding:
Also note that the html page needs to be running on the same server and not from local file for ajax to work