I have a simple html form and jquery. and all I want to run ajax function of jquery, but it always gives error response.
my code is
<html>
<head>
<script src="jquery-1.8.1.min.js" type="text/javascript"></script>
</head>
<body>
<form action="" method="post" id="messageForm">
<table border=1>
<tr><td>Name</td><td align=right><input type="text" name="from" /></td></tr>
<tr><td>Surname</td><td align=right><input type="text" name="to" /></td></tr>
<tr><td colspan=2>Message</td></tr>
<tr><td colspan=2><textarea name="message" rows=10 cols=50> </textarea></td></tr>
<tr><td colspan=2 align=right><input type="submit" value="Send" /></td></tr>
</table>
</form>
<span id="textres">
</span>
<script lang="javascript">
$("#messageForm").submit(function(event) {
$.ajax({
url: "ajax.php",
data: $("#messageForm").serialize(),
cache: false,
error: function(XMLHttpRequest, textStatus, errorThrown){
//console.log or alert error
alert("textStatus:"+textStatus+",errorThrown:"+errorThrown+",XMLHttpRequest:"+XMLHttpRequest);
},
success: function(html){
alert("Data Loaded: "+html);
}
});
});
</script>
</body>
</html>
and, it never runs success event. when I look google chorome console, there is no error and if I copy the code of
$.ajax({
url: "ajax.php",
data: $("#messageForm").serialize(),
cache: false,
error: function(XMLHttpRequest, textStatus, errorThrown){
//console.log or alert error
alert("textStatus:"+textStatus+",errorThrown:"+errorThrown+",XMLHttpRequest:"+XMLHttpRequest);
},
success: function(html){
alert("Data Loaded: "+html);
}
});
to console, it works well. what should I do to run a simple jquery ajax function ?
the
submit()means the page will be refreshed, try this :