How to execute Javascript Functions on a server by Python script? - javascript

I have to execute some Javascript functions from a local machine without using a browser. Searching around the internet, I've found a solution.
This is my python code:
url = "http://url/to/my/php/script.php?variable=HelloWorld"
print("Url: ", url)
urlData = requests.get(url)
print(urlData.url)
And this is my PHP script:
<?php
$variable = $_GET['comune'];
echo '<div id="map"></div>';
echo '<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAXtpSi5amANeo6IcUuPuilyJMWcYc_RxY&libraries=geometry,places">
</script>
<script type="text/javascript" src="../jsLibrary/geoxml3/kmz/geoxml3.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://unpkg.com/popper.js#1.12.6/dist/umd/popper.js" integrity="sha384-fA23ZRQ3G/J53mElWqVJEGJzU0sTs+SvzG8fXVWP+kJQ1lwFAOkcUOysnlKJC33U" crossorigin="anonymous"></script>
<script src="https://unpkg.com/bootstrap-material-design#4.1.1/dist/js/bootstrap-material-design.js" integrity="sha384-CauSuKpEqAFajSpkdjv3z9t8E7RlpJ1UP0lKM/+NdtSarroVKu069AlsRPKkFBz9" crossorigin="anonymous"></script>
<script>$(document).ready(function() { $("body").bootstrapMaterialDesign(); });</script>
<script type="text/javascript" src="../jsLibrary/echarts.min.js"></script>
<script type="text/javascript" src="../jsLibrary/charts_functions.js"></script>
<script type="text/javascript" src="../jsLibrary/geo_visualization_functions.js"></script>';
echo "<script>initMap();</script>";
echo "<script>initZone('$variable');</script>";
echo "<script>initSections('$variable')</script>";
?>
The idea is to generate an html code with php that automatically executes the javascript functions that I need. In fact, calling my php script within a browser all works fine! But if I try to call my php script, as I've done with my python script, anything works. What could be the problem? Is there another workaround?
My problem is executing those javascript functions from python, how can I do this?
Thanks a lot.

Related

Javascript widget appearing only for logged in users

I have a javascript widget, but the widget should only be seen by logged in users.
<script>
window.fwSettings={
'widget_id':77000003788
};
!function(){if("function"!=typeof window.FreshworksWidget){var n=function(){n.q.push(arguments)};n.q=[],window.FreshworksWidget=n}}()
</script>
<script type='text/javascript' src='https://euc-widget.freshworks.com/widgets/77000003788.js' async defer></script>
I have tried to use a php function, but it didnt work:
<?php
if(is_user_logged_in()) {
echo '<script>
window.fwSettings={
'widget_id':77000003788
};
!function(){if("function"!=typeof window.FreshworksWidget){var n=function(){n.q.push(arguments)};n.q=[],window.FreshworksWidget=n}}()
</script>
<script type='text/javascript' src='https://euc-widget.freshworks.com/widgets/77000003788.js' async defer></script>';
}
?>
I placed the code in my footer.php file right before the body-closing tag as the widget should be placed there.
Any help is appreciated! (and yes, I'm very new to coding)
Your code has a quoting problem. You are starting a string with a single quote, ', but then you including additional single quotes inside the string. Make sure to turn on both WordPress and PHP error reporting when debugging, it will warn you about this. The easiest solution is to break out of PHP and switch back to HTML mode.
<?php if(is_user_logged_in()): ?>
<script>
window.fwSettings={
'widget_id':77000003788
};
!function(){if("function"!=typeof window.FreshworksWidget){var n=function(){n.q.push(arguments)};n.q=[],window.FreshworksWidget=n}}()
</script>
<script type='text/javascript' src='https://euc-widget.freshworks.com/widgets/77000003788.js' async defer></script>
<?php endif; ?>

Turn PHP variable into Javascript variable and use that Javascript variable as an argument in a Javascript function

An input from a form in my index.php page is sent to my search.php page. This input is turned into the PHP variable $q with $_GET. How do I turn this PHP variable into a Javascript variable that is a string? Then how do I pass this string as an argument in a Javascript function in the body tag when the page loads? The onload function only works if the first parameter is a string. Here is my simplified code:
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(*PHP variable turned into Javascript string*, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Javascript within your script tag 'should' be ignored if there's a src for it. However you can't have precompiled php in a js file. One option is to set the javascript variables within your php files, then separately include your js files. If your js files make use of those variables, make sure to set the variables first:
<script type="text/javascript">
var q = "<?php echo $q;?>";
</script>
<script src="assets/js/script.js"></script>
The script doesn't work because you're trying to include an external JavaScript file, while also using the same tag for inline script.
This part
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
Should look something like this
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
Fully fixed code
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(q, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Edit: Footnote
As #dossy points out, you should avoid directly passing user input into the HTML code. Use json_encode() to avoid any malicious code or invalid input.
<script>
var q = <?php echo json_encode($q); ?>;
</script>
This is what json_encode() is for. Other answers that use the naive approach of var x = "<?php echo $var; ?>"; will break if $var contains a double quote, for example.
This is the safest way of doing this:
<script type="text/javascript">
var q = <?php echo json_encode($q); ?>;
</script>

Uncaught `TypeError: $(...).dataTable is not a function` in online server, but not in my local server

I have an error TypeError: $(...).dataTable is not a function when logged to my console after i uploaded my files to my online server, but in my local server, this won't appear and my app works fine.
I followed all the instructions here but still doesn't work. And I really don't know how to fix this.
Here's my script below:
<script src="<?php echo base_url();?>assets/grocery_crud/js/jquery-1.11.1.min.js"></script>
<script src="<?php echo base_url();?>assets/grocery_crud/js/jquery_plugins/config/jquery.noty.config.js"></script>
<script src="<?php echo base_url();?>assets/grocery_crud/js/common/lazyload-min.js"></script>
<script src="<?php echo base_url();?>assets/grocery_crud/js/common/list.js"></script>
<script src="<?php echo base_url();?>assets/js/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="<?php echo base_url();?>assets/js/plugins/datatables/dataTables.bootstrap.min.js"></script>
<script src="<?php echo base_url();?>assets/grocery_crud/themes/datatables/js/flexigrid.js"></script>
Please help me. Hope this won't be closed.
I found out that in my live server, the pathing of files is case-sensitive. Unlike in my local server, I can just mix cases and no issues found. In my case, when I call the script like this: <script src="mysite/assets/js/dataTables/jquery.dataTables.min.js"></script> , and the path is assets/js/datatables/jquery.dataTables.min.js , this won't work on a live server where datatables folder is not the same with dataTables folder in my path to call that file.
In the official documentation, it is telling to include datatables.min.js from the cdn. This script contains a definition of both jquery and DataTables.
The second script, bundles/datatables/js/datatables.js, is trying to patch jquery to add the functions initDataTables and dataTable.
Therefore, the order matters.
Here is my /symfony/templates/list.html.twig file for Symfony 4.2 :
<!-- Insert this at the end of your body element, but before the closing tag -->
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.2.1/dt-1.10.16/datatables.min.js"></script> {# Included libraries: jQuery 3 3.2.1, DataTables 1.10.16 #}
<script src="{{ asset('bundles/datatables/js/datatables.js') }}"></script> {# An omines script that patches jquery : add initDataTables function #}
<script>
$(function() {
// 'datatable' is defined in the symfony controller.
// datatable_settings Twig function renders a compact JSON string with the configured settings required for initialization.
var table = $('#presidents');
if (table && table.initDataTables)
table.initDataTables({{ datatable_settings(datatable) }});
});
</script>

Dreamweaver Shows Red Line Near Script Tag In PHP File

Here is my code in product.php file where a red line is shown by dreamweaver editor when i try to add the constant path of my own which i define in my php configuration.php file. Here is the snapshot so you can understand properly.
my product.php file snapshot is here
<?php require_once('header.php'); ?>
<script type="text/javascript">
$(document).ready(function() {
$('#search_div').get(0).scrollIntoView();
});
</script>
<script type="text/javascript" src="<?php echo BASE_PATH;?>js/jssor.js"></script>
<script type="text/javascript" src="<?php echo BASE_PATH;?>js/jssor.slider.js"></script>
I tried but can't able to fix the error. Please, any help would be appreciated.
put your javascript tag's code with src attribute i.e with source file above the document.ready script and right after the php code where you call your header.php file like this
<?php require_once('header.php'); ?>
<script type="text/javascript" src="<?php echo BASE_PATH;?>js/jssor.js"></script>
<script type="text/javascript" src="<?php echo BASE_PATH;?>js/jssor.slider.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#search_div').get(0).scrollIntoView();
});
</script>
When you write any coded script tag in the php file make sure that your coded script tag should be called below the script tag in which you call your javscript source file with php define constants.

Yii and jquery and javascript inclusion...confused

Crossposting from http://www.yiiframework.com/forum/index.php/topic/37313-confused-about-jquery-and-script-inclusion-handling/ but sometimes people answer here more rapidly...
I am totally confused about Yii's handling of jquery and other javascript file inclusion.
This was working:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#Event_recuring_nature, #Event_venue, #Event_expected_attendance, #Event_age_group, #Event_state, #Event_gender, #Event_ethnicity, #Event_exclusivity, #Package_cash_product_sponsorships, #Event_vanue_signature, #Event_logo_on_step_and_repeat, #Event_inclusion_in_press, #Event_ad_space, #Event_inclusion_in_event_materials, #Package_category_exclusivity, #logo_on_signature, #Event_proposed_events_included, #Event_dependant_on_sponsorship, #Event_sponsorship_type, #Event_attendee_professions, #Event_attendee_income').yaselect();
});
</script>
<script type="text/javascript" src="/js/libs/jquery-ui-datetimepicker.js"></script>
<script type="text/javascript" src="/js/event_create.js"></script>
<script type="text/javascript" src="/js/slider.js"></script>
<script type="text/javascript" src="/js/other_social.js"></script>
<script type="text/javascript" src="/js/package.js"></script>
while this (which supposedly would be better?) does not:
<?php
Yii::app()->clientScript->registerScript('create-script', "
$(function() {
$('body').css('overflow-x','hidden');
$('#Event_recuring_nature, #Event_venue, #Event_expected_attendance, #Event_age_group, #Event_state, #Event_gender, #Event_ethnicity, #Event_exclusivity, #Package_cash_product_sponsorships, #Event_vanue_signature, #Event_logo_on_step_and_repeat, #Event_inclusion_in_press, #Event_ad_space, #Event_inclusion_in_event_materials, #Package_category_exclusivity, #logo_on_signature, #Event_proposed_events_included, #Event_dependant_on_sponsorship, #Event_sponsorship_type, #Event_attendee_professions, #Event_attendee_income').yaselect();
});
");
?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/libs/jquery-ui-datetimepicker.js'); ?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/event_create.js'); ?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/slider.js'); ?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/other_social.js'); ?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/package.js'); ?>
I had the directory
<app_dir>/js/ for all javascript and created
<app_dir>/protected/assets/js as suggested in a post on the yii forum for registerScriptFile (which supposedly handles script inclusion nicely).
I ended up having of course duplicated files and I am cleaning up.
The layout has this in the header:
<?php Yii::app()->clientScript->registerCoreScript('jquery')?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/libs/jquery-ui-1.8.20.custom.min.js')?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/libs/jquery.yaselect.min.js')?>
<?php Yii::app()->clientScript->registerScriptFile($this->assetsBase.'/js/script.js')?>
and I have this in config/main.php:
// application components
'components'=>array(
'clientScript'=>array(
'packages'=>array(
'jquery'=>array(
'baseUrl'=>Yii::app()->request->baseUrl . '/js/libs/',
'js'=>array('jquery-1.7.2.min.js')
)
)
),
(I know that baseUrl is now pointing to /js, but trying with
'baseUrl'=>Yii::app()->basePath . '/assets/js/libs'
also did NOT load jquery at all!!!
PLEASE HELP! I am new to Yii and am loosing my mind on this. Thank you.
EDIT: This is what the code generates:
<script type="text/javascript" src="/js/libs/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/assets/ab20866e/jquery.yiiactiveform.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/libs/jquery-ui-datetimepicker.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/event_create.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/slider.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/other_social.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/package.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/libs/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/libs/jquery.yaselect.min.js"></script>
<script type="text/javascript" src="/assets/2dfe5520/js/script.js"></script>
To me, the second line, /assets/ab20866e/jquery.yiiactiveform.js, looks suspicious as having a different asset id...
While I don't have your layout file in front of me, it would appear that your layout has $content before the script file registrations.
Because of this, the scripts in your view are loaded, then the scripts in the template. When this happens, the datetimepicker is being loaded, but reports errors as jquery-ui hasn't been loaded yet. Make sure that your template has the scripts loading before $content.
Alternatively, you could force scripts that are loaded in your view to be in the body, as opposed to the head by specifying a position argument, e.g.:
<?php Yii::app()->clientScript->registerScriptFile(Yii::app()->request->baseUrl . '/js/libs/jquery-ui-datetimepicker.js', CClientScript::POS_BEGIN); ?>
Another thing to consider is forcing Yii to load jQuery from the start like so:
cs()->registerCoreScript('jquery');
You can also load jQuery UI like so:
cs()->registerCoreScript('jquery.ui');
I find this solves a lot of registerScriptFile POS_BEGIN/POS_HEAD issues when loading other jQuery libraries and files (as in ernies answer)

Categories