Disabling button on ajax submit - javascript

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);});

Related

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.

Response from Servlet page is shown in new page

I am using Ajax and jQuery to submit a dynamic form.
It works fine, but the response from Servlet is shown in a new page.
function call(formid) {
alert(formid);
var form = $(formid); // id of form tag
form.submit(function () {
$.ajax({
type: form.attr('method'), //post method
url: form.attr('action'), //ajaxformexample url
data: form.serialize(), // serialize input data values
success: function (data) {
var result=data;
$('#content').html(result); //showing result
}
});
return false; // not refreshing page
});
}
How I can show response from Servlet in same page?
(out.println("<br/>Massage = "+message+"<br/>"););
You are experiencing this because you are not stopping what a form submit does:
So, according to .submit( handler ) change your line:
form.submit(function () {
to:
form.submit(function (e) {
e.preventDefault(); // stop form submit and do your ajax call
UPDATE
According to your comment I suggest you to try the following code:
function submitFrm(obj, e) {
e.preventDefault();
var form = $(obj).closest('form'); // id of form tag related to the current button
var formid = form.attr('id');
alert(formid);
$.ajax({
type: form.attr('method'), //post method
url: form.attr('action'), //ajaxformexample url
data: form.serialize(), // serialize input data values
success: function (data) {
var result=data;
$('#content').html(result); //showing result
}
});
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form id="formid">
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
<input type="submit" value="Submit" onclick="submitFrm(this, event);">
</form>

How to call javascript validate function before form submit on an ajax call

Here is my validate() function, returns either true or false.
My problen is i want to call ajax submit form code only if validate() returns true, otherwise it will show the alert with error messages for not valid data and stay in page Without submitting the form , without using ajax I know that i can use if true return document.form2.submit();but in my case it doesn't work, Please help!
Ajax Code :
$("#form2").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: "addv.php",
type: 'POST',
data: formData,
success: function (data) {
$('.fv').html(data).hide().fadeIn(500).delay(1000).fadeOut(500);
},
contentType: false,
processData: false
});
return false;
});
javascript function :
function validate()
{
var m=document.getElementById("mat").value;
var c=document.getElementById("kilo").value;
var v=true;
if(!isNaN(m))
{
alert("matricule doit etre une chaine !");
document.getElementById("mat").value=null;
v=false;
}
if(isNaN(c))
{
alert("kilométrage doit etre un entier !");
document.getElementById("kilo").value=null;
v=false;
}
return v;
}
Form :
<form enctype="multipart/form-data" class="form2" id="form2">
<label >Matricule</label></br>
<input type="text" name="mat"></br>
<label>kilométrage</label></br>
<input type="text" name="kilo"></br>
<label>Marque</label> </br>
<select name="mar" id="mar">
<?php
while($res=mysqli_fetch_array($req1))
{
echo "<option> $res[0] </option>";
}
?>
</select>
<label>Propriétaire Cin</label> </br>
<select name="pro" id="prop" onchange=fn()>
<?php
while($res=mysqli_fetch_array($req2))
{
echo "<option> $res[0] </option>";
}
?>
</select>
<label>Nom et Prénom</label> </br>
<input type="text" disabled id="propr"></br>
<label>Photo</label> </br></br>
<input type="file" name="img" id="img"style="color:red;"></br></br>
<input type="submit" value="Ajouter">
<b><p class="fv" style="color:red" align="center"></p></b>
</form>
You can use preventDefault to prevent submit of form. And use condition if validate returns true then use Ajax other case show alert
$("#form2").submit(function(e){
e.preventDefault();
if(validate()){
var formData = new FormData($(this)[0]);
$.ajax({
url: "addv.php",
type: 'POST',
data: formData,
success: function (data) {
$('.fv').html(data).hide().fadeIn(500).delay(1000).fadeOut(500);
},
contentType: false,
processData: false
});
} else {
alert('error');
}
});
You can do something like this
$.ajax({
url : 'my_action',
dataType: 'script',
beforeSend : function(xhr, opts){
if(!validate()) //just an example
{
xhr.abort();
}
},
complete: function(){
console.log('DONE');
}
});
You can check if your data is valid or not and based on it abort ajax request.
To answer your question, when I submit my forms via ajax I tend not to use submit button.
<input type="submit" value="Ajouter">
to
<input type="button" id="process_form" value="Ajouter">
then you can add some JS functions like
$('#process_form').click ( function (e) {
if(validate){
// AJAX HERE
}else{
// return errors
}
});
That should get you moving in the right direction. In your case the form won't submit because you have not supplied a method nor an action. When using Ajax these aren't required though.
Try This
$("#userFrm input,#userFrm select").each(function(index, value){
if(value.checkValidity()==false){
alert("error message");
return false
}
});
// AJAX HERE

not able to submit form without page reloading

I have the following code that i wish to use to submit form without reloading the page, but it reloads the entire page and when checked in console the script.php page is also not getting executed.
Code on index.php page
<script>
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
</script>
<form method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>
code on script.php page
<?php
$name=$_POST['name'];
echo $name;
?>
Can anyone please tell how i can submit the form without reloading the page and also display the result from script.php page on index.php page
update your function. pass event object in function. and use event.preventDefault() to prevent default submit action.
$(".submit").click(function(e) {
e.preventDefault();
try this
<script>
$(function() {
$(".submit").click(function(event) {
event.preventDefault();
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
OR
<input type="button" class="submit" />Submit
You need to send the data from the script.php page back to your index.php page. Swich out the little bit of ajax for this:
$.ajax({
type: "POST",
url: "script.php",
data: "datastring",
dataType: "json",
success: function(dataType){
$("#result").html(dataType);
}
});
In your script.php:
<?php
$name=$_POST['name'];
echo json_encode($name);
?>
Do not mix form submit and button click.
If you are a click event of button then use type="button" and if you are doing $("form").submit() then use type="submit".
Also check for
$(".submit").click(function(e) {
e.preventDefault();
and check your ajax post data , do
$.ajax({
type: "POST",
url: "script.php",
//changes made here
data: { name: $("#name").val()},
//changes made here. you have not written response
success: function(response) {
$('#result').html(response);
}
});
Instead of listening to the input's click event, you should listen to the form's submit.
<script>
$(function() {
$("#name-form").on('submit', function(e) {
e.preventDefault(); // prevent form submission
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function(response) {
$('#result').html(response);
}
});
});
});
</script>
<form id="name-form" method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>

HTML/JQuery: Button submits once when it shouldn't at all

I'm using jQuery to allow the form to submit, so I don't want the form to submit on it's own.
Here's my form:
<form class="navbar-form navbar-right" id="signform">
<div class="form-group">
<input type="text" placeholder="Username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control">
</div>
<button id="signbtn" class="btn btn-success">Sign in</button>
</form>
Here's my JQuery code:
var signingIn = false;
$(document).ready(function() {
$('#signbtn').click(function() {
if (signingIn) return;
signingIn = true;
var img = $('<img id="loader" style="padding-left: 10px;" src="loader.gif"/>');
$(this).after(img);
var data = $('signform').serialize();
$.ajax({
url: '/logs',
type: 'post',
data: data,
done: function() {
$('#loader').remove();
alert('success');
}
});
});
});
Now when I go to the url: website.com/index.html and click Sign in, it refreshes the page (what I don't want at all) and goes to website.com/index.html? - Now when I click it again, nothing happens (exactly what I want all the time so my added elements through jQuery isn't lost).
You want to use jQuery ajax call like so:
$(document).on('click','button#signbtn', function(){
var $form = $('form#signform');
var url = $form.attr('action');
$.ajax({
type: "POST",
enctype: 'mutipart/form-data',
url: url,
data: $form.serialize(), // serializes the form's elements.
success: function(data){// whatever you want your code to do on success}
})
return false; // avoid to execute the actual submit of the form.
});
$(function() {
$( '#signform' ).submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr( 'action' ),
data: $(this).serialize(),
success: function(result) {
// Do something on success
}
});
});
});

Categories

Resources