$('form#register').on('submit', function(e) { e.preventdefault(); userauth(this); // if done : // if fail : b }); $('form#login').on('submit', function(e) { e.preventdefault(); userauth(this); // if done : x // if fail : y }); function userauth(form) { console.log( $(form).serialize() ); var request = $.ajax({ url: 'process.php', cache: false, type: 'post', data: $(form).serialize() }); request.done( function (msg) { console.log(msg); }); request.fail(function(jqxhr, textstatus) { console.log(jqxhr, textstatus); }); } how check done/fail in submit handlers?
yes, know requires basic understanding of callback , asynchronous execution of javascript. i've read quite few books , tutorials don't seem it. maybe example here help.
simplest way add callback parameters:
function userauth(form, donecallback, failcallback) { console.log( $(form).serialize() ); var request = $.ajax({ url: 'process.php', cache: false, type: 'post', data: $(form).serialize() }); request.done(donecallback); request.fail(failcallback); } and call as:
$('form#register').on('submit', function(e) { e.preventdefault(); userauth(this, function(){ //i'm done }, function(){ //i failed }); }); keep in mind callback functions receive same arguments done , fail jquery. if don't want this, call them as:
request.done( function (msg) { donecallback(); }); request.fail(function(jqxhr, textstatus) { failcallback(); }); callback not difficult concept. keep in mind they're arguments ints, strings, regexps , on. they're happen function, they're callable.
edit answer comment
you can save value function in more 1 way:
var globalvariable; userauth(this, function() { var myvalue = 4; // local variable globalvariable = myvalue; window.explicitglobalvariable = myvalue; // same above, except haven't created variable beforehand implicitglobalvariable = myvalue; // i'm omitting var keyword, leak global scope }) the downside using global variables code smell in cases. there ways avoid them, require more knowledge need achieve give example.
Comments
Post a Comment