KiiroSora09
KiiroSora09

Reputation: 2287

Run an ajax script before submitting

Good Day.

I'm having a problem with running a ajax call before a form submits. I'm just a newbie web developer so please bear with me.

My code is like this:

$( function() {
 $('#formname' ).submit( function() {
  $.post( 'validation.php', $( this ).serialize(), function( data ) {
   if( data == 'something' ) return true;
   else return false;
  } );
 }
} );

This code is not working for me. Is there something wrong with the code or are there other ways to attain this.

Thanks in advance,

Upvotes: 0

Views: 1065

Answers (3)

erimerturk
erimerturk

Reputation: 4288

you can define click event your submit button. and then when you click it, first do your post and then submit form.

html :

<form id="target" action="destination.html">
  <input type="text" value="Hello there" />
  <input type="submit" value="Go" />
</form>
<div id="other">
  Trigger the handler
</div>

js:

  $('#other').click(function() {

   $.post( 'validation.php', $('#target').serialize(), function( data ) {
     if( data == 'something' ) {
         $('#target').submit();
     }
  });
 });

Upvotes: 1

Niels
Niels

Reputation: 49929

You can do this, but it's very ugly and you really don't want this.

$( function() {
 $('#formname' ).submit( function() {
    var returnValue;
  $.post( {
     async: false, // This makes it possible
     url: 'validation.php', 
     data: $( this ).serialize(), 
     success: function( data ) {
         if( data == 'something' ) returnValue = true;
         else returnValue = false;
     }
  } );
  return returnValue;
 }
} );

But why do you want this? Because you can just do another Ajax function and be ready. And after you done your ajax requests you can do a document.location= "newlocation.html". Because now your application will wait untill you ajax request is done. And if your ajax request will take 10 seconds, people can't use your page for 10 seconds.

If you just always return false and do the Ajax request where you will handle the form. And oncomple you do the document.location, will be a better option. So your application will not get stuck.

Upvotes: 2

ThiefMaster
ThiefMaster

Reputation: 318518

You need to return false; in the submit handler, not inside the AJAX callback. However, even better is changing the function to accept a parameter e and then calling e.preventDefault(); even before doing the AJAX call. If the validation succeeded, use $('#formname')[0].submit(); to actually submit the form without calling your submit handler again.

PS: Better use a plugin such as the excellent jQuery form plugin and the validation plugin.

Upvotes: 1

Related Questions