Geo Api in TPL file - javascript

I am using this code to display a div only for clients from United Kingdom and it works through built-in page builder - prestashop.
Unfortunately I cannot make it work in tpl file for address form.
Basically I need a text below the address form.
<div class="hide GB">text</div>
<script type="text/javascript">
{literal}
$.get("https://freegeoip.app/json/", function (response) {
document.getElementsByClassName(response.country_code)[0].style.display = "block";
}, "jsonp");
{/literal}
</script>
I also tried this one:
{literal}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>$.ajax("https://freegeoip.app/json/")
.done(function (e) {
$('.hide').eq(e.country_code === 'GB' ? 0 : 1).show();
});</script>
<div class="hide">text</div>
<div id="country_code"></div>
{/literal}
They both work in the fiddle. They both work in the page builder when added as raw html (without literal tags ofc)
However I cannot make them to work in adrress-form.tpl file for some reason. The text just wont show. However the country code is being displayed where I want it. It is just the text that wont.
Any ideas?
Regards

{literal}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="GB">text</div>
<script>$.get("https://freegeoip.app/json/", function (response) {
$("#country_code").html(response.country_code);
if(response.country_code=='GB'){
document.getElementById(response.country_code).style.display = "block";
}
}, "jsonp");</script>
{/literal}
I actually solved this with this code.
CSS wise:
#GB{display:none;}

Related

Javascript of selected php file won't load when using JQuery's load(file.php) method

I have a master container php file with a div container. Initially, the div container doesn't have any content or html children by default when page is loaded. I use JQuery to load php files to this div container when the user clicks a navigation item in the navbar.
landingpage.php
<?php
require_once 'navbar.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin | Dashboard</title>
<link rel="stylesheet" href="css/dashboard_admin.css">
</head>
<body>
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<div class="container" id="content_container">
<div class="div_dashboardLabel" id="dashboard_Label">
<h2 id="label_Dashboard">Admin Dashboard</h2>
</div>
</div>
<!-- END OF CONTENT CONTAINER-->
</div>
<!-- end of wrapper-->
<script src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
var user = '<?php echo json_encode($user);?>';
var role = '<?php echo json_encode($role); ?>';
</script>
<script src="js/landingpage.js"></script>
</body>
</html>
landingpage.js
/* GLOBAL VARIABLES WITHIN THIS DOCUMENT*/
var div_content_container = $("#content_container");
var navitem_dashboard = $("#admin_dashboard");
var navitem_admin_account_management = $("#admin_accountmanagement");
var userObj = JSON.parse(user);
var roleObj = JSON.parse(role);
var logout = $('#logout');
/* END */
$(document).ready(function(){
loadDashboard(); // dashboard is loaded as default view.
navitem_admin_account_management.on("click",loadAccountManagement);
});
function loadDashboard() {
var url_admin_dashboard = 'view/admin_dashboard.php';
var url_teacher_dashboard = 'view/teacher_dashboard.php';
var url_student_dashboard = 'view/student_dashboard.php';
div_content_container.html('');
if (roleObj.rolename === 'Administrator') {
div_content_container.load(url_admin_dashboard);
} else if (roleObj.rolename === 'Teacher') {
div_content_container.load(url_teacher_dashboard);
} else if (roleObj.rolename === 'Student') {
div_content_container.load(url_student_dashboard);
}
}
function loadAccountManagement(){
var url = 'view/admin_accountmanagement.php';
div_content_container.html('');
div_content_container.load(url);
}
Everything works as expected for landingpage.php which uses landingpage.js for the front end. No problem.
The problem is when admin_accountmanagement.php file is loaded in div_content_container. The JS of admin_account_management.php doesn't seem to bind to elements:
function loadAccountManagement(){
var url = 'view/admin_accountmanagement.php'; // has its JS file
div_content_container.html('');
div_content_container.load(url);
}
For example, let's take url which is 'view/admin_accountmanagement.php' This page gets loaded within div_content_container when user clicks a navbar item Account Management
as in
<div class="wrapper">
<!-- CONTENT CONTAINER's content depends on what was clicked on navbar -->
<div class="container" id="content_container">
<!-- view/admin_accountmanagement.php loaded here -->
</div>
<!-- END OF CONTENT CONTAINER-->
</div>
There are no problems displaying the page or replacing the current element contained in the div_content_container. The problem is, the JS file attached to view/admin_accountmanagement.php doesn't seem to apply when view/admin_accountmanagement.php page is loaded in div_content_container
The view/admin_accountmanagement.php is loaded but the click events binded to the elements of view/admin_accountmanagement.php doesn't work. I know this because I tried to display an alert() message on $(document).ready()
admin_accountmanagement.php
<body>
<div>
<button class="button" id="btn_AddUser">
Add New User
</button>
</div>
<script src="js/admin_accountmanagement.js"></script> <!-- this JS doesn't seem to get binded when this page is loaded in the div_content_container -->
</body>
admin_accountmanagement.js
var btn_add_user = $('#btn_AddUser');
$(document).ready(function(){
alert("TEST"); //doesn't work no alert message.
btn_add_user.on("click",test); //doesn't work no alert message
});
function test(){
alert("testing"); //doesn't work. no alert message
}
I'm only able to display the page but when I click on the <button id="btn_AddUser"> nothing happens.
How can I solve this given the how I structured the loading of pages to div_content_container?
Thanks in advance.
Change your admin_accountmanagement.js to
var btn_add_user = $('#btn_AddUser');
alert('Account management js loaded'); // this should show alert
$(document).on("click",btn_add_user,test);
function test(){
alert("testing"); //doesn't work. no alert message
}
This method works because the binding is not dependent on "document ready" as document ready has already been fired when you loaded the parent page for the first time
#jordan i agree with #Magnus Eriksson as it is better to bind it on('event','selector','function') but make use of .off() before your .on() as you are playing with dynamic content which may cause multiple binding of the function. And if you are still not able to get the binding event to work you can try injecting the .js file in your page's head section after the load of your content like: $('head').append('<script src="admin_accountmanagement.js"></script>'). With your load() function in your js to bind the click event.
Or, your use the below code snippet:
function LoadContent()
{
var url = 'view/admin_accountmanagement.php';
var jssrc = 'js/admin_accountmanagement.js';
div_content_container.html('');
div_content_container.load(url);
if($('head').find('*[src="'+jssrc+'"]').length==0)
{
//the below approach have some consequences related to it as you will not be able to see the injected js in your developers tool's Sources(in chrome).
$('head').append('<script src="'+jssrc+'"></script>');
}
}
and then on your .js will look like this:
var btn_add_user = null;
$(window).load(function(){
alert("TEST");
btn_add_user = $('#btn_AddUser');
btn_add_user.off('click').on("click",test); //use .off('event') if load() is being called multiple times.
});
function test(){
alert("testing");
}

Create a dynamic dropdown form that loads its data from a JSON file using JQuery

In a class, I was asked to make a dynamic drop-down menu in a form using HTML5 and JavaScript. I did that here.
Now, I need to call data from a JSON file. I looked at other answers on SOF and am still not really understanding how to use JQuery to get info from the JSON file.
I need to have 2 fields: the first field is a Country. The JSON key is country and the value is state. A copy of the JSON file and contents can be found here. The second drop-down field adds only the values / arrays related to its associated Country.
Here is a copy of my HTML5 file:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
Here is a copy of the JS file I wrote so far that tries to get the data from the JSON file and fails:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the content from the other JS file that adds the field instruction:
var selectYourCountry = document.getElementById('selectCountry');
selectYourCountry.innerHTML = "Select Your Country: ";
var selectYourState = document.getElementById('selectState');
selectYourState.innerHTML = "Select Your State";
This was supposed to at least add the values to the field, but nothing but empty boxes appear on the web page.
I then need to make a conditional statement like the one at here but calling or referencing data from the JSON file.
I have only taken some HTML and JavaScript courses, not JQuery and JSON. So, your help will greatly increase my knowledge, which I will be very grateful for.
Thank you!!
I found this SOF answer and changed my JS file to the following:
$(document).ready(function()
{
$('#locationSelector').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"countryState.JSON",
dataType: "json",
success: function (data) {
$.each(data.country,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#locator');
});
}
});
});
});
And, I edited my HTML document as follows:
<form id="locationSelector" enctype='application/json'></form>
I removed and added back the <select> tags and with the following at least I get a blank box:
`<form id="locationSelector" enctype='application/json'>
<select id="locator"></select>
</form>`
I feel like I am getting closer, but am still lost.
Can you try this:
$.get("countryState.JSON", function( data ) {
var html = "";
$.each(data.d, function(i, el) {
console.log(el);
html += "<option value='"+Your value+"'>"+Your displayed text+"</option>";
});
$('#state').html(html);
});

jquery bulk upload javascript issue

I am running into a javascript issue where it's getting a "Uncaught ReferenceError: $ is not defined". With my reading I think it's the order of when I am trying to do $(document).ready before the javascript is loaded up but I am not sure what to do about it. I have tried moving the jquery and the fileuploadmulti above the script but then I get "Uncaught TypeError: $(...).uploadFile is not a function" and then I go down the road of chicken and egg and don't know what is correct. Any help or point in the right direction would be helpful. Thank you.
<script>
//This is where my error shows up
$(document).ready(function(){
var settings = {
url: "/index.php/upload",
method: "POST",
allowedTypes:"jpg,png,gif,doc,pdf,zip",
fileName: "myfile",
multiple: true,
onSuccess:function(files,data,xhr)
{
$("#status").html("<font color='green'>Upload is success</font>");
},
afterUploadAll:function()
{
alert('All Files uploaded');
},
onError: function(files,status,errMsg)
{
$("#status").html("<font color='red'>Upload is Failed</font>");
}
};
$("#mulitplefileuploader").uploadFile(settings);
});
</script>
<script src="/js/jquery.js"></script>
<script src="/js/fileuploadmulti.min.js"></script>
<div class="boxed link">
<div id="mulitplefileuploader">Upload</div>
<div id="status"></div>
</div>
<div class="col-lg-12">
<h1>Adding pages to <?php echo $model->name; ?></h1>
</div>
First check whether JQuery is loaded or not.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
And wrap the all JQuery code inside $(document).ready(function(){ \\code here }); function.
$(...).uploadFile is not a function error because you are not loading the fileupload plugin properly.
Check all script tag URL'S are right or not.
You are using the $ before including jQuery. Try to include it before.
Try to include
<script src="/js/jquery.js"></script>
<script src="/js/fileuploadmulti.min.js"></script>
before $(document).ready(function(){ });

Can't pass a javascript variable to a php tag

I want to display a javascript variable in the tag in the HTML page but it doesn't appear when I click the button. Can anyone tell me what I'm doing wrong?
HTML
<button name = "presser">go </button>
<p id = "display"></p>
<script type ="text/javascript" src ="jquery.js"></script>
<script type ="text/javascript" src = "processor_file.js"></script>
Javascript
$(":button").click(function(){
$.get("middleman.php", {theword: "happen"},function(data,status){
$.getElementById("display").innerHTML = data;
});
});
PHP code from middleman.php
<?php
if(isset($_GET["theword"])){
$token = $_GET["theword"];
echo substr($token, 1, 3);
}
?>
The word is successfully passed to the javascript page from the php page but when I try to display it through the <p> tag, nothing happens.
You are mixing vanilla js and jquery, you should do as follows:
$(":button").click(function(){
$.get("middleman.php", {theword: "happen"},function(data,status){
$("#display").html(data);
});
});
$.getElementById should be document.getElementById. Or use the jQuery function
$("#display").html(data);

How do I get past the jQuery error "$ not found error"?

MAIN WINDOW
// some javascript
//some html
//here ajax-call to load all divs
//all divs hidden by default
//based on user choice(from select option), show selected group of divs
//click any shown div to call corresponding popup
POPUP WINDOW
//edit contents of that div.
//on close i need
1. refresh main window to load all divs
2. select the previously selected user option(from select option)
3. show corresponding divs only
4. most important is i have to give the user the main page,
where they clicked the div before(not the page starting always!)
I tried and i am left with " $ not found error ". any ideas..? suggestions?
this is the main window
<script type="text/javascript" src="jquerymin.js"></script>
<script type="text/javascript">
var visible_status=0;
function selectFn(sno){
if(sno==1){
$('#id2').hide();
$('#id1').show();
visible_status=1;
}else if(sno==2){
$('#id2').show();
$('#id1').show();
visible_status=2;
}
}
function popitup(url) {
newwindow=window.open(url+'?parent_status='+visible_status,'name');
if (window.focus) {newwindow.focus();}
return false;
}
</script>
<select name='optionw'
onchange="selectFn(this.options[this.selectedIndex].value);">
<option value="">Select</option>
<option value="1">Div1</option>
<option value="2">All</option>
</select>
<div id='id1' style="display:none;">DIV1</div><!--by ajax i am loading-->
<div id='id2' style="display:none;">DIV2</div><!--these divs-->
<button onclick="popitup('popup.php');">popUp</button><br><!--and these-->
popupwindow
<script type="text/javascript" src="jquerymin.js"></script>
<script type="text/javascript">
var parent_status='<? echo $_GET[parent_status];?>';
function closePopup() {
window.opener.history.go(0);
//alert('going to call parent selectFn('+parent_status+')');
window.opener.selectFn(parent_status);
self.close();
}
</script>
...Here editing a part of the main page content...
<input type=button value=close_popup onclick="closePopup();">
If i remove the comments in the closePopup function , it works as expected. Any help to make it work without commnted line.
I would suggest that perhaps you're not linking to the jQuery library properly or have it linked in the wrong order. Could you provide more details as to what you're asking? Do you want the code to do this, or are you just asking about the jQuery object not being found?
get firebug plugin for firefox. load your page .. go to firebug console .. type $ and if it doesnt say 'function()' you haven't included the jQuery library properly
I'm trying to understand your question; it's very unclear what you're describing. Is the code you're showing coming from your web browser once you've loaded it (by viewing the source) or is it prior to being evaluated on the server?
What happens if you change this line in the popup:
var parent_status='<? echo $_GET[parent_status];?>';
to this:
var parent_status=1;
According to what I have understood here is the code below and check it if this works for you:
Paste this code inside main window:
<?php if(isset($_GET['parent_status'])): ?>
$(document).ready(function(){
selectFn(<?php echo $_GET['parent_status'] ?>);
})
<?php endif ?>
Below this code:
function popitup(url) {
newwindow=window.open(url+'?parent_status='+visible_status,'name');
if (window.focus) {newwindow.focus();}
return false;
}
And, replace the closePopup function inside popup window with this code:
function closePopup() {
var href = window.opener.location.href;
if((pos = href.lastIndexOf('parent_status=')) >= 0)
{
var patt = new RegExp('parent_status=' + parent_status);
href = href.replace(patt, 'parent_status='+parent_status);
} else {
href = window.opener.location.href + '?parent_status=' + parent_status
}
window.opener.location.href = href;
self.close();
}
Hope this helps.

Categories