Back button support with Wordpress AJAX - javascript

I have been reading and researching how to support the back button on my site while using jquery ajax in wordpress. I have read about implementing hashes but there is still something I am not quite understanding. I am not really sure how implement it into my current code base.
ajax.js
jQuery(document).ready( function ($) {
$(".product-cat").click(function(e) {
e.preventDefault;
$.ajax({
url: ajaxproducts.ajax_url,
type: 'post',
data: {
action: 'ajax_product_load',
datavar: $(this).data( 'id' )
},
success: function ( result ) {
$("#main").empty();
$("#main").html( result );
}
})
})
});
plugin-functions.php
Product Category Name
When a user clicks the link, all data is retrieved through ajax just fine and loads all the products for that selected category. However, if the back button is pressed, it does not go back to the product category's page rather it goes back to the home page. I want it to be able to go back to categories page and if a user wants to bookmark the product page that they selected they should be able to.
Any help trying to figure this out would be appreciated.

Related

How do I clear the Shopify cart whenever the homepage is loaded?

I am a designer and have been asked by a client if I can help them with a certain piece of functionality on their store.
They are only selling one type of product on their store, with different bundle options available. Since customers will only ever be purchasing 1 product at any given time from the store, they have asked me if I can have it so that only 1 product can be in the cart at any given time, and if the customer were to go back from the checkout page (or any other page) and select a different bundle of the product, it would remove the other product from their cart.
I don't have any AJAX cart items (drawers, slideout cart etc) on the site so using AJAX would be an option here. My knowledge of anything other than HTML, CSS and some basic JS is very limited.
With my limited knowledge, I was thinking that running a script that clears the cart when the Homepage is loaded would work well, as there are really only 3 pages on the site, the Homepage, Cart page and Checkout page. This is code that I found, but I am not sure how to implement it or if it would even work at all:
$(document).ready(function() {
$('.clear-cart').on('load',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/cart/clear.js',
success: function(){
alert('I cleared the cart!');
},
dataType: 'json'
});
})
});
Your effort to help out this noob in need would be much appreciated!
you need to check the class of the page like on the default debut theme it uses the class template-index for the index page aka homepage.
and add the condition into the code to check it.
$(document).ready(function() {
$(document).on('load',function(e){
if( !$('body').hasClass('template-index') ){
return;
}
e.preventDefault();
$.ajax({
type: "POST",
url: '/cart/clear.js',
success: function(){
alert('I cleared the cart!');
},
dataType: 'json'
});
})
});

Wordpress use ajax on page load from url get parameters

So i am building a search on website, and main search form is on home page where user can input information's like, interests, books, movies.
And that form should submit to another page where search will be displayed.
So it's similar like any other search, but on search page, i should keep parameters in url, so it's not going to be POST, it would be GET.
Home page is something like mywebsite.com
And when form is submitted it's posted with GET parameters so user can keep search results in his url. Submitted post should lead to something like.
mywebsite.com/search?interests=sports&books=harry+potter&movies=moviename
And because it can take some time to search and load results i would like to load the page and than do an ajax post to search function and populate search results once ajax responds.
I've built in past some ajax content loading and post and load data with ajax, but all that while keeping on same page, i never built when you submit content from one page to another in wordpress.
Any suggestions how can i do that and make ajax grab the content ?
I found the answer, and it's actually quite easy, instead triggering ajax with function, for example function with button click.
Just trigger ajax on page load, and don't enqueue script anywhere else except on that page, this would help a bit.
if ( is_page_template('template-search.php') ) {
wp_enqueue_script('ajax_search');
}
This will ensure script is loaded only on that template page, and as for script it self, just load ajax on page ready:
jQuery(document).ready(function($) {
jQuery.ajax({
dataType: 'json',
url: search_flight.ajaxurl,
data: {
action: 'search_flight',
},
beforeSend: function() {
},
success: function(data) {
console.log(data);
},
error: function() {
}
});
});

Better way to reload page if hash change is detected with AJAX content?

I am working with AJAX content. Basically a bunch of products are on one page and when you click a product it currently goes to the product without having to reload the page at all. The product UPC is appended as a hash. Problem is that when a user clicks the back button, it doesn't work. A user currently has to rely on breadcrumbs to go back.
My solution was to use a window on hash change function, which works but obviously forces the page to reload when going forward. Kind of defeats the purpose of AJAX. Is there a better way to navigate to the last item on the page if a user clicks the back button by grabbing its hash value rather than doing what I am currently using below?
$(window).on('hashchange', function() {
var hash = window.location.hash;
var fullURL = window.location.href = "http://www.test.com/product-categories/test.php" + hash;
if (fullURL) {
location.reload();
}
});
Here is how you can do it with History API
function loadProduct(productid, reload){
$.ajax({
...
...
data: {productId : productid},
success:function(){
if(!reload) {
History.pushState('productName', { productId : productid }, '#' + productId)
}
}
})
}
$(product).on('click', function(){
loadProduct( productId , true )
});
$(window).on('popstate', function(){
loadProduct( e.state.productId, false );
});
This way you will store product id each time user clicks on a product. and when they go back & forth, it will get the stored product id and will reload it

Update Shopify cart with ajax without page refresh

I am changing a users Shopify shopping cart with Ajax, the cart is being changed successfully but in order to display the updated cart the user has to refresh the page. I want to display the cart changes WITHOUT a refresh.
I'm using the ajax api just fine, and I can add and remove items with:
Shopify.addItem();
Shopify.removeItem();
Those work great, but they require the user to reload the page to see the new/changed items in their cart. Do you know of a way to display the updated cart WITHOUT a page reload?
So everyone has the complete picture, here is my code:
function poll(products) {
$.ajax({
url: "/apps/proxy",
data: {products: products},
type: "GET",
dataType: "json",
complete: setTimeout(function()
{cartAdd(); poll(products)}, 15000),
success: function(data) {
$.each(data, function(incoming_key, incoming_value){
Shopify.getCart(function(cart){
$.each(cart.items, function(cart_key, cart_value){
if(cart_value.variant_id == incoming_value.id_to_remove){
Shopify.addItem(incoming_value.variant_id, incoming_value.quantity);
Shopify.removeItem(incoming_value.id_to_remove);
console.log("some reason the incoming id is null or maybe not " + incoming_value.variant_id );
}
else if(cart_value.variant_id == incoming_value.variant_id && cart_value.quantity != incoming_value.quantity){
Shopify.changeItem(cart_value.variant_id, incoming_value.quantity);
}
});
});
});
},
});
}
Do an ajax call to the cart page /cart, get the required elements and replace them on the current page.
Add the code for the above after the first $.each function.
you can use the shopify ajax cart, after insert or update call the GET action:
using-ajax-api#get-cart

deleting an account using multiple ajax requests

The user, upon clicking a button(delete) is given the option to delete his account-he must enter his password also to do that.
So I am describing above the 1st ajax request which is made.WHat is returned from the server is a response if there are still bookings(it is a booking web app) made from the user and if he should reconsider-a message appears.
If he insists deleting his account then he must click the delete button again.
The problem(if you have not noticed) is that by clicking again the delete button the above procedure is repeated while the aim now-after the warning message appears-is that the click of the delete button means "yes, despite the bookings I want to delete my account".
So, this delete button must have dual role, one before the warning appear and one after the warning.
What can I do in a situation like this?I was thinking implementing a confirm box but the above are all taking place in a modal box.So a confirm box over a modal I do not think is the correct solution.
Here is the ajax request that is sent when the user first clicks the delete button:
$('.deactivate').click(function(){
event.preventDefault();
var trimmeddelpass=$.trim($('input#del_password').val());
if(trimmeddelpass!=="")
{ $.ajax({
type: "POST",
url: "delaccountajax.php",
data: {"delpass":trimmeddelpass},
success:function(data){
if(data==2)
{$('#warning').html('You have still bookings pending');
$('#warning').show();
}
else if(data==3)
{ window.location.href = "../Frontend/login.php";//proceed deleting the account
}
error:function(jxhr){
alert(jxhr.responseText);}
});
}
Here is the server code:
$output=delete_account($conn,$delpass,$sessionml);
if($output=='2')
{$success='2';}
elseif($output=='3')
{logout();
$success='3';}
echo $success;
Both of the codes above are simplified versions involved since some other stuff were in them too,-they are not needed though for the issue we are dealing.
I have problem implementing the code you propose...it is the right solution of course but...look what is going on,here is the code:
$('.deactivate').click(function(){
event.preventDefault();
deletestate=0;
if(deletestate==0)
{ $.ajax({
type: "POST",
url: "delaccountajax.php",
data: {"delpass":trimmeddelpass},
success:function(data){
if(data==2)
{$('#warning').html('You have booking pending');
$('#warning').show();
deletestate=1
}....
if(deletestate==1){....}
The code above always set the global deletestate to 0,setting it to 1 later has no effect whatsoever...how can i do this?

Categories