
Untitled
By: a guest on
May 8th, 2012 | syntax:
JavaScript | size: 1.66 KB | hits: 24 | expires: Never
// If I click the submit-button, the data should be send via ajax. Opening of the file that is set in the action-attribute in the form-element should be prevented. But it doesn't prevent, it actually opens the site. What did I do wrong here?
//Javascrpt (jQuery)
function ajaxForm(action, field, value) {
var url, data, formId;
if (field && value) {
data = field + '=' + value;
}
if (action === 'regForm') {
formId = '#' + action;
url = $(formId).getAttr('action');
if (!field && !value) {
data = $(formId).serialize();
}
}
hideshow('loading', 1);
error(0);
success(0);
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function (msg) {
if (parseInt(msg.status, 10) === 1) {
success(1, msg.txt);
} else if (parseInt(msg.status, 10) === 0) {
error(1, msg.txt);
}
hideshow('loading', 0);
}
});
}
$('#regForm').submit(function (e) {
ajaxForm('regForm');
e.preventDefault();
});
// HTML
<form id="regForm" action="functions/register.php" method="post">
<table>
<tr>
<td><label for="username">Username</label></td>
<td><input name="username" id="username" type="text"></td>
</tr>
<tr>
<td><label for="email">E-Mail</label></td>
<td><input name="email" id="email" type="text"></td>
</tr>
<tr>
<td><label for="password">Passwort</label></td>
<td><input name="password" id="password" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Registrieren"><img id="loading" src="img/ajax-loader.gif" alt="Laden..."></td>
</tr>
</table>
</form>