Reputation: 591
I am facing issue, i f i am using ajax call, the return false not working.. and form submitted sucessfully.. I want that when i get response 1 form don't submit.. but on ajax request response form still submitting please help me..
here is code:
<form action="<?php echo base_url(); ?>do/add/review" method="post" name="dologin" id="dologinsubmitreview" onSubmit="return showpopupbox();">
function showpopupbox(){
var strs = $("form").serialize();
var autocompleteURL = "<?php echo base_url(); ?>grahak/save_record_session?rnd=" + Math.random() +"&sessiondata="+ $("form").serialize();
$.ajax({
url : autocompleteURL,
async: false,
cache: false,
method : "POST",
success : function(respd)
{
if(respd == 1){
$("#classiconpopupbx").show();
return false;
}
else {
return true;
}
}
});
}
Upvotes: 1
Views: 2268
Reputation: 93611
One way you can do this is to prevent the submit, always, then if your Ajax call returns true, post the form (and tell the code to allow it this time):
For starters, don't mix inline event handlers with jQuery. The jQuery way is better:
// Start by not allowing submit
var allowSubmit = false;
$('form').submit(function(){
var $form = $(this);
// Only run the ajax if this is not a "real" submit
if (!allowSubmit){
// do the ajax call
$.ajax({
url: ...
success: function(respd){
if(respd == 1){
$("#classiconpopupbx").show();
}
else {
allowSubmit = true;
$form[0].submit(); // important - bypass jQuery event handler
}
}
});
}
// Conditionally allow the form to submit
return allowSubmit;
});
Upvotes: 0
Reputation: 26180
You need to redesign your flow. Javascript is asynchronous, which means that the form is submitted LONG before the AJAX call is complete.
Instead, use jQuery on
to bind to the event, capture the event in the function, and run event.preventDefault()
immediately which will stop the form from submitting. THEN run your AJAX call.
In your AJAX success function, you'll need to decide what to do when it comes back "truthy". Without knowing more about your desired outcome, it's impossible to advise how to handle that piece.
<!-- remove the inline onsubmit script handler -->
<form action="<?php echo base_url(); ?>do/add/review" method="post" name="dologin" id="dologinsubmitreview">
// no-conflict safe document ready
jQuery(function($) {
// Bind to the form submit here, and call event.preventDefault immediately
$('#dologinsubmitreview').on('submit', function(event) {
event.preventDefault();
showPopUpBox(event);
}
function showpopupbox() {
var strs = $("form").serialize();
var autocompleteURL = "<?php echo base_url(); ?>grahak/save_record_session?rnd=" + Math.random() +"&sessiondata="+ $("form").serialize();
$.ajax({
url : autocompleteURL,
async: false,
cache: false,
method : "POST",
success : function(respd) {
if(respd == 1){
$("#classiconpopupbx").show();
} else {
// Do what you need to do here if the AJAX is true
}
}
});
}
});
Upvotes: 1