Jquery ready function with click and ajaxForm calls - jquery-plugins

I m really new working with JQuery and I have an error in my code. The next piece of code was working perfect when a user click a "Button", it load a file in a content div.
$(document).ready(function() {
$('.Button').click(function() {
var href = $(this).attr('href');
if( typeof href != "undefined" && href != ""){
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
$('#content').html(data);
ultXML = href;
}
});
}
});
});
But now I m trying to use JQuery Form plugin (with this example http://www.malsup.com/jquery/form/) And it doesnt work (the ajaxForm call), I cant understand how to merge the next code in my orignal code. I try many ways, for example making 2 ready function but it also doesnt work,
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
Where I must put the next piece of code in my original ready function? How can meger both?
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});

Like this, work?
$(document).ready(function() {
$('.Button').click(function() {
var href = $(this).attr('href');
if( typeof href != "undefined" && href != ""){
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
$('#content').html(data);
ultXML = href;
}
});
}
});
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});

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

How to use SweetAlert success with OK button?

I have created a SweetAlert using the code below. After I used this, the result was shown BUT I am not pressing OK yet, already jumped to URL that I set.
This is a SweetAlert script I created (I save in my script when I want to use then I take it from because I'm using Laravel framework).
<script type="text/javascript">
function showSuccessSwal(message) {
Swal.fire(
'Success',
message,
"success"
);
}
function showErrorSwal(message) {
Swal.fire(
'Error',
message,
"error"
);
}
</script>
And this is a script I'm using:
<script type="text/javascript">
$('#somthing-form').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: 'POST', // GET, POST, PUT
url: form.attr('action'),
data: form.serialize(),
success: function(result) {
showSuccessSwal(result.message);
window.location.href="{{ route('something.index') }}";
},
error: function(xhr) {
var errorString = '';
var errors = xhr.responseJSON.errors;
Object.keys(errors).forEach(function(key) {
var error_message = errors[key];
$.each(error_message, function(key, value) {
errorString += value + '\n';
});
});
showErrorSwal(errorString);
}
});
});
</script>
I want the result to work like this:
I press a submit button.
Display a SweetAlert with an OK button.
Wait for the user to press the OK button then go to the URL I set (not straight jump to URL before I press OK button).
you need to call the swal before you call the ajax
swal({
title: 'Are you sure to go ahead?,
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, please!'
}).then(function(result) {
if (result.value) { // when you click `yes, please!`
$.ajax({
type: 'POST', // GET, POST, PUT
url: form.attr('action'),
data: form.serialize(),
success: function(result) {
showSuccessSwal(result.message);
window.location.href="{{ route('something.index') }}";
},
error: function(xhr) {
var errorString = '';
var errors = xhr.responseJSON.errors;
Object.keys(errors).forEach(function(key) {
var error_message = errors[key];
$.each(error_message, function(key, value) {
errorString += value + '\n';
});
});
showErrorSwal(errorString);
});
}
});

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

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.

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.

Resources