Change text of Input button after clicking on it - javascript

I have the following input HTML tag
<input type="submit" id="submitForm" value="Submit" class="btn btn-primary start" autocomplete="off" onclick="submitForm();" />
When I click on the submit button, it goes to the related JavaScript file and executes the function submitForm();
I would like to change the text of the submit form to "Please wait..." until the function is completed.
Is there a way this can be done?
This is how the submitForm() function looks like:
function submitForm() {
$("#submitForm").val("Please wait...");
if (formValidation() === true) {
submitFormInfo().done(function () {
$("#submitForm").val("Submit");
});
}
}
function submitFormInfo() {
return $.ajax({
cache: false,
url: "URLHERE"
error: function (xhr) {
},
success: function (result) {
},
async: false,
processData: false
});
}

Are you having asynchronus operation in submitform() ?
if yes then you can use following line
$("#submitForm").val("Please Wait");

You can use jquery please see:-
https://jsfiddle.net/swawrm1g/3/
I have removed:-
onclick="submitForm();"
and added:-
$('#submitForm').click(function(){
$(this).val('Please Wait...');
submitForm()
});
function submitForm() {
alert('Form submitted');
};

Simple javascript is enough to do this..
<script>
function submitForm(){
document.getElementById('submitForm').value="Please wait..";
}
</script>
<input type="submit" id="submitForm" onclick="submitForm()" value="Submit">

Use the beforeSend option on your ajax call, so in your submitForm() function, you can do something like this:
function submitForm() {
var submitForm = $("#submitForm");
if (formValidation() === true) {
$.ajax({
cache: false,
url: "URLHERE",
async: false,
type: 'post',
data: { somedata: 'here' },
beforeSend: function (){
submitForm.val("Please wait...").attr("disabled", "disabled");
},
success: function (data){
// do something
},
error: function (){
// do something
},
complete: function () {
// regardless of the response status (success/error)
// the codes below will be executed.
submitForm.val("Submit").removeAttr("disabled");
}
});
}
}

Related

How to fix return Ajax in a div without return false

I'm working on a web application, and i have a problem with a return of Ajax.
I can see the result of the return of AJAX, but my problem is that this result appears and then disappears. I found a solution that is return false, the problem being that once the display is done and I return false, my div remains on the page but I can not reuse the button on which I made my onclick (to call my javascript function and so the ajax call).
If someone has a solution.
This is the code :
<input class="Admin-Bouton" type="submit" onclick="affOtp();return false" value="Générer" form="formParametres" />
<div id="syntheseOTP"></div>
function affOtp() {
$(function(){
$.ajax({
url: 'vue/ressources/affOtp.php',
type: 'POST',
dataType: 'html',
data: { idEmploye: nom },
success: function(msg) {
console.log(msg);
document.getElementById("syntheseOTP").innerHTML = msg;
},
error: function(resu, statut, erreur) {
console.log(erreur);
alert("papa");
}
});
});
};
That happen because the form will be submited and the page refresh, you could avoid that by using type button instead of submit :
<input id="Admin-Bouton" class="Admin-Bouton" type="button" onclick="affOtp();return false" value="Générer" form="formParametres" />
I suggest to attach the event click in the js code instead of inline-event onclick :
$('#Admin-Bouton').on('click', affOtp);
HTML will be like :
<input id="Admin-Bouton" class="Admin-Bouton" type="button" value="Générer" form="formParametres" />
Hope this helps.
Edit: Left out "return" before affOtp();
<input class="Admin-Bouton" type="submit" onclick="return affOtp();" value="Générer" form="formParametres" />
<div id="syntheseOTP"></div>
function affOtp() {
$(function(){
$.ajax({
url: 'vue/ressources/affOtp.php',
type: 'POST',
dataType: 'html',
data: { idEmploye: nom },
success: function(msg) {
console.log(msg);
document.getElementById("syntheseOTP").innerHTML = msg;
},
error: function(resu, statut, erreur) {
console.log(erreur);
alert("papa");
}
});
});
return false;
};
Since none of the answers are still working for you, I would recommend you to do following changes (keeping in mind you don't want to change type="submit").
<input id="AjaxButton" class="Admin-Bouton" type="submit" value="Générer" form="formParametres" />
<!-- remove onlick attribute and add a Id attribute in above line -->
<div id="syntheseOTP"></div>
Now make sure you add a click event handler in your scripts.
$('#AjaxButton').on('click',affOtp);
function affOtp(e) { // add e as input parameter
// removed unnecessary wrapper
e.preventDefault(); // this will now stop the click event.
$("#syntheseOTP").html("Loading...."); // add loading text into div
$.ajax({
url: 'vue/ressources/affOtp.php',
type: 'POST',
dataType: 'html',
data: { idEmploye: nom },
success: function(msg) {
console.log(msg);
$("#syntheseOTP").html(msg); //refactored to use jquery syntax
},
error: function(resu, statut, erreur) {
console.log(erreur);
alert("papa");
}
});
};

ajaxSubmit: Duplicate Entry on the database

I have a form and a input type file inside.
<form id='imageform' method='post' enctype='multipart/form-data' action='php/exec/add-message-image-exec.php' style='clear:both'>
<div id='imageloadstatus' style='display:none'><img src='assets/loader.gif' alt='Uploading....'/></div>
<div id='imageloadbutton'>
<div class='file-field input-field'>
<div class='btn'>
<span>Upload</span>
<input type='file' name='file' id='photoimg'/>
</div>
<div class='file-path-wrapper'>
<input class='file-path validate' type='text'>
</div>
</div>
</div>
</form>
It performs whenever i attach an image in the input file, and an ajax will handle it to submit it automatically and save it to the database.
$(document).ready(function () {
$('#photoimg').on('change', function () {
var A = $('#imageloadstatus');
var B = $('#imageloadbutton');
$('#imageform').ajaxSubmit({target: '#preview',
beforeSubmit: function () {
A.show();
B.hide();
},
success: function () {
A.hide();
B.show();
},
error: function () {
A.hide();
B.show();
}}).submit();
});
});
My problem is that it submits the image twice and save it to my database/table twice. But when i remove the .submit(); inside my script, it only perform once but there's a small modal-like window and another screen appeared whenever i attach an image/submit.
Remove 'action' and put it in an ajax POST request instead.
$(document).ready(function () {
$('#photoimg').on('change', function () {
var A = $('#imageloadstatus');
var B = $('#imageloadbutton');
$.ajax({
url: 'php/exec/add-message-image-exec.php',
type: 'POST',
data: $('#imageform').serialize(),
beforeSubmit: function () {
A.show();
B.hide();
},
success: function (data) {
//do something with data
//ex: console.log()
console.log(data);
A.hide();
B.show();
},
error: function () {
A.hide();
B.show();
}
});
});
});

Validation not firing submitHandler

As stated in the title, the submitHandler is not firing/being reached, but the validation is working correctly. The submit handler is in the correct, but not firing.
$(function () {
$("#form").validate({
rules: {
domain: {
required: true
},
playerClass: {
required: true,
}
},
submitHandler: function (form) {
var accountNumber = $("input#accountNumber").val();
var domain = $("input#domain").val();
var playerClass = $("input#playerClass").val();
var dataString = JSON.stringify([{
"accountNumber": accountNumber,
"playerClass": playerClass
}]);
//Save Form Data........
$.ajax({
type: "POST",
dataType: "json",
url: "/",
contentType: "application/json",
data: dataString,
success: function () {
$('.render-info').html("<div class='alert alert-success'>You've successfully built your player code</div>");
$(".player-code").show();
},
failure: function () {
alert(dataString);
$('.render-info').html("<div class='alert alert-failure'>Submission Error</div>");
}
});
$(".player-code").show();
}
});
});
jsFiddle: Link
Because you don't have a real submit button. A div is not a button...
<div class="btn btn-default submit">Submit</div>
You need a button or input with type="submit" to trigger the submitHandler when the form is valid.
<input type="submit" class="submit" />
OR
<button type="submit" class="submit">Submit</button>
http://jsfiddle.net/e04rca0t/7/

Jquery $(this).closest('form'); not working after button click

I have the following js code:
$("#add_station").on('click', function () {
$(this).closest('form').submit(function () {
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
return false;
});
When I click the button with the id add_station it alerts on click function after $($this).closest('form').submit(function(){...) it doesn't work as you can see I've put an alert 'works' after submit function.I get no errors on the console and I can't figure what the problem is. Also, the button that is clicked is inside a form.
I need to use $($this).closest('form').submit(function(){...) inside because after ajax success a new form will be generated with add station button that will use this code.
You should block the default submit trigger by using
e.preventDefault();
$(this).closest('form').submit(function (e) {
e.preventDefault();
<!--rest of the code-->
})
add a separately submit handler
$("#add_station").on('click', function () {
$(this).closest('form').submit();
});
$("form").on("submit", function (e) {
e.preventDefault();
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
after ajax success a new form will be generated with add station
button that will use this code
If you generate a new button you have to bind the click again after it is placed to the dom.

Submit ajax request one by one with each()

i tried to submit multiple form using ajax, but how to send one by one, i mean send the first ajax after done/success then send second ajax, below is my script:
<form>
<input type="text" name="name" value="john doe" size="60">
<input type="text" name="age" value="23" size="2">
</form>
<form>
<input type="text" name="name" value="Alex" size="60">
<input type="text" name="age" value="24" size="2">
</form>
<button>Submit</button>
<script>
function post_form_data(data) {
$.ajax({
type: 'POST',
url: 'https://members.lelong.com.my/Auc/Member/Feed/feed.asp',
data: data,
success: function () {
console.log('Success');
},
error: function () {
console.log('error');
}
});
}
$('button').on('click', function () {
$('form').each(function () {
post_form_data($(this).serialize());
});
});
</script>
You can try this :
function post_form_data(data,cache,i) {
$.ajax({
type: 'POST',
url: 'https://members.lelong.com.my/Auc/Member/Feed/feed.asp',
data: data,
success: function () {
console.log('Success');
i++;
post_form_data(cache.eq(i).serialize(),_cached,i);
},
error: function () {
console.log('error');
}
});
}
$('button').on('click', function () {
var _cached=$('form');
post_form_data(_cached.eq(0).serialize(),_cached,0);
});
You can add
async : false
to make it sequential.
$.ajax({
type: 'POST',
url: 'https://members.lelong.com.my/Auc/Member/Feed/feed.asp',
data: data,
async :false ,
success: function () {
console.log('Success');
},
error: function () {
console.log('error');
}
});
Note:- async : false can logically turn down behavior of ajaxified request. We discourage the use of it until its needed desperately.
You could put requests data in array, returning promise interface from function and use done/then or always:
function post_form_data(data) {
return $.ajax({
type: 'POST',
url: '/echo/html',
data: data,
success: function () {
console.log('Success');
},
error: function () {
console.log('error');
}
});
}
$('button').on('click', function () {
var requests = $('form').map(function () {
return $(this).serialize();
}).get();
var i = 0;
if (requests.length) {
makeRequest(requests, i);
}
});
function makeRequest(requests, i) {
var iPromise = post_form_data(requests[i]);
if (i < requests.length - 1) {
iPromise.done(makeRequest(requests, ++i))
}
}

Categories