Skip to content

Instantly share code, notes, and snippets.

@jcblw
Created June 13, 2012 00:18
Show Gist options
  • Save jcblw/2920965 to your computer and use it in GitHub Desktop.
Save jcblw/2920965 to your computer and use it in GitHub Desktop.
send form data via ajax to php script
(function(){
/* Script that compiles values of form
* the sends them via ajax to php script
* php script will send back json after validation process
* use the console logs for debugging
*/
// you might need a better selector -> select your form
var form = $('form'),
// compile all values
compile = function(){
var values = [], selected;
form.find('input').each(function(){
values.push($(this).attr('name') + '=' + $(this).val());
});
form.find('select').each(function(){
selected = $(this).find('option:selected');
values.push($(this).attr('name') + '=' + selected.val());
});
return values.join('&');
},
//send values via ajax
send = function(){
var compiled_values = compile(),
loading = $('.loading_reg');
form.find('input').add('select').removeClass('error_');
//hide the error message
//errorMsg.hide();
//loading show
//loading.show();
$.ajax({
url : 'path-to/mail-script.php',
dataType: 'json',
data: compiled_values,
type: 'POST',
error: function(err){
//console.log(err);
//Show an error prompt
},
success: function(res){
//console.log(res);
// loading hide
//loading.hide();
//console.log(res);
if(res.status === 'success'){
// replace form content with success msg
form.html(res.message);
}else{
var i = 0;
while(i < res.message.length){
$('.' + res.message[i]).addClass('error_');
i += 1;
}
// show the error
//errorMsg.show();
}
}
});
return false;
};
// attach to the submit button
form.find('input[type=submit]').bind('click', function(){
send();
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment