jQuery: form and ajaxcall
I would like to make an ajax call on submit.
<form id="editMail" action="" method="post">
<input name="user_email" type="text" value="mail" maxlength="50" id="user_email" style="width:200px;">
<input name="submit" type="submit" id="submit_editMail" value="Ändra">
</form>
$('#editMail').submit(function() {
$.ajax({
type: "POST",
url: "misc/email/activate.php",
data: { action: 'edit', user_email: new_usermail },
success: function(r){
if(typeof(r.error) != 'undefined') {
if(r.error != ''){
alert(r.error);
}
}else{
alert('OK');
}
开发者_运维技巧});
});
But still nothing is happening, it doesnt do the ajax call but only refersh the page it's on. I tried adding onClick="return false;" to the submit button, but then nothing at all happens
Return false
in your handler. Otherwise, the POST request will be started, then the default form submit will happen. You can also use the preventDefault
function of the event object like this:
$('#editMail').submit(function(event) {
$.ajax({
type: "POST",
url: "misc/email/activate.php",
data: { action: 'edit', user_email: new_usermail },
success: function(r){
if(typeof(r.error) != 'undefined') {
if(r.error != ''){
alert(r.error);
}
}else{
alert('OK');
}
}
});
event.preventDefault();
});
Edit:
Make sure your script is not running before the page has finished loading. You may need to wrap your script in a ready
handler, like this:
$(document).ready(function() {
$('#editMail').submit(function(event) {
$.ajax({
type: "POST",
url: "misc/email/activate.php",
data: { action: 'edit', user_email: new_usermail },
success: function(r){
if(typeof(r.error) != 'undefined') {
if(r.error != ''){
alert(r.error);
}
}else{
alert('OK');
}
}
});
event.preventDefault();
});
});
You are missing the closing bracket group for your .submit();
Also you had unnecessary ); closing your 'success' function.
Also added the needed "return false" to prevent default submit actions.
corrected:
$('#editMail').submit(function() {
$.ajax({
type: "POST",
url: "misc/email/activate.php",
data: { action: 'edit', user_email: new_usermail },
success: function(r){
if(typeof(r.error) != 'undefined') {
if(r.error != ''){
alert(r.error);
}
}else{
alert('OK');
}
}
});
return false;
});
精彩评论