Created
June 14, 2016 12:07
-
-
Save sujeetkv/04e912d5e4177621a0eb519f3f5fc940 to your computer and use it in GitHub Desktop.
Ajax Submit Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* ajax submit example */ | |
$(function(){ | |
// example 1 (only POST) | |
$('#form-id').submit(function(e){ | |
e.preventDefault(); | |
var frm = this; | |
var ajax_opts = {}; | |
ajax_opts.url = $(frm).attr('action'); | |
ajax_opts.type = 'post'; | |
ajax_opts.cache = false; | |
if(window.FormData){ | |
ajax_opts.data = new FormData(frm); | |
ajax_opts.processData = false; | |
ajax_opts.contentType = false; | |
}else{ | |
ajax_opts.data = $(frm).serialize(); | |
} | |
ajax_opts.success = function(result){ | |
// do stuff | |
}; | |
$.ajax(ajax_opts); | |
}); | |
// example 2 | |
$('#form-id').submit(function(e){ | |
e.preventDefault(); | |
var frm = this; | |
var ajax_opts = {}; | |
ajax_opts.url = $(frm).attr('action'); | |
ajax_opts.type = $(frm).attr('method'); | |
ajax_opts.cache = false; | |
if(ajax_opts.type.toUpperCase() == 'GET'){ | |
ajax_opts.url += ((ajax_opts.url.indexOf('?') > -1) ? '&' : '?') + $(frm).serialize(); | |
}else{ | |
ajax_opts.data = $(frm).serialize(); | |
} | |
ajax_opts.success = function(result){ | |
// do stuff | |
}; | |
$.ajax(ajax_opts); | |
}); | |
// example 3 | |
/* | |
Use jQuery form plugin | |
http://malsup.com/jquery/form/ | |
https://github.com/malsup/form/ | |
*/ | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment