Not able to submit a form via Ajax - ajax

EDIT
the code below seems to works as long as the form is valid.
but when it is not the case (clean method in django form) h1 text of form is removed (????) and the error messages are not displayed...
I guess that an empty popup.html is return via ajax and as there is no button to interact with nothing happen but why h1 text is removed...???
var prevent_edit = false;
var prevent = false;
// popup d'informations indiquant que la levée d'insue a déjà été faite
// pour ce patient
$("#form_unblind_edit").submit(function (event) {
console.log('form_unblind_edit click - first')
console.log('prevent_edit - first', prevent_edit)
if (!prevent_edit) {
event.preventDefault();
}
});
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
// affichage des informations sur le patient sélectionné pour la ré-allocation
$("#unblind_edit").on("click", function (event) {
console.log('click unblind edit');
var csrftoken = getCookie('csrftoken');
var patient = $("#id_pat").val();
$.ajax({
type: "POST",
url: '/unblind/already_unblind/',
data: {
csrfmiddlewaretoken: csrftoken,
'patient': patient,
},
dataType: 'html',
success: function (data) {
console.log('success');
// var prevent_edit = false;
$("#can_unblind").html(data);
$('#unblindconfirm').modal('show');
$('body').on('click', '#edit_button_OK', function (event) {
console.log('edit_button_OK')
$('#edit_button_OK').attr("disabled", "disabled");
prevent_edit = true;
console.log('prevent_edit', prevent_edit);
$("#form_unblind_edit").submit();
})
},
error: function (resultat, statut, erreur) {
console.log('error');
}
});
});
i need some help for popup with ajax
User complete the form and submit the form by clicking a button
I prevent submit with event.preventDefault(); to display a popup.
But I need to ask database for informations to display on popup, so I use an ajax query
when ajax success, popup is displayed with informations from database and I want the form t be submited by clicking on "OK" button of the popup
but it failed, I think, because event (submit) is attached to a button that is not present in DOM when page load...
JS
$(document).ready(function () {
var prevent_edit = false;
// prevent submission
$("#form_unblind_edit").submit(function (event) {
if (!prevent_edit) {
event.preventDefault();
}
});
// ajax query that display popup
$("#unblind_edit").on("click", function (event) {
var csrftoken = getCookie('csrftoken');
var patient = $("#id_pat").val();
$.ajax({
type: "POST",
url: '/unblind/already_unblind/',
data: {
csrfmiddlewaretoken: csrftoken,
'patient': patient,
},
dataType: 'html',
success: function (data) {
$("#can_unblind").html(data); //popup html attach to DOM
$('#unblindconfirm').modal('show'); //popup displayed
$('body').on('click', '#edit_button_OK', function (event) {
console.log('edit_button_OK'); // WORKING
prevent_edit = true;
$("#form_unblind_edit").trigger('submit'); //form submission = NOT WORKING
})
}
});
});

Maybe change the type of the submit button in the form to "button"
<button type="button">Submit</button>
This way the submit action is not executed when the user clicks submit and instead you display the popup. Then you should be able to submit the form using JQuery.
$("#form_unblind_edit").trigger('submit');

Related

Borwser's back button state update after ajax call

I am trying to sort out back and forward browser buttons in my ajax page load setup.
This is my ajax code that calls page content:
jQuery(document).ready(function () {
$ = jQuery;
$("body").on("click", ".menuAjax a", function (e) {
//On click on body for ajax calls
e.preventDefault();
var pageID = $(this).data("id");
var catType = $(this).data("type");
var pageTitle = $(this).data("title");
var footerAdSwitch = $("#overFooter").data("footeradswitch");
var homePageSet = parseInt($("#homePageSet").val());
var $this = $(this);
//console.log($this);
var res;
var payload = JSON.stringify({
action: "router_loader",
pageid: pageID,
footeradswitch: footerAdSwitch,
homepage: homePageSet,
cattype: catType,
pagetitle: pageTitle,
});
XHR = $.ajax({
type: "get",
url: my_ajax_object.ajax_url + '/' + payload + '/view_' + (pageID || catType),
beforeSend: function () {
$("#ajaxPageLoader").show();
},
complete: function () {
$("#ajaxPageLoader").hide();
},
success: function (res) {
if (res != "") {
$("#ajaxpageLoad").html(res);
setTimeout(function () {
$("#ajaxPageLoader").hide();
}, 600);
$(".nav li.menu-item").removeClass(
"current-menu-item current_page_item"
);
$($this).parent().addClass("current-menu-item current_page_item");
const nextURL = $this[0].href;
history.pushState(res, pageTitle, nextURL);
document.title = pageTitle + " - company name";
$.getScript("/wp-content/themes/customTpl/js/functions.js");
var lazyLoadInstance = new LazyLoad({
threshold: 200,
});
$("html, body").animate({ scrollTop: 0 }, 0);
} else {
$("#ajaxPageLoader").hide();
}
},
error: function (req, status, error) {},
});
});
//Exclude expander btn from ajax call
$("body").on("click", ".btnNoBorder, .mobileMenueBtn, .closeBtn", function (e) {
e.stopPropagation();
});
window.addEventListener('popstate', function(e) {
$("#ajaxpageLoad").html(res);
updateContent(e.state);
});
});
Right now I ma stuck with popstate function, which I would like to pass urls of current position, so they are remembered once a users presses back button.
Can someone suggest me direction as to how to update history navigation with the browser buttons ?

Manual custom Ajax Add to Cart One time payment subscription

Good day, I am trying to manual ajax this
Add to cart
What this does is, It will add to the cart the one-time purchase option from the woocommerce subscription. I am trying to ajax it so it won't refresh the page when you click on it.
I found an idea how to manually ajax it by using these lines of codes. Reference here
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function(response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
The codes above work and it does ajax however, it displays the monthly subscription, not the one-time purchase. It should display the one-time purchase because of the &convert_to_sub_55337=0 which means the one-time subscription option is selected.
Also, I am getting an error after clicking the button on the console log
Uncaught TypeError: $button is undefined
I am a newbie to handling ajax so I am unsure about the issue
Thank you in advance!!
you can try this code i hope it will helped.
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
jQuery('.testing').removeClass('added').addClass('loading');
},
complete: function(response) {
jQuery('.testing').addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);

Opposite of PreventDefault() : Continuing ActionLink logic

<%: Html.ActionLink("Print", "Print", "Print", New With {.id = Model.ID}, New With {.target = "_blank", .class = "print"})%>
How to return to my actionlink's functionality once preventDefault is called? ( the _blank page is not being opened on return)
$('#NameOfButton').bind('click', function (e) {
e.preventDefault(); // Stop click event
//Gather Data
var data = $(this).parents('form').first().serialize();
//Check Data , if saved to DB continue Click functionality
$.ajax({
url: '<%:Url.Action("Get")%>',
cache: false,
type: 'POST',
data: data,
success: function (result) {
if (result.Success == true) {
//return;
return true;
} else {
//do nothing
console.log('false');
}
}
});
});
Solution:
$('#NameOfButton').bind('click', function (e) {
e.preventDefault(); // Stop click event
//Gather Data
var el= $(this);
var data = $(this).parents('form').first().serialize();
//Check Data , if saved to DB continue Click functionality
$.ajax({
url: '<%:Url.Action("Get")%>',
cache: false,
type: 'POST',
data: data,
success: function (result) {
if (result.Success == true) {
window.location.href = el.attr('href');
} else {
//do nothing
}
}
});
});
You can trigger the event again:
$('#NameOfButton').bind('click', function (e, skip) {
if (skip) return; // check param
e.preventDefault(); // Stop click event
//Gather Data
var data = $(this).parents('form').first().serialize();
var el = $(this);
//Check Data , if saved to DB continue Click functionality
$.ajax({
url: '<%:Url.Action("Get")%>',
cache: false,
type: 'POST',
data: data,
success: function (result) {
if (result.Success == true) {
console.log('true');
el.trigger('click', [true]); // trigger same event with additional param
} else {
//do nothing
console.log('false');
}
}
});
});

Polling jQuery ajax for each. Check if element does not exist, if so prepend to div

I have a div #notification-data which on $(document).ready gets populated with multiple <li></li> from $.post.
The $.post then gets called setTimeout(poll_n,9000); so data is up-to-date.
So im not updating all the data every time, I would like to do check if the <li></li> already exists in #notification-data, if it does not exist then I would like to prepend() it to #notification-data.
The data comes in the form of:
<li id="new_notification_1" class="seen_0 li_notification">blah</li>
<li id="new_notification_2" class="seen_0 li_notification">bleh</li>
As an extra question, is this the correct way of long polling?
Here is my code:
function poll_n(){
$.post('<?php echo $siteUrl ?>notifications.php?x=' + (new Date()).getTime() +'', function(data) {
$(data).find(".li_notification").each(function () {
var li_id = $(this).attr('id');
if ($(li_id).closest('#notification-data').length) {
//do nothing
} else {
$('#notification-data').append(??not_sure_what_goes_here??); // process results here
}
});
setTimeout(poll_n,9000);
});
}
EDIT - After answer I have now got this but it does not work (I get nothing in the console).
success: function(data){
$(data).find(".li_notification").each(function() {
var id = $(this).attr('id'),
notification = $('#notification-data');
console.log(id);
console.log('hello');
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend('#' + id);
}
});
},
You can try this:
function poll_n() {
$.ajax({
type: 'POST',
url: 'your url',
success: function(data){
var notification = $('#notification-data');
$.each($(data), function(){
var id = this.id;
if (notification.find('#' + id).length === 0) {
// notification doesn't exists yet then lets prepend it
notification.prepend(this);
}
});
},
complete: function(jqXHR, status) {
if (status === 'success') {
setTimeout(poll_n, 9000);
}
}
});
}
You must call poll_n() again after the request has been completed.

jQuery UI Dialog Validation

I know this is a common problem. I've been looking at the various solutions proposed on this site and elsewhere but cannot hit upon something that works in my situation.
Here is my script:
$(function () {
$('a.editPersonLink').live("click", function (event) {
loadDialog(this, event, '#personList');
$.validator.unobtrusive.parse('#editPersonContainer');
});
$(".deleteButton").live("click", function(e) {
e.preventDefault();
var $btn = $(this);
var $msg = $(this).attr("title");
confirmDelete($msg,
function() {
deleteRow($btn, $target);
});
});
});
function loadDialog(tag, event, target) {
event.preventDefault();
var $loading = $('<img src="../../Content/images/ajaxLoading.gif" alt="loading" class="ui-loading-icon">');
var $url = $(tag).attr('href');
var $title = $(tag).attr('title');
var $dialog = $('<div></div>');
$dialog.empty();
$dialog
.append($loading)
.load($url)
.dialog({
autoOpen: false
,title: $title
,width: 800
,modal: true
,minHeight: 200
,show: 'slide'
,hide: 'clip'
});
$dialog.dialog( "option", "buttons", {
"Save": function () {
var dlg = $(this);
$.ajax({
url: $url,
type: 'POST',
data: $("#formData").serialize(),
success: function (response) {
$(target).html(response);
dlg.dialog('close');
dlg.empty();
$("#ajaxResult").hide().html('Record saved').fadeIn(300, function () {
var e = this;
setTimeout(function () { $(e).fadeOut(400); }, 2500);
});
},
error: function (xhr) {
if (xhr.status == 400)
dlg.html(xhr.responseText, xhr.status); /* display validation errors in edit dialog */
else
displayError(xhr.responseText, xhr.status); /* display other errors in separate dialog */
}
});
},
"Cancel": function() {
$(this).dialog("close");
$(this).empty();
}
});
$dialog.dialog('open');
};
Right up near the top I am trying to cause the form to recognise the validation from the partial view on the dialog via the statement:
$.validator.unobtrusive.parse('#editPersonContainer');
editPersonContainer is the name of the div containing the data in the partial view loaded into the dialog.
The bottom line is that the validation is not recognised. Am I making the call to validator.unobtrusive.parse in the wrong place, or am I missing something else here?
I ended up changing my script to use the techniques described here
Validation now works on my jQuery UI dialogs.
Hi I came up to your question as I was looking for the same.
I include this before the ajax call to validate on client side:
if (ModelState.IsValid) {}
I make an article with the full project on
Validation client/Server JqueryUI Dialog

Resources