How to clear the cart using ajax in shopify? - shopify

I need to add link on home page or any other page with the help of that link I want to clear all my cart items.
can any one help me with this

You can use Shopify's clear.js API. Follow these steps:
Add a link to clear cart:
Clear Cart
Add this script in your custom JS file:
$('.clear-cart').on('click',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/cart/clear.js',
success: function(){
alert('Cleared the cart!');
},
dataType: 'json'
});
})

Related

Why isn't express's res.render called inside the PUT method?

I have an express app with ejs view engine.
In the ejs template, I have a button with an onClick event to trigger a fetch request:
<button class="remove-btn" onclick="removeGroceryItem('<%= index %>')" >Remove</button>
the fetch function
function removeGroceryItem (id) {
fetch('/', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ groceryItem: id })
})
.then((value)=> console.log(value))
.catch((e)=>console.error(e))
}
The express app route handler:
/* PUT grocery list*/
app.put('/', function(req, res, next) {
groceryItemsContainer.splice(Number.parseInt(req.body.groceryItem), 1)
res.render('index', {
title: 'Express Grocery List App',
notification: 'removed',
groceryList: groceryItemsContainer
})
res.end();
})
The PUT request is received with a status of 200. But the res.render does not seem to be triggered -- why is that??
It appears from your comment that you are expecting the result of your res.render() to display in the browser. That is NOT what an Ajax call using fetch() does from your browser Javascript. It ONLY gets the content back to your Javascript. It does not display anything in the browser.
So, the content you res.render() goes back to your Javascript in your web page and the console.log(value) you have in your Javascript in the web page should actually be showing the content in the console from the res.render(). If you want that content to display in the browser, then you need to insert that content into the current browser DOM yourself with your own Javascript.

Fetch Product variant by SKU works in storefront but not in independent JavaScript program

If I put below script in theme.liquid(Shopify storefront), I get expected result:
<script>
const GRAPHQL_URL = 'https://<my-store>/admin/variants/search.json?query=sku:big-mug-black';
const GRAPHQL_BODY = {
'method': 'GET',
'headers': {
'Content-Type': 'application/json',
},
};
fetch(GRAPHQL_URL, GRAPHQL_BODY)
.then(res => res.json())
.then(console.log)
.catch(console.error);
</script>
But If I try to execute same piece of code from JavaScript program, I get 404({errors: "Not Found"})
const GRAPHQL_URL = `https://<my-proxy>.herokuapp.com/https://<my-store>/admin/variants/search.json?query=sku:big-mug-black`;
const STOREFRONT_ACCESS_TOKEN = '<my-token>';
const GRAPHQL_BODY = {
'method': 'GET',
'headers': {
'Authorization': `Basic ${btoa('<my-api-key>' + ':' + '<my-password>')}`,
'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN,
'Content-Type': 'application/json',
},
};
fetch(GRAPHQL_URL, GRAPHQL_BODY)
.then(res => res.json())
.then(console.log)
.catch(console.error);
Note: I can fetch all products using same program, so its not an permission issue. Is there something I need to add/remove to achieve same result in my local JavaScript program? Thank you.
I might have solution just for your need.
You gonna need following accesses:
read_products - for finding product
read_script_tags - for read existing script tags
write_script_tags - for writing new script tag
First on your application create console action that will be run automatically every X hours. That action shall download all existing products. You gonna need save them to local database.
Things to remember during downloading all products.
Api limits watch for them in headers (X_SHOPIFY_SHOP_API_CALL_LIMIT)
Pagination, there is variable link in headers (Api pagination)
When you have stored all products locally, you can create search method for it using SKU.
When you have working method you can create find method in your controller. You will use this method to create request from shopify page to your server.
After creating this you can add JS by yourself or even better automate it with script tags.
ScriptTag on Shopify are basically javascript code that you host on your side and they are automatically loaded TO EACH page in shopify (except basket).
POST /admin/api/2021-01/script_tags.json
{
"script_tag": {
"event": "onload",
"src": "https://djavaskripped.org/fancy.js"
}
}
With that you can add javascript that can be used to create find request on your website. And you can return result back.
I created simplified graph for that.
.

Submitting two forms in one button - Yii FrameWork

I am trying to submit more than two forms in one button by using JS, how could i proceed to do this for yii active forms.
This is not specific to Yii. You can handle this using javacript. Write a function for on click event of the submit button. serialize the form1, serialize the form2. Concatenate two serialize results and pass it to an ajax request.
$('your_submit_button_selector').on('click', function(event){
event.preventDefault();
formData = $('your_form1_selector').serialize()+$('your_form2_selector').serialize();
$.ajax({
url: submitUrl,
data: formData,
type: 'POST',
success: function(data) {
...
}
});
});
Why don't you use this way...
jQuery('#yourForm1').submit();
jQuery('#yourForm2').submit();
Good Luck.

Call controller of a project from a diff project using jQuery Ajax

Can we call a controller of one project from another project using Jquery Ajax, MVC4?
If we can, how to do that?
I have tried the below but it is not working:
$.ajax({
url: "/test/Testing",
dataType: "json",
data: {
//We need to send some in future...
},
success: function (data) {
$("div[data-stage = \"stagerWidget\"]").html(data.results[0]);
return;
}
});
This is solved by specifying type of request (get or post).

Wikipedia list=search REST API: how to retrieve also Url of matching articles

I'm studying Wikipedia REST API but I'm not able to find the right option to get also URLs for a search query.
this is the URL of the request:
http://it.wikipedia.org/w/api.php?action=query&list=search&srsearch=calvino&format=xml&srprop=snippet
this request outputs only the Title and the Snippet but no URLs for articles.
I've checked wikipedia API documentation for the list=search query but seems there is no option to get also URLs.
Best Regards,
Fabio Buda
You can form the URL of the article easily by yourself from the title. For the Italian Wikipedia, it's http://it.wikipedia.org/wiki/ followed by the URL-encoded title of the article. It's as simple as that.
The actual URL of the article also replaces spaces with underscores, but you don't have to do that if you don't want to, the URL with spaces redirects to the one with underscores.
EDIT: You can get the URL, but it's not possible to get search-related information at the same time. To do that, use the list as a generator. For example:
http://it.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=calvino&format=xml&gsrprop=snippet&prop=info&inprop=url
But I think changing the format of page URLs is very unlikely: too many other people rely on that.
I've found impossible to retrieve both description and url at once, so I split in two javascript method, the first get description, the second get url:
function get_wiki_info() {
$.ajax({
url: 'http://it.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=city]").val(), format: 'json' },
dataType: 'jsonp',
success: function (data) {
console.log('wiki', data.query.search[0].snippet);
$('#info-wiki-text').html(data.query.search[0].snippet);
get_wiki_links();
},
fail: function (data) {
$('#info-wiki-text').html("Impossible retrieve information for " + $("input[name=city]").val());
}
});
}
function get_wiki_links() {
$.ajax({
url: 'http://it.wikipedia.org/w/api.php',
data: { action: 'query', generator: 'allpages', search: $("input[name=city]").val(), format: 'json', gapfrom: $("input[name=city]").val(), gapto: $("input[name=city]").val(), prop: 'info', inprop: 'url' },
dataType: 'jsonp',
success: function (data) {
console.log('wiki', data.query.pages);
$.each(data.query.pages, function (key, val) {
$('#wiki-city-link').attr('href', val.fullurl);
});
},
fail: function (data) {
console.log(data);
}
});
}
If you prefer, to retrieve description:
https://it.wikipedia.org/w/api.php?action=query&list=search&srsearch=Your%20Params&utf8=
to retrieve url:
https://it.wikipedia.org/w/api.php?action=query&generator=allpages&search=Your%20Params&gapfrom=Your%20Params&gapto=Your%20Params&prop=info&inprop=url&utf8=