I have a form I am trying to submit via ajax from PHPAcademy's tutorial found here
Basically the form needs to submit via ajax, simple enough. But when I try do that, it just opens the PHP file in the browser. PLEASE HELP!
here is the ajax code:
$('form.login_settings').submit(function(){
var that = $(this),
url = '../login_settings_submit.php',
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
I have tried using e.preventDefault();
but with no luck
I have also tried changing the initial function from
$('form.login_settings').submit(function(){
to
$('form.login_settings').on('submit', function(){
What am I doing wrong?
It's pretty easy friend:
Java Script Code:
$(function() {
$('form.login_settings').submit(function(e){
e.preventDefault();
var that = $(this),
type = that.attr('method'),
data = that.serialize()
$.ajax({
type: type,
url: '../login_settings_submit.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
});
use jQuery .serialize method to parametrize form data and write code inside
$(document).ready(function(){
//
}); or
$(function(){
//
});
and if you wanna check ajax error then you can use
,error : function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connected.
Please verify your network connection.');
} else if (jqXHR.status === 404) {
alert('The requested page not found. [404]');
} else if (jqXHR.status === 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.
' + jqXHR.responseText);
}
}
after success method. It's good to check ajax error always when you are in production.