2010-09-03 15 views
12

Il mio obiettivo è: Quando per viene presentato:forma jQuery presentare

  • una convalida sulla forma è fatta: OK
  • un ajax è chiamato a vedere che il nome utente e la password corrispondono: OK
  • se non corrispondono, visualizza un errore: OK
  • se corrispondono, allora davvero inviare il modulo: NO T OK.

Il problema è che non posso inviare il modulo poiché è presente un evento jquery submit!

function form1Submit() { 
var username=$('#username').val(); 
var password=$('#password').val(); 
if (username.length<2) { 
    return false; 
} 
if (password.length<2) { 
    return false; 
} 
$.post("check.php", { username: username, password:password }, function(data) { 
    if (data=="ko") { 
     alert('bad password'); 
     return false; 
    } else { 
    //to be done here ! 
    } 
}); 
    return false; 
} 
function init() { 
    $('#form1').submit(function(){ 
     return form1Submit(); 
    }) 
} 
$(document).ready(function(){ 
    init(); 
}) 

risposta

9

è possibile chiamare il nativo pubblica un evento, in modo da fare questo:

$('#form1').submit(form1Submit); 

Poi, nel tuo post richiamata fare questo:

$.post("check.php", { username: username, password:password }, function(data) { 
    if (data=="ko") { 
     alert('bad password'); 
    } else { 
     this.submit(); 
    } 
}); 

Il this.submit() non sta chiamando lui jQuery .submit() funzione di trigger, ma piuttosto la funzione nativa <form>.submit().

1

Il return false sta bloccando l'azione di invio modulo predefinito. Hai sia-return true dalla funzione form1Submit() di lasciare che il modulo predefinito presentare azione Fare il suo lavoro, o per aggiungere un altro $.post() all'interno del else che presenta i dati al form in modo asincrono, se il tuo intento era quello di farlo utilizzando ajaxical poteri.

1

Il problema è che form1Submit restituisce sempre false.

1
function form1Submit(ev, ok) { 

    ev.stopPropagation(); 

    ok = (typeof ok != 'undefined') ? ok : false; 

    if (ok) 
    return true; 

    var username=$('#username').val(), 
     password=$('#password').val(), 
     selfForm = this; 

    if (username.length < 2) 
    return false; 

    if (password.length < 2) 
    return false; 

    $.post("check.php", { username: username, password:password }, function(data) { 
    if (data=="ko") { 
     alert('bad password'); 
    } else { 
     $(selfForm).trigger('submit', [true]); // again submit but with ok parameter 
    } 
    }); 

    return false; 
} 

function init() { 
    $('#form1').bind('submit', form1Submit); 
} 

$(document).ready(function(){ 
    init(); 
}) 
+0

'$ (selfForm) .trigger ('submit', [true]);' sembra fare il trucco. Sostituisci semplicemente selfform con l'ID del modulo e sarai tutto pronto. Ad esempio: '$ ('# frm_test'). Trigger ('submit', [true]); ' – Devner

Problemi correlati