stop/cancel form jquery form action from javascript? - javascript

I have a form that is submitted via jquery for an instant image upload. When the image starts to upload via the form, i show a cancel upload button via jquery. Now is there a way using jquery, i can stop/cancel the form submission on the click property of the cancel upload button? What i do currently is that i delete the current upload from the databse using ajax and then refresh the page. this will not upload the image but i am trying to find something that will not let the page refresh.
$('.deleteimage').live("click", function () {
var ID = $(this).attr("id");
var IPString = $(".ipvaluetable").val();
var dataString = 'msg_id=' + IPString;
document.getElementById("preview").style.visibility = "hidden";
$(".preview").slideUp('slow', function () {
$(this).remove();
});
document.getElementById("deleteimage").style.visibility = "hidden";
$.ajax({
type: "POST",
url: "http://schoolspam.com/delete_image.php",
data: dataString,
cache: false,
success: function (html) {}
});
location.reload();
return false;
});

Well on cancel you can do event.preventDefault(); and then return false.
Example
$('.cancel').on('click', function(e){
e.preventDefault();
return false;
});

Please use below code and also see my comments :
$('.deleteimage').live("click", function (e) {
e.preventDefault();//Stops default behaviour
var ID = $(this).attr("id");
var IPString = $(".ipvaluetable").val();
var dataString = 'msg_id=' + IPString;
document.getElementById("preview").style.visibility = "hidden";
$(".preview").slideUp('slow', function () {
$(this).remove();
});
document.getElementById("deleteimage").style.visibility = "hidden";
$.ajax({
type: "POST",
url: "http://schoolspam.com/delete_image.php",
data: dataString,
cache: false,
success: function (html) {}
});
//location.reload();//This one needs to be removed so as to stop the reload
return false;
});

Related

Launch modal in modal

I want to launch a modal in a modal. It's actually working, but if I open the 2nd modal in the 1st modal, the 2nd modal appears, but behind the 1st modal and the scroll bar disappear, when I close the 1st modal: modal
The JavaScript is in my modal PHP file.
How can I solve this problem?
Javascript
$(document).ready(function() {
$('.relations').click(function(e) {
var checkBoxes = $("input[name=case]");
var checkedBoxes = checkBoxes.filter(":checked");
if (checkedBoxes.length === 0) {
return false;
}
e.preventDefault();
var insert = [];
$('.checkboxes').each(function() {
if ($(this).is(":checked")) {
insert.push($(this).val());
}
});
insert = insert.toString();
var data_id = $(this).attr("id");
$.ajax({
url: "nodes.php",
method: "post",
dataType: "json",
data: {
data_id: data_id,
insert: insert
},
success: function(data) {
$('#moreInfo').html(data);
$('#dataModal').modal("show");
var nodeDatas = new vis.DataSet();
nodeDatas = data;
$.ajax({
method: "post",
dataType: "json",
url: "edges.php",
data: {
data_id: data_id
},
success: function(data) {
var edgeDatas = new vis.DataSet();
edgeDatas = data;
var myDiv = document.getElementById("moreInfo");
data = {
nodes: nodeDatas,
edges: edgeDatas
};
var options = {
};
var network = new vis.Network(myDiv, data, options);
}
});
}
});
});
});
I'm assuming that the second modal is moreInfo div, if that's correct, you need to make few css changes for that element to appear on top of the first modal, using z-index:99999; maybe more, and also for the scrollbar to appear you need another css property overflow:scoll;
I hope this helps!

AJAX sending multiple requests after button click

I just want one click to equal one submit in my jQuery code.
I've read quite a few posts on this same topic but I think mine is different. I do have a mouseleave and focusout event that I'm using to find errors in user input. Those functions feed down into the function that is submitting multiple times. The more times I hit mouseleave and focusout the more times my Ajax request is submitted. But I need mouseleave and focusout to continue to work and check the users input, that's why I'm not using one. Please see my code below, the function that I think is submitting multiple times is handleButtonClicksAfterError
function getCreditAmountToSend(modal){
console.log("getCreditAmountToSend");
var checkBox = $(modal).contents().find("#fresh-credit-checkbox");
checkBox.change(function(){
if($(checkBox).is(":checked")) {
var creditAmount = +(sessionStorage.getItem("creditAmount"));
sessionStorage.setItem('amountToSend', creditAmount);
}
});
var pendingCreditAmount = $(modal).contents().find("#pending_credit_amount");
pendingCreditAmount.on({
mouseleave: function(){
if(pendingCreditAmount.val() != ""){
adminForGetPendingCredit(modal);
}
},
focusout: function(){
if(pendingCreditAmount.val() != ""){
adminForGetPendingCredit(modal);
}
}
});
}
function adminForGetPendingCredit(modal){
console.log("adminForGetPendingCredit");
var checkBox = $(modal).contents().find("#fresh-credit-checkbox");
if(!$(checkBox).is(":checked")) {
var enteredAmount = +($(modal).contents().find("#pending_credit_amount").val());
var creditAmount = +(sessionStorage.getItem("creditAmount"));
sessionStorage.setItem('enteredAmount', enteredAmount);
doWeDisplayError(modal,creditAmount, enteredAmount);
}
}
function doWeDisplayError(modal,creditAmount, enteredAmount){
console.log("doWeDisplayError");
$(modal).contents().find("#fresh-credit-continue-shopping").prop("disabled", false);
$(modal).contents().find("#fresh-credit-checkout").prop("disabled", false);
if(creditAmount < enteredAmount){
$(modal).contents().find("#pending_credit_amount").val("");
$(modal).contents().find("#fresh-credit-continue-shopping").prop("disabled", true);
$(modal).contents().find("#fresh-credit-checkout").prop("disabled", true);
displayError();
}
else{
handleButtonClicksAfterError(modal, enteredAmount);
}
}
function handleButtonClicksAfterError(modal, enteredAmount){
// this is the problem!!!!!!!!!!!!!
console.log("handleButtonClicksAfterError");
sessionStorage.setItem('amountToSend', enteredAmount);
var continueButton = $(modal).contents().find("#fresh-credit-continue-shopping");
continueButton.click(function() {
modal.hide();
});
var checkoutButton = $(modal).contents().find("#fresh-credit-checkout");
checkoutButton.click(function() {
console.log("handleButtonClicksAfterError");
sendData();
});
}
function displayError(){
console.log("displayError");
$(function(){
$("#fresh-credit-iframe").contents().find("#pending_credit_amount").attr("placeholder", "Whoops, that was too much");
$("#fresh-credit-iframe").contents().find("#pending_credit_amount").attr({
class: "form-control form-control-red"
});
sessionStorage.removeItem('enteredAmount');
});
}
This is the function that actually POSTs the data
function sendData(){
var amountToSend = sessionStorage.getItem("amountToSend");
var products = $.parseJSON(sessionStorage.getItem("products"));
console.log("sendData");
console.log("This is the amount to send " + amountToSend);
$.ajax({
url: "/apps/proxy/return_draft_order",
data: {amountToSend, products},
type: "POST",
dataType: "json",
complete: function(data) {
window.location.href = data.responseText;
console.log("This is the URL from poll " + data.responseText );
return false;
},
});
}
It ended up being super simple.. I just needed the jQuery off method.. I attached it to the button before click and everything is peachy.. Looks like this:
checkoutButton.off().click(function(){});
off clears all the previous event handlers and then just proceeds with Click
Pretty cool, to read more check it out here
use async:false to prevent multiple request
$(document).off('click').on('click', function(){
$.ajax({
type:'POST',
url: ,
async:false,
cache: false,
data:{}
,
success: function(data){
},
error:function(data){
}
});
});

how restart Jquery function if not complete

How can I let my form alert re-start once the user re-click the button if the input still empty
What I made :
after the click it will check if the inputs empty will stop the code and show alert. but once the alert appeared if I re-click the button again its not work again!
$(document).ready(function(){
function requierd()
{
$('#allrequierd').addClass("animated");
$('#allrequierd').addClass("shake");
$('#alertDanger').removeClass("hide");
setTimeout( "$('#alertDanger').fadeOut();", 4000);
}
function pass()
{
$('#alertDanger').addClass("hide");
$('#alertsuccess').removeClass ("hide");
$('#visitorFullName').val('');
$('#visitorPhoneNumber').val('');
$('#visitorEmail').val('');
$('#visitorMsg').val('');
$('#alertsuccess').addClass ("animated");
$('#alertsuccess').addClass ("bounceIn");
setTimeout( "$('#alertsuccess').fadeOut();", 4000);
}
$('#sendContactMsg').click(function ()
{
var visitorFullName = $('#visitorFullName').val();
var visitorPhoneNumber = $('#visitorPhoneNumber').val();
var visitorEmail = $('#visitorEmail').val();
var visitorMsg = $('#visitorMsg').val();
var visitorCallMethod = $('#visitorCallMethod').val();
var dataString = 'visitorFullName='+visitorFullName+'&visitorPhoneNumber='+visitorPhoneNumber+'&visitorEmail='+visitorEmail+'&visitorMsg='+visitorMsg+'&visitorCallMethod='+visitorCallMethod;
if(visitorFullName==''||visitorPhoneNumber==''||visitorEmail==''||visitorMsg=='')
{
requierd();
}else{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "functions/sContactus.php",
data: dataString,
cache: false,
success: function(result){
// alert(result);
if (result == "Success") {
// alert("DONE");
pass();
}else {
alert("Sorry Try Again")
}
}
});
}
return (start);
});
// END jquery
});
When you fire the alert the first time, your #alertDanger is getting the .fadeOut() which will apply inline display:none style to that element. You're not removing that inline style at any point, and in fact you're also not adding back the "hide" class either, so your #alertDanger will remain hidden.
What you should do is "reset" the alert div after you fade it out:
function removeAlert() {
$('#alertDanger').fadeOut();
$('#alertDanger').addClass("hide").css("display","block");
}
And in your required() function:
setTimeout( removeAlert, 4000);

Javascript/jQuery wait for variable true

I have the following setup:
A document can have multiple forms.
When the input on an input field changes, jQuery will fire an ajax event. And input.data("checking", true) is called.
When the ajax event has been finished, input.data("checking", false) is called.
Now I want to make a custom form submit that waits for all input in this form to be on input.data("checking") === true.
My code so far, without the question applied:
$(document).on("submit", "form", function(event) {
event.target.checkValidity();
event.preventDefault();
event.stopPropagation();
//TODO: prevent this when not everything is checked
var dataSerialized = $(this).serialize();
var service = $(this).attr("action");
$.ajax({
url: "services/" + service + ".php",
data: dataSerialized,
type: "POST",
cache: false,
success: function(html) {
if (html == "1") {
//TODO: load page from json callback
//loadPage(onsuccess);
}
else {
loadPage("error");
}
},
error: function(html, message) {
finalError(message);
}
});
});
How could I make this function wait (non-blocking!) until all ajax events are finished?
Suppose to create a function checkDone which returns true when input.data("checking") == false for all input in the form, you could do:
$(document).on("submit", "form", function(event) {
event.target.checkValidity();
event.preventDefault();
event.stopPropagation();
var that = $(this);
var interval = setInterval(function() {
if(checkDone(that)) {
clearInterval(interval);
var dataSerialized = that.serialize();
var service = that.attr("action");
$.ajax({
url: "services/" + service + ".php",
data: dataSerialized,
type: "POST",
cache: false,
success: function(html) {
if (html == "1") {
//TODO: load page from json callback
//loadPage(onsuccess);
}
else {
loadPage("error");
}
},
error: function(html, message) {
finalError(message);
}
});
}
}, 500);
});
In this way you check every 0.5 seconds if you can submit the form after all inputs are validated, and if so the interval is cleared and the form submitted.
However I would recommend not to remove standard server side validation on post submit.

JQuery ,replaceWith() not working after writing to session from iframe, unless page is refreshed

I have a function that rewrites dynamically a div after ajax call
function showPage(href){
setTitle("",0);
$.ajax({
type: "POST",
url: href,
cache: false,
success: function(html){
rewriteContentDiv(html,isNotFade);
}
});
}
function rewriteContentDiv(html, href, isNotFade) {
var bodyObj;
if($('#content-div').length !=0){bodyObj=document.body;}else{bodyObj=parent.document.body;}
$('#content-div', bodyObj).fadeOut("slow", function () {
var div = $('<div class="content" id="content-div">test2</div>').hide();
div.html(html);
$('#content-div', bodyObj).replaceWith(div);
$('#content-div', bodyObj).fadeIn("slow");
$('#content-div', bodyObj).find("a").click(function (e) { catchAnchorClick($(this), e) });
});
}
I call this function from a page and it works, unless 1 specific circumstance:
When inside the "content-div" I have an iframe with a button which writes something to a session with
function setObject(key,value){
var session = window.sessionStorage;
session.setItem(key, escape(JSON.stringify(value)));
}
The object does get written to the session, but then the rewriteContentDiv function starts to fail on
$('#content-div', bodyObj).replaceWith(div);
line, without showing any exception or letting me step into the jQuery function - i debug on chrome 30.0.1599.101 m.
If I press "refresh" - the function starts working again, and I see the object in the session storage.
Why can it be and what can be done to prevent it?
I tried to make an ugly trick of setting
"window.location="
to the url of itself when in the problematic situation, but it didn't help...
Thanks.
Check the code once again as there are some grammar errors
function showPage (href){
setTitle("",0);
$.ajax({
type: "POST",
url: href,
cache: false,
success: function (html) {
rewriteContentDiv(html, href, isNotFade);
}
});
}
function rewriteContentDiv (html, href, isNotFade) {
var bodyObj;
if ($('#content-div').length > 0) {
bodyObj = document.body;
} else {
bodyObj = parent.document.body;
}
$('#content-div', bodyObj).fadeOut("slow", function () {
var div = $('<div class="content" id="content-div">test2</div>').hide();
div.html(html);
$('#content-div', bodyObj).replaceWith(div);
$('#content-div', bodyObj).fadeIn("slow");
$('#content-div', bodyObj).find("a").click(function (e) {
catchAnchorClick($(this), e) });
});
}

Categories

Resources