Opposite of PreventDefault() : Continuing ActionLink logic - ajax

<%: 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');
}
}
});
});

Related

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

Show Button after ajax function success

I want to show a button "Reload Game" after function success instead of this bootstrapDialog box
I need this button to fit over my <div class="tilting"></div> Instead of showing somewhere else on page
You need to use below code inside the success method,
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
If you are using jQuery Ajax try it below way,
function loadDoc() {
$.ajax({
type: 'POST',
url: 'APUC',
data: 'productName=' + productName,
dataType: 'html',
cache: false,
success: function (result) {
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
},
});
}
If you are using pure Ajax, try it like this:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}

Ajax Form Submit with attachment

I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.
How can i get this to work?
Here is my ajax code:
$('#submit_btn').click(function () {
$.ajax({
type: 'POST',
url: '/contact.php',
dataType: "json",
data: $('#contactform').serialize(),
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});
On the php side i have phpmailer setup and am handling the file so:
if(!empty($_FILES['file'])) {
$_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']);
}
$('#submit_btn').click(function () {
var formData = new FormData($('#contactform'));
$.ajax({
type: 'POST',
url: '/contact.php',
// dataType: "json",
data: formData ,
processData: false,
contentType: false,
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});

Toggle partial view with AJAX

In my MVC-project I have this code for rendering a partial-view:
Method:
public ActionResult ShowArtCollection()
{
var model = new ViewModel();
model.ArtWorks = db.ArtWorks.ToList();
return PartialView("_artcollection", model);
}
AJAX:
$("#btnArt").click(function () {
$.ajax({
url: '/Home/ShowArtCollection',
dataType: 'html',
success: function (data) {
$('#artworks').html(data);
}
});
});
I would like my #btnArt to be able to toggle the partial view. I mean that when the _artcollection is rendered by the click of the button, the next click should "unrender" the view. Any tips on how to achieve this?
you can put a flag and check if rendered next time unrender on click:
var rendered = false;
$("#btnArt").click(function () {
if (!rendered) {
$.ajax({
url: '/Home/ShowArtCollection',
dataType: 'html',
success: function (data) {
$('#artworks').html(data);
rendered = true;
}
});
} else {
$('#artworks').html("");
rendered = false;
}
});
this will do the trick for you.

Issue in JQuery Confirmation Dialog inside form submit

In a JQuery dialog I have four fields. When I click on Save button I needs to check and validate the following
Validate all required fields ( On submit of form using validate.js and unobstrusive.js )
Check the value of dropdown and if it is of a partcular type ie (Redundant), Show user a confirmation dialog.
If the user confirm by pressing Yes, then close the confirmation dialog and call Ajax
But the problem is when I confirm by clicking Yes button on confirmation dialog, the dialog closes but the execution is not going down.
ie, Serializing the form data and make an Ajax call to call the webservice.
Please can anyone help.
$(function () {
$('form').submit(function () {
$('#result').html(" ");
var redunt = null;
redunt = $(ClientCrud_StatusCodeId).find('option:selected').text();
if ($(ClientCrud_StatusCodeId).find('option:selected').text() == "Redundant") {
$('#clientRedundantMessage2').html("Client once made redundant cannot be reactivated. Are you sure ?");
$("#RedundantMessage2").dialog(
{
autoOpen: false,
height: 170,
width: 420,
modal: true,
resizable: false,
title: "Confirmation for Redundant",
Content: "Fields cannot be left blank.",
buttons: {
"Yes": function () {
redunt = "Active";
$('#RedundantMessage2').dialog('close');
},
"No": function () {
$(this).dialog("close");
return false;
}
}
}) //.dialog("widget").draggable("option", "containment", "none");
$("#RedundantMessage2").dialog("open");
}
if ($(this).valid())
{
debugger;
if (redunt == "Active") {
$.ajax({
url: this.action,
type: this.method,
async: false,
cache: false,
data: $(this).serialize(),
error: function (request) {
$("#result").html(request.responseText);
// event.preventDefault();
},
success: function (result) {
if (result == "success") {
$.ajax({
url: "/Client/ClientGrid",
type: 'POST',
data: { "page": 0 },
datatype: 'json',
success: function (data) {
$('#grid').html(data);
},
error: function () {
alert('Server error');
}
});
$('#myEditClientDialogContainer').dialog('close');
$('#myEditClientDialogContainer').remove()
}
else {
clearValidationSummary();
var a = '<ul><li>' + result + '</li></ul>';
$('#result').html(a);
}
}
});
}
}
$("#griderrormsg1 li").hide().filter(':lt(1)').show();
return false;
});
editallowed = true;
});
I think you have a issue with the sequence of code, when the function $("#RedundantMessage2").dialog( ...... ); execute don't wait for the user response in this case "yes" or "no" so... your flag redunt = "Active" don't make sense.
the buttons option has function that execute when the opcion is choosen, so you must call a function to execute the post
$(function () {
$('form').submit(function () {
$('#result').html(" ");
var redunt = null;
redunt = $(ClientCrud_StatusCodeId).find('option:selected').text();
if ($(ClientCrud_StatusCodeId).find('option:selected').text() == "Redundant") {
$('#clientRedundantMessage2').html("Client once made redundant cannot be reactivated. Are you sure ?");
$("#RedundantMessage2").dialog(
{
autoOpen: false,
height: 170,
width: 420,
modal: true,
resizable: false,
title: "Confirmation for Redundant",
Content: "Fields cannot be left blank.",
buttons: {
"Yes": function () {
redunt = "Active";
trySend();
$('#RedundantMessage2').dialog('close');
},
"No": function () {
$(this).dialog("close");
return false;
}
}
}) //.dialog("widget").draggable("option", "containment", "none");
$("#RedundantMessage2").dialog("open");
}
$("#griderrormsg1 li").hide().filter(':lt(1)').show();
return false;
});
editallowed = true;
});
the other js function
function trySend(){
if ($('#IdOfYourForm').valid())
{
debugger;
if (redunt == "Active") {
$.ajax({
url: this.action,
type: this.method,
async: false,
cache: false,
data: $(this).serialize(),
error: function (request) {
$("#result").html(request.responseText);
// event.preventDefault();
},
success: function (result) {
if (result == "success") {
$.ajax({
url: "/Client/ClientGrid",
type: 'POST',
data: { "page": 0 },
datatype: 'json',
success: function (data) {
$('#grid').html(data);
},
error: function () {
alert('Server error');
}
});
$('#myEditClientDialogContainer').dialog('close');
$('#myEditClientDialogContainer').remove()
}
else {
clearValidationSummary();
var a = '<ul><li>' + result + '</li></ul>';
$('#result').html(a);
}
}
});
}
}
}

Resources