How can I make a condition for a variable? - opencart

I have a working GeoIP detection code on the 'product.tpl' page in Opencart.
How can I make a condition for a variable?
Example: if the "city"="London" then php echo "Your city is London".
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<div>Country: <span id="country"></span></div>
<div>State: <span id="state"></span></div>
<div>City: <span id="city"></span></div>
<script>
$.ajax({
url: "https://geoip-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function( location ) {
$('#country').html(location.country_name);
$('#state').html(location.state);
$('#city').html(location.city);
}
});
</script>

Just check City and insert message that you need.
For example
var text = '';
if(location.city == 'London'){
text = 'XXX';
} else {
text = 'YYY';
}
$('#city').parent().after('<p>' + text + '</p>');

Related

use django "include" inside a js function

I am doing a search page in which parameters are sent by ajax and then upon reception of the queryset I rebuild my cards. The whole thing is classic and working ok, here is a simplified version of the thing. Lots of lines killed or modified since it is not really the subject of the post
let getobject = async (value,url) => {
var res2 = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
"X-CSRFToken": getCookie("csrftoken"),
},
body: JSON.stringify({
value: value,
})
})
let data2 = await res2.json();
videoitems.innerHTML = ''
modalbin.innerHTML = ''
data2["data"].forEach(async item => {
if (item.ext == '.mp4') {
const dynamicreation = async () => {
let dyncontent3 = await createnewcard(item)
let placing = await videoitems.appendChild(dyncontent3);
}
const nooncares2 = await dynamicreation()
} else if (item.ext == ".pdf") {
const dynamicreation2 = async () => {
let dyncontent4 = await createnewcard(item)
let placing2 = await videoitems.appendChild(dyncontent4);
}
const nooncares4 = dynamicreation2()
}
})
}
the createnewcard function
var createnewcard = item => {
var dyncontent = document.createElement("div");
dyncontent.innerHTML =
`<div class="m-2 extralarge-modal video${item.id}">
<div data-reco="${item.id}"
class="extralarge-modal bg-white rounded-lg border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-700">
<div class="p-5">
<p class="mb-3 font-normal text-gray-700 dark:text-gray-400">
${item.title}
</p>
</div>
</div>
</div>`;
return dyncontent
}
What I would like to know is if it would be possible to mix this js with the django "include" function and instead of using js template litterals use an html component of the card that I would include upon looping in the data reveived. I could also maybe include it inside the createnewcard js function but so far it all failed quite miserably.
Thanks a lot
Yes, you've to create card.html or whatever you can name then you've to just include inside your js make sure you use same variables while looping in js eg.(item)
card.html
<div class="m-2 extralarge-modal video${item.id}">
<div data-reco="${item.id}"
class="extralarge-modal bg-white rounded-lg border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-700">
<div class="p-5">
<p class="mb-3 font-normal text-gray-700 dark:text-gray-400">
${item.title}
</p>
</div>
</div>
</div>
and inside your Js do like this
var createnewcard = item => {
var dyncontent = document.createElement("div");
dyncontent.innerHTML = `{% include "card.html" %}`
return dyncontent
}

Display custom success or error progress bar

I am making a django app that displays a progress bar. So far I have got it working to display a progress bar using this library and the following code which they suggested.
<div class='progress-wrapper'>
<div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width:
0%;"> </div>
</div>
<div id="progress-bar-message">Waiting for progress to start...</div>
<script src="{% static 'celery_progress/celery_progress.js' %}"></script>
<script>
// vanilla JS version
document.addEventListener("DOMContentLoaded", function () {
var progressUrl =
"{%
try:
url 'celery_progress:task_status' task_id
catch:
pprint("PHEW")
%}";
CeleryProgressBar.initProgressBar(progressUrl);
});
</script>
However, how might i integrate the above code with the code below to get it to display success or error:
function customSuccess(progressBarElement, progressBarMessageElement) {
progressBarElement.innerHTML = (
'<figure class="image"><img src="/static/projects/images/aww-yeah.jpg"></figure>'
)
progressBarElement.style.backgroundColor = '#fff';
progressBarMessageElement.innerHTML = 'success!'
}
function customError(progressBarElement, progressBarMessageElement) {
progressBarElement.innerHTML = (
'<figure class="image"><img src="/static/projects/images/okay-guy.jpg"></figure>'
)
progressBarElement.style.backgroundColor = '#fff';
progressBarMessageElement.innerHTML = 'shucks.'
}
CeleryProgressBar.initProgressBar(taskUrl, {
onSuccess: customSuccess,
onError: customError,
});
just change the script in your html with this one:
<script>
function customSuccess(progressBarElement,
progressBarMessageElement) {
progressBarElement.innerHTML = (
'<figure class="image"><img src="/static/projects/images/aww-yeah.jpg"></figure>'
)
progressBarElement.style.backgroundColor = '#fff';
progressBarMessageElement.innerHTML = 'success!'
}
function customError(progressBarElement, progressBarMessageElement) {
progressBarElement.innerHTML = (
'<figure class="image"><img src="/static/projects/images/okay-guy.jpg"></figure>'
)
progressBarElement.style.backgroundColor = '#fff';
progressBarMessageElement.innerHTML = 'shucks.'
}
document.addEventListener("DOMContentLoaded", function () {
var progressUrl = "{% url 'celery_progress:task_status' task_id %}";
CeleryProgressBar.initProgressBar(progressUrl, {
onSuccess: customSuccess,
onError: customError,
});
});
</script>
i tried it with the same app. it works! :)
don't forget to change this one to a valid url:
<img src="/static/projects/images/aww-yeah.jpg">)

Comparing value from html to context

I need to compare a value (variable) extracted from a page to context.
For example:
Color is a dropdown selection.
$(document).ready(function(){
$("#color").change(function() {
var selected_color = $(this).val() ;
{% if context_value == selected_color %}
.. do something
{% endif %}
})};
Is this possible ? If not, is there some solution for such case ?
I recommend you use Ajax to communicate asynchronously between JavaScript and python (without refreshing the page).
your JS:
$(document).ready(function(){
$("#color").change(function() {
var selected_color = $(this).val() ;
$.ajax({
method: "POST",
url: 'color_check',
data: selected_color,
success: handleFormSuccess,
error: handleFormError,
})
})
function handleFormSuccess(data, textStatus, jqXHR){
.. do something
}
function handleFormError(jqXHR, textStatus, errorThrown){}
};
Your python view:
def color_check(request):
if request.is_ajax():
selected_color = request.POST
context_value = 'Red'
if selected_color == context_value:
return JsonResponse(True)
EDIT: Arun Singh's solution is simpler and works too. I would only make the paragraph hidden from the user:
<p style="display:none" id="my-data" data-name="{{context_value}}"></p>
<p id='data'>{{ context_value }}</p>
or
<p id="my-data" data-name="{{context_value}}"></p>
$(document).ready(function(){
$("#color").change(function() {
var selected_color = $(this).val() ;
var djangoData = $('#data').val();
if (djangoData === selected_color){
console.log('do something)
}else{
console.log('do something else')
}
})};

Opencart if product available Button show else disable that button

Hi i'm creating a application using Opencart. It fully customized, i have doubt in this.
I have filter.tpl page, in this page i need to display and hide button based on product availability
Eg:
If product available show like this
enter image description here
else button show like this enter image description here
Am trying this fowling code using ajax
filter.tpl
$('input[name=\'filter_name\']').autocomplete({
'source': function(request, response) {
$.ajax({
url: 'index.php?route=catalog/product/getProductCheck' + encodeURIComponent(request),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
label: item['name'],
value: item['product_id']
}
}));
}
});
},
'select': function(item) {
$('input[name=\'filter_name\']').val(item['label']);
}
});
In controller
product.php
public function getProductCheck()
{
/*Some code here*/
}
So you can use if ($product['quantity']) statement for example
I got the out put am using javascript following code
<div class="form-group">
<div style='display:none;' id='instock'>
<a class='instock-btn'>Product / Solution Available</a>
<input type='submit' class='btn-orng available' name='' value="Click here for more details" size='20' />
</div>
<div style='display:none;' id="outstock">
<input type='submit' class='outstock-btn' name='' value="Product / Solution Not Available" size='20' />
<input type='submit' class='btn-orng' name='' value="We will contact you at the earliest" size='20' />
</div>
</div>
script
$(document).ready(function(){
$('#dia1').on('change', function() {
//var value =
if (this.value <='320' )
{
$("#instock").show();
$("#outstock").hide();
}
else
{
$("#instock").hide();
$("#outstock").show();
}
});
$('#len1').on('change', function() {
//var value =
if (this.value <='310' )
{
$("#instock").show();
$("#outstock").hide();
}
else
{
$("#instock").hide();
$("#outstock").show();
}
});
});

href to id not working in Opencart

In information section, I have a menu with a href to id, but they are not working. I don´t know the reason since it´s very simpl. In the menu:
PRECIOS
In the section:
<h2 id="terms-prices">PRECIOS</h2>
I´ve finally fixed it with jquery:
$(document).ready(function() {
$(window).load(function() {
$(function(){
$('a[href^=#]').click(function(e){
var id = $(this).attr('href').substr(1);
var pos = $('#' + id).offset().top - $('#nav').height() * 1.2;
$('body').animate({ scrollTop: pos });
e.preventDefault();
});
});
});
});