my html goes like this ,
<form name="postcontent" id="postcontent">
<input name="postsubmit" type="submit" id="postsubmit" value="POST"/>
<textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>
The jquery code is as follows
$("#postcontent").submit(function(e) {
$.ajax({
type:"POST",
url:"add_new_post.php",
data:$("#postcontent").serialize(),
beforeSend:function(){
$(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
},success:function(response){
//alert(response);
$("#return_update_msg").html(response);
$(".post_submitting").fadeOut(1000);
}
});
});
When I click on the submit button , my ajax request is not working , it looks as if the control is being passed to the JQuery submit function , but the ajax request is not executing/working properly,what is wrong ?
put the event handler function inside $(document).ready(function(){...}). it shall work now
also add preventDefault() to restrict page refreshing
$(document).ready(function() {
$("#postcontent").submit(function(e) {
e.preventDefault();
$.ajax({
type : "POST",
url : "add_new_post.php",
data : $("#postcontent").serialize(),
beforeSend : function() {
$(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
},
success : function(response) {
alert(response);
$("#return_update_msg").html(response);
$(".post_submitting").fadeOut(1000);
}
});
e.preventDefault();
});
});
try this code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<Script>
$(document).ready(function(){
$("#postcontent").click(function(e) {
$.ajax({type:"POST",url:"add_new_post.php",data:$("#postcontent").serialize(),beforeSend:function(){
$(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
},success:function(response){
//alert(response);
$("#return_update_msg").html(response);
$(".post_submitting").fadeOut(1000);
}
});
});
});
</script>
<form name="postcontent" id="postcontent">
<input name="postsubmit" type="button" id="postsubmit" value="POST"/>
<textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>
you need to prevent the default behavior of your form when submitting
by adding this:
$("#postcontent").on('submit' , function(e) {
e.preventDefault();
//then the rest of your code
}
Try this
$("#postcontent").submit(function() {
return false;
};
$('#postsubmit').click(function(){
// your ajax request here
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With