Prevent Default is not working - javascript

I have checked around here and none of these solution on here fix my issue.
I cannot seem to get the preventDefault() to work. Code below:
Jquery:
$("#changepassword").submit(function(event) {
event.preventDefault(); // stop normal form submission
$.ajax({
url: "changePassword.php",
type: "POST",
data: $(this).serialize(), // you also need to send the form data
dataType: "html",
success: function(html) {
$("#s-window").append(html);
}
});
});
HTML:
<div id="s-window">
<form id="changepassword" action="changePassword.php" method="POST">
<input type="password" name="currentPassword" placeholder="Current Password"/>
<input type="password" name="newPassword" placeholder="New Password"/>
<input type="password" name="confirmPassword" placeholder="Confirm Password"/>
<input class="button" type="submit" value="Change Password" />
</form>
</div>
There are no errors on my conosle. The changePassword.php works as it is supposed to. But rather than updating my #s-window it redirects me to the changePassword.php page
How can I recode this to make everything happen on the page?

You need to wait until document is ready:
$(document).ready(function(){
$("#changepassword").submit(function(event) {
event.preventDefault(); // stop normal form submission
$.ajax({
url: "changePassword2.php",
type: "POST",
data: $(this).serialize(), // you also need to send the form data
dataType: "html",
success: function(html) {
$("#s-window").append(html);
}
});
});
});

You can try this way using return false;, if you have any confusion see here more event.preventDefault() vs. return false
$("#changepassword").submit(function(event) {
//event.preventDefault(); // stop normal form submission
return false;
});

At least in IE, event is a global variable (as per Is 'event' a reserved word in JavaScript?). This may not be the cause of your problem, but it might be a good idea to change your naming nonetheless.

In you ajax call change dataType: "html" to dataType: "script"

Related

JQuery toggle() - Element only displayed after JQuery submit function

I'm trying to display a loading gif at the beginning of a JQuery submit function, but the gif is only displayed after the submit function ends. (Each of the alerts are displayed before the gif)
For the ajax, I currently set it to always respond with an error saying "No video chosen".
JQuery
$("#myForm").submit(function(e){
e.preventDefault();
$("#loading_gif").toggle();
alert('The gif should be displayed');
var Fdata = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "/send_video",
data: Fdata,
processData:false,
contentType: false,
async:false,
cache: false,
success: function(data){
alert('success');
//commented or else the gif is never displayed
//$("#loading_gif").toggle();
},
error: function(error){
alert('error');
e = document.getElementById("error");
e.innerHTML = JSON.parse(error.responseText);
//commented or else the gif is never displayed
//$("#loading_gif").toggle();
}
});
});
HTML
<div id="error"></div>
<form id="myForm" action="/" method="post" enctype="multipart/form-data">
<input id="video" type="file" name="video">
<input id="submit" type="submit" value="Send">
<img id="loading_gif" style="display:none" src="mysite/img/loading.gif">
</form>
I don't think $.ajax is the problem, because I removed it and still didn't work.
I already tried to separate toggle() from the rest of the submit by doing this:
$("#submit").click(function(){
$("#loading_gif").toggle();
$("#myForm").submit();
});
But it changed nothing.
Thanks a lot.
You don't want async:false remove this and your problem should go away.

Save input data and add icon inside textbox after ajax success

I want to save each input text by its own id and append the icon inside that input after ajax succeed.
HTML:
<div class="form-group has-feedback autosave">
<input type="text" class="form-control" id="fname" name="fname" placeholder="Your name"/>
<i class="form-control-feedback"></i>
</div>
<div class="form-group has-feedback autosave">
<input type="text" class="form-control" id="lname" name="lname" placeholder="Your lastname"/>
<i class="form-control-feedback"></i>
</div>
Javascript:
$(document).on('blur', '.autosave input', function(e) {
//when input inside .autosave was blurred
var _id=$(this).attr('id');//id
var _val=$(this).val();//value
$.ajax({
type: 'POST',
url: 'save.php',
data: {id:_id,val:_val},//send id and val
dataType: 'json',
success:function(data){
$(_id).addClass('fa fa-check');//addclass when succeed
console.log(data);//debug
},//success
});//$.ajax
});
I plan to display the check icon inside each input when the submit succeed. So the idea is getting the id and val from each input. And send it to db via ajax. After the response, that input will be update with icon with specific id.
You don't need to use the element's id - you can store the reference to this which the function runs under and use that within the $.ajax success handler. Try this:
$(document).on('blur', '.autosave input', function(e) {
var $el = $(this);
$.ajax({
type: 'POST',
url: 'save.php',
data: {
id: $el.prop('id'),
val: $el.val()
},
dataType: 'json',
success: function(data) {
$el.addClass('fa fa-check');
console.log(data); //debug
},
});
});
Finally, after a big trying. I found the solution. Thanks to #RoryMcCrossan who gave me the starting idea.
Javascript
...
success: function(resp) {
$this.closest('.form-line').find('i').removeClass('fa fa-check').addClass('fa fa-check');
$this.closest('.form-group div.form-line').addClass('success has-success');
console.log(resp); //debug
},
The only different is the process after success. It looks messy, but working. If you have any shorter pattern would be appreciated.

Running an Ajax click event on a div added by another Ajax click event

For some reason I can't run the Ajax click on a div that was just added by another ajax click event on the exact same page.
Both ajax requests use the same request page, but contain a different data string.
These are my two Ajax functions
$(document).ready(function(){
$('#log_login').click(function(event){
event.preventDefault();
var email=$("#log_email").val();
var login=$("#log_login").html();
var dataString = 'email='+email+'&login='+login;
$.ajax({
type: 'POST',
url: '$language_rewrite/$administrator_login/forgotpassword',
data: dataString,
beforeSend: function(){
$("#login-msg").hide();
$("#log_login").html('$translate_login_8...');
},
success: function(html){
if(html){
if(html.indexOf("$forgot_translate_1") > -1){
$("#p_log_email").html('$forgot_translate_1');
$("#log_verify_code").html('<input id="log_code" type="text" name="email" placeholder="$admin_f_subject"/><br>');
$("#log_verify_btn").html('<div id="log_verify" name="login" class="standard-button">$admin_verify_btn</div>');
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
});
});
});
$(document).ready(function(){
$('#log_verify').click(function(event){
event.preventDefault();
var code = $("#log_code").val();
var verify = $("#log_verify").html();
var dataStringTwo = 'code='+code+'&verify='+verify;
$.ajax({
type: 'POST',
url: '$language_rewrite/$administrator_login/forgotpassword',
data: dataStringTwo,
beforeSend: function(){
$("#login-msg").hide();
$("#log_verify").html('$admin_verify_btn...');
},
success: function(html){
if(html){
if(html.indexOf("1") > -1){
$("#log-verify").html('<div id="log_login2" name="login" class="standard-button">FINISHED</div>');
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
});
});
});
This is the HTML code that is being changed
<div id="log_verify_code">
<input id="log_email" type="text" name="email" placeholder="<?php echo $translate_login_2; ?>"/><br>
<input id="log_code" type="hidden" value=""/>
</div>
<div id="log_verify_btn">
<div id="log_login" name="login" class="standard-button"><?php echo $translate_login_8; ?></div>
<input id="log_verify" type="hidden" value=""/>
</div>
The first Ajax functions works perfectly, and it changes the input field, however when I press the second button nothing happens. Not even an error, or a PHP error. Nothing. How come?
Event handlers are bound only to existing elements. For future elements you must use delegated events and bind to existing ancestor, or for instance the document itself.
$(document).on("click", ".future-elem", function() {
// code here
});
Source: $.on - read: direct and delegated events
EDIT: just saw this was already being commented

input form does not work when call it from jquery ajax

Sorry but i am totally newbie for ajax and jQuery if i am asking ridiculous question.
Basically i've a form like below;
<form id="login_form" >
<input type="text" id="inputEmail" name="username">
<input type="password" id="inputPassword" name="password">
<div id="MyDynamicDiv"></div>
<button id="signin" name="signin" type="submit">button</button>
</form>
<script>
$("#login_form").submit(function() {
if ($("#login_form").valid()) {
$('.messagebox').slideUp('slow');
var data1 = $('#login_form').serialize();
$("button").button('loading');
$.ajax({
type: "POST",
url: "login/login.php",
data: data1,
dataType: 'json',
success: function(msg) {
if (msg.result == 12) {
$('#MyDynamicDiv').load('captcha.php');
}
if (msg.result == 1) {
$('.messagebox').addClass("success-message");
$('.message').slideDown('slow');
$('#alert-message').text("....");
$('#login_form').fadeOut(5000);
window.location = "members.php"
} else { return false;}
</script>
and my captcha.php is
<input type="text" name="captcha_code">
<img id="captcha" src="/test/securimage/securimage_show.php">
[ Different Image]
also login/login.php includes
echo json_encode( array('result'=>12));
I am ok to call captcha.php and show up on the page however, form does not work for captcha input. Should i call it in different way that i could not find out anywhere what i should do exactly.
Edit:
it seems input value of captcha_code does not send/post correctly. If i use the captcha.php code embedded into login form, than it works.
Thanks in advance,
It appears your captcha input is outside of the <form> element, therefore it will not be included in the POST data when you serialize() the form. Move the input inside the form element.
You seem to be missing some closing parenthesis and braces.
Doing return false from the success function does nothing because of the async nature. Instead you should return false from the submit event, or prevent default.
Corrected code with commented changes (assuming you've moved the captcha input):
$("#login_form").submit(function (e) { // capture event
e.preventDefault(); // always prevent the form from submitting
if ($("#login_form").valid()) {
$('.messagebox').slideUp('slow');
var data1 = $('#login_form').serialize();
$("button").button('loading');
$.ajax({
type: "POST",
url: "login/login.php",
data: data1,
dataType: 'json',
success: function (msg) {
if (msg.result == 12) {
$('#MyDynamicDiv').load('captcha.php');
}
if (msg.result == 1) {
$('.messagebox').addClass("success-message");
$('.message').slideDown('slow');
$('#alert-message').text("....");
$('#login_form').fadeOut(5000);
window.location = "members.php"
}
} // was missing
}); // was missing
} // was missing
}); // was missing
For future debugging, remember to check the console (F12) for errors, and indent your code because it makes missing braces more obvious. You can use the TidyUp feature of JSFiddle to auto indent it.

Disabling button on ajax submit

I have this button that I want to disable when my ajax is running, and then being enabled again once it's done.
My HTML:
<form name="send" class="stacked form-send-disable" id="form">
<label for="senderID">Your phone number here (senderID)</label>
<input type="tel" name="senderID" id="senderID" autofocus="on" class="input-1-2" placeholder="Your number" maxlength="9">
<label class="error" id="senderID_error" for="senderID">Please enter your own number here.</label>
<label for="recipient" id="recipient_label">Your recipient(s)</label>
<input type="text" name="recipient" id="recipient" class="input-1" maxlength="50" placeholder="e.g 748930493 - add multiple numbers by using a comma ' , '.">
<label class="error" id="recipient_error" for="recipient">You need to enter at least one number here.</label>
<label for="message">Write your message</label>
<textarea type="text" name="message" class="input-1" placeholder="(Write something clever..)" id="message"></textarea>
<label class="error" for="message" id="message_error">You can't send empty messages.</label>
<input type="submit" name="submit" class="button btn btn-green block disabled-btn" id="submit_btn" value="Send the message(s)">
</form>
ajax:
<---- Some form validation going on up here ------>
var dataString = 'recipient=' + recipient + '&message=' + message + '&senderID=' + senderID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$('#send-message').append("<div id='feedback'></div>");
$('#feedback').html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.append("")
.hide()
.fadeIn()
.delay(4000)
.fadeOut();
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
});
}
});
return false;
});
I tried to do the following in my document:
Jquery:
$('#form').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
But nothing happens. I guess I have to somehow call this within the ajax, so that it applies to the button that way?
Thanks in advance.
UPDATE
$(':submit', this).prop('disabled', true);
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$('#send-message').append("<div id='feedback'></div>");
$('#feedback').html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.append("")
.hide()
.fadeIn()
.delay(4000)
.fadeOut();
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
}).always(function(){$(':submit', this).prop('disabled', false);});;
}
I updated with the above code (big thanks to A.Wolff), and my ajax request still works, however there is no change on the button, which i assume is because of lack of css for this particular state of the button, how do I go about this?
Thanks to the other replies, i will try them out.
I made a working demo that disables the form whilst the ajax request is happening. I hope its of some use. See: http://jsfiddle.net/EWkpR/
$("#form").on("submit", function(event) {
//stop the default submission:
event.preventDefault();
//create an alias to this form
$form = $(this);
//create the feedback element
$feedback = $("<div id='feedback'>Please wait...</div>");
$form.before($feedback);
//validate the form:
var valid = true;
/*[some form validation here]*/
//use jQuery's serialize to build the form submission params:
var dataString = $(this).serialize();
console.log(dataString);
//check if invalid
if(!valid){
//not valid. tell the user
$feedback.html("<p>Some message about invalid fields!</p>");
} else {
//valid.
$form.disable();//disable the form;
//do the ajax
$.ajax({
type: "POST",
url: "/index.php/sms/sender/",
data: dataString,
success: function() {
$feedback
.html("<p><i class='fa fa-check fa-2x'></i> Your message has been succesfully sent!</p>")
.fadeIn()
.delay(4000)
.fadeOut("normal",
function(){$form.enable();}//callback to fade the form back in
);
$.ajax({
type: "POST",
url: "/index.php/pipit/message_sent",
data: dataString,
});
}
});
}
return false;
});
//plugin function to disable form fields
$.fn.disable = function(){
this.fadeTo(1,.5);
this.find("input").attr("disabled", true);
};
//plugin function to enable form fields
$.fn.enable = function(){
this.fadeTo(1,1);
this.find("input").removeAttr("disabled");
};
You can set the button as disabled before the AJAX runs and re-enable it once the ajax has completed.
$.ajax({
beforeSend: function() {
$("input[type=submit]", $("#form")).attr("disabled", "disabled");
},
...
complete: function () {
$("input[type=submit]", $("#form")).removeAttr("disabled");
}
});
Edit: I notice there is a class on the button disabled-btn if this needs to be added and removed as the button is disabled/re-enabled then you can do this by chaining the following to the above:
.addClass("disabled-btn");
...
.removeClass("disabled-btn");
I would assume if this is the case then the class should be removed from the actual element to start with.
You could use:
//using allias for nested ajax:
var _self = this;
$(':submit', _self ).prop('disabled', true);
//your nested ajax request
$.ajax(...).always(function(){$(':submit', _self ).prop('disabled', false);});

Categories

Resources