Display loading.gif while uploading a file using jQuery - javascript

How to show loading.gif while uploading a file using jQuery?
<input type="file" class="form-control" name="profilepic" id="profilepic" accept="image/*" required >
<div id="loader_img"></div>
<button type="submit" name="submit" id="submit" class="btn btn-primary"><span class="glyphicon glyphicon-check"></span> Save</button>
When I click on the save button, loading.gif has to be shown while loading a file.
This is my jQuery:
<script>
$(function() {
$('form[name="chngimg"]').find('input,select,textarea').not('[type=submit]').jqBootstrapValidation({
submitSuccess: function ($form, event) {
$.ajax({
type: "POST",
url: "propicchng.php",
data: $('form').serialize(),
success: function(msg){
$('#loader_img').show();
// just to confirm ajax submission
$("#imgchng").modal('hide');
alert(msg);
$( '#chngimg-form' ).each(function(){
this.reset();
});},
error: function(){
alert("failure");
}
});
event.preventDefault();
}
});
});
</script>

What #Mehran Torki is saying is that you need to first put the loader to show before the request - and then hide it in success callback. This is how your code should look like to show the loader - mind the comments!
$(function() {
$('form[name="chngimg"]').find('input,select,textarea').not('[type=submit]').jqBootstrapValidation({
submitSuccess: function ($form, event) {
//here - showing loader to the user
$('#loader_img').show();
$.ajax({
type: "POST",
url: "propicchng.php",
data: $('form').serialize(),
success: function(msg){
//here - hiding when request is done
$('#loader_img').hide();
// just to confirm ajax submission
$("#imgchng").modal('hide');
alert(msg);
$( '#chngimg-form' ).each(function(){
this.reset();
});},
error: function(){
alert("failure");
}
});
event.preventDefault();
}
});
});

Related

Jquery submit event not firing

I am trying to submit a form using jquery. I am running a Django server.
The JS Code and HTML are as follows:
document.addEventListener('DOMContentLoaded', function() {
// Submit comment form
document.querySelector('#comment-form').addEventListener("submit", function(event){event.preventDefault()});
document.querySelector('#comment-form').addEventListener('submit', () => save_comment());
});
function save_comment() {
console.log('Save function triggered');
frm = document.querySelector('#comment-form');
data_submit = {
updated_comment: frm.querySelector('#comment-editbox').value,
month: frm.querySelector('#comment-mth').value,
gl_code: frm.querySelector('#comment-gl').value,
csrfmiddlewaretoken: jQuery("[name=csrfmiddlewaretoken]").val(),
};
console.log('Save function triggered 2');
frm.submit(function (e) {
console.log('Submit triggered');
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: data_submit,
success: function (data) {
console.log("successful");
},
error: function(data) {
console.log("failed");
}
});
console.log('save ended');
return false;
});
}
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<label id="comment-heading">Comments <span id="comment-subheading"></span></label>
<form action="{% url 'comment' %}" method="post" id='comment-form'>
{% csrf_token %}
<textarea id="comment-editbox" name="comment-editbox"></textarea><br>
<input type="hidden" id="comment-mth" name="comment-mth" value="">
<input type="hidden" id="comment-gl" name="comment-gl" value="">
<input class="btn btn-primary" type="submit" value="Save" id='comment-save'>
</form>
</div>
</div>
"Save function triggered" and "Save function triggered 2" get logged onto the console when I submit the form. But "Submit triggered" does not.
The form does get submitted to the server which returns a json response and causes the form to navigate to the response route. I do not want the form to redirect to the response route or reload the page.
What am I doing wrong?
Why are you using?
frm.submit(function (e) {
...
});
You are calling submit method on the DOM and passing in a function to it. There is no function with submit(); Those two lines should be removed.
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#comment-form').addEventListener('submit', save_comment);
});
function save_comment(e) {
e.preventDefault();
console.log('Save function triggered');
const frm = document.querySelector('#comment-form');
const data_submit = {
updated_comment: frm.querySelector('#comment-editbox').value,
month: frm.querySelector('#comment-mth').value,
gl_code: frm.querySelector('#comment-gl').value,
csrfmiddlewaretoken: jQuery("[name=csrfmiddlewaretoken]").val(),
};
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: data_submit,
success: function(data) {
console.log("successful");
},
error: function(data) {
console.log("failed");
}
});
console.log('save ended');
}

Unable to submit the ajax form multiple times after using .submit() function

This is my code:
var onloadCallback = function() {
$( "#submit" ).each(function() {
grecaptcha.render($( this ).attr('id'), {
'sitekey' : '6Lcjvi4UAAAAAIR7_ckItF2HfMEFHx427WUDdGDk',
'callback' : onsubmitforgotpass
});
});
};
function onsubmitforgotpass(token) {
$(document).ready(function() {
$("form.formajax").submit(function() {
$.ajax({
type: "POST",
url: "admin/login/forgotpass.php",
data: $("form.formajax").serialize(),
cache: false,
success: function(result) {
$(".forgotpassresult").html(result);
$(".forgotpassresult").css("opacity", "1");
}
});
return false;
});
$("form.formajax").submit();
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="" method="post" class="formajax">
<input type="text">
<input type="submit" id="submit">
</form>
I am unable to submit this ajax form multiple times.
It is probably because of these 2 lines:
$("form.formajax").submit(function()
and
$("form.formajax").submit();
If I replace those line with $("#submit").click(function() and $("#submit").click();
Then I can submit the form multiple times.
Anyway to submit the form multiple times using .submit(); function? (It will help me in some other part of my code also, so I do not want to use click();
hey please test the following things:
Please remove the actions
action="abc.com"
to
action=""
add ajax call on button click like below example:
$("#submit").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "admin/login/forgotpass.php",
data: $("form.formajax").serialize(),
cache: false,
success: function(result) {
$(".forgotpassresult").html(result);
$(".forgotpassresult").css("opacity", "1");
}
});
});
});

Mailchimp via jQuery Ajax. Submits correctly but JSON response is returned as a separate page

I have the following form:
<form class="footer-newsletter-form" id="footer-newsletter" method="post" action="http://xxxxxx.us1.list-manage.com/subscribe/post-json?u=xxxxxxxxxxxxxxxxxxxxxxxxx&id=xxxxxxxxxx&c=?">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field" value="{% if customer %}{{ customer.email }}{% endif %}" placeholder="{{ 'general.newsletter_form.email_placeholder' | t }}" aria-label="{{ 'general.newsletter_form.newsletter_email' | t }}">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the following jquery bit:
<script type="text/javascript">
$(document).ready(function () {
function register($form) {
jQuery.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { console.log('error') },
success : function(data) {
if (data.result != "success") {
console.log('success');
} else {
console.log('not success');
//formSuccess();
}
}
});
}
jQuery(document).on('submit', '.footer-newsletter-form', function(event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch(error){}
});
});
</script>
Which submits correctly. However, when I press the submit button what I expect to happen is that the page does not refresh and when I check the browser console I'll either see "success" or "not success". Instead what happens is I'm sent to a page that displays the following JSON message: ?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."}).
So how do I take that success message (or error if there's an error) and have the page not only remain as is, but also capture the success message so I can display a "Success" alert? The success alert I know how to do. I just need help having the browser remain where it is and tell the difference between success and error.
P.S. I'm not sure if this is relevant but the platform is Shopify. I don't think Shopify does anything to prevent the submission from going through as it should or the response coming back so I don't think it is relevant.
The whole issue was the $(document).ready(function () {}); part. For some reason unbeknownst to me that causes the event.preventDefault(); method from running and the form submits regularly. If you remove the $(document).ready(function () {}); part it'll work as intended.
My final code for anyone looking in the future:
Form:
<form class="footer-newsletter-form" method="POST" id="footer-newsletter" action="https://xxxxxxxxxxxxx.us1.list-manage.com/subscribe/post-json?c=?">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx">
<input type="hidden" name="id" value="xxxxxxxxxx">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the JS:
<script>
function register($form) {
$.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log('error')
},
success: function (data) {
if (data.result != "success") {
console.log('Error: ' + data.msg);
} else {
console.log("Success");
$($form).find("div#subscribe-result").html("<p class='success-message'>Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you!</p>");
setTimeout(function() { $($form).find("div#subscribe-result").hide(); }, 7000);
}
}
});
}
$(document).on('submit', '#footer-newsletter', function (event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch (error) {}
});
</script>

Redirection after successful form submit

I have a form which should submit data after pressing the submit button. After tagging a few input fields as required the form always shows me when there is no input in the required field after pressing the submit button - so far, so good.
What I would like to realize is that there is a redirection to another page if the submission was successful. If there are some empty required fields the form should show me, without redirecting me to another page.
By now I have the following code:
Submit button:
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="submityes" id="submityes" class="btn btn-danger">Submit</button>
</div>
</div>
Also I have the following js function to submit the form and to redirect me to another page:
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
The problem I have right now is that I will always be redirected to the "submit_resolved.php" page, whether all required fields are complete or not.
How can I solve this problem? I only want to be redirected when all required fields are not empty.
You should bind to the submit event, not click event:
UPDATED TO MATCH THE COMMENTS
$(function () {
var submityesClicked;
//catch the click to buttons
$('#submityes').click(function () {
submityesClicked = true;
});
$('#submitno').click(function () {
submityesClicked = false;
});
$('#webform').submit(function (e) {
e.preventDefault();//prevent the default action
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
window.location.replace(submityesClicked ? "/submit_resolved_yes.php" : "/submit_resolved_no.php");
},
error: function () {
alert("error");
}
});
});
});
The submit event is triggered only if the form is valid.
Note that the submit event is triggered by the form but the click event is triggered by the input element.
Do redirection on complete. Not on success
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
//window.location.replace("/submit_resolved.php");
},
complete: function () {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
I assume you are validating form in process.php so, you have to return error if validation fail from process.php like this.
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
check this link: Return errors from PHP run via. AJAX?
Hope this may be helpful to you.
The simplest thing you can do is to add "required" attribute to you input elements.Example:
<form action="/action_page.php">
Username: <input type="text" name="usrname" required>
<input type="submit">
</form>
It's a HTML5 attribute, so no JavaScript required. And it is supported by all major browsers. Check this link:
http://caniuse.com/#search=required
Anyway, you shouldn't rely just on front-end verification. Check those inputs on back-end, too.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<form action="">
Username: <input type="text" id="usrname" required>
<button type="button" name="submityes"
id="submityes" class="btn btn-danger">Submit</button>
</form>
</div>
function isValid(){
var usrname = $("#usrname").val();
if(usrname == ""){
return false;
}
return true;
}
$(function () {
$('#submityes').submit(function () {
if(isValid() == true){
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
alert("success");
window.location.replace("/submit_resolved.php");
},
});
}else{
alert("error");
}
});
});

Facing AJAX issue with JSP

I am working on a small tool which just consists of a single JSP which is used for view as well as for processing the AJAX response.
If the call is of type 'GET', I am showing a form the user.
<form id="submitForm" method="post">
<div class="ui-widget">
<label for="tags">Please Select the Merchant : </label>
<input id="tags" name="mechant" style="width:300px;height:40px;border: 0.5px solid;border-radius: 5px;">
<input type="submit" value="Get Data" style="border: 0.5px solid;border-radius: 5px;">
</div>
</form>
And following is the code which will make the call.
$("#submitForm").submit(function() {
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Once the user submits the form which goes as 'POST' the logic in the same JSP is returning the response.
Right now I am trying with a very simple logic.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Hello World");
Now when this response is return the whole of initial page is washed off and I just see "Hello World" on the page. Even though as per my understanding only the div with id "data" should be updated with value.
Kindly anyone have a look and let me know what might be going wrong here.
Thanks in advance.
You could try preventing the default handler as well as prevent bubbling up the DOM.
$("#submitForm").submit(function(event) {
// Prevent the default action
event.preventDefault();
// Pevent propagation of this event up the DOM
event.stopPropagation();
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});

Categories

Resources