I have functions stored in SQL table that I need to use inside JS. The problem is, that I also need to use PHP variables in these functions.
The following:
<?php
$container='11';
$title='Header';
$function_text =
<<<EOT
$(function() {
$('#container$container').parent('div').find('h3').html('$title');
});
EOT;
echo $function_text;
?>
returns correctly:
$(function() {
$('#container11').parent('div').find('h3').html('Header');
});
but this one:
<?php
$ID=1;
$container='11';
$title='Header';
$article = $cls -> Query(sprintf('SELECT * from graphs WHERE ID="%s"', $ID));
$function_text = $article[0]['function'];
echo $function_text;
?>
prints exactly the contents of SQL field, without recognising variables:
$(function() {
$('#container$container').parent('div').find('h3').html('$title');
});
How could I get the variables to be injected to echoed text?
Change the data that is stored in your database, so that it uses format placeholders instead of references to variables:
$(function() {
$('#container%s').parent('div').find('h3').html('%s');
});
Use sprintf():
$function_text = sprintf($article[0]['function'], $container, $title);
Related
I have a small problem. I would like to insert SQL table information into a predefined Javascript code. I know how it works with PHP but I have never done it with Javascript and so I need your help.
I am a total beginner.
SQL Table:
Date_begin | Date_end | Text
-----------|----------|-----
03/2002 |07/2020 |test1
05/2002 |08/2020 |test2
... |... |...
PHP SQL Query (PDO):
<?php
$Date_begin = $connection->query("SELECT Date_begin FROM `test_table`");
$Date_end = $connection->query("SELECT Date_end FROM `test_table`");
$Text = $connection->query("SELECT Text FROM `test_table`");
?>
Predefined static JavaScript Code where the Information must be put in:
<script>
['03/2002', '07/2020', 'test1'],
['05/2002', '08/2020', 'test2'],
....
</script>
My attempt to solve it to make it dynamic:
<script>
var Date_begin = <?php echo $Date_begin ?>;
var Date_end = <?php echo $Date_end ?>;
var Text = <?php echo $Text ?>;
begin loop
['XXX', 'XXX', 'XXX'], // SQL Row 1
['XXX', 'XXX', 'XXX'], // SQL Row 2
['XXX', 'XXX', 'XXX'], // SQL Row 3
... // SQL Row n
end loop
</script>
Now I need to generate the above lines dynamic and fill it with the SQL Information. I think I need a loop but I don't know the syntax. I also don't know if I passed the variables from PHP to JavaScript correctly.
Thanks for any help and answer.
At the moment, you are not fetching any data, just executing the queries. Note that you only need one query since you are fetching all the data from the same table with the same conditions (in this case, none). You can get a JavaScript array of data directly from your PHP code by using json_encode.
Your code should look something like this:
<?php
$result = $connection->query("SELECT Date_begin, Date_end, Text FROM `test_table`");
if (!$result) {
// deal with error
}
$data = $result->fetchALL(PDO::FETCH_NUM);
?>
<script>
var data = <?php echo json_encode($data, JSON_UNESCAPED_SLASHES); ?>
// process data array
</script>
I need to display the values of an SQL table in a D3 map for each US state. Below is code excerpts from my file.php:
Here is the SQL query:
$sql = "SELECT COUNT(State) FROM `mytable`";
$sql_result= mysqli_query($cnx,$sql) or die('Could not execute' . mysqli_error()) ;
Here is how I pass the result into an array
<? while($myvar=mysqli_fetch_array($sql_result)) { **need to add both php and javascript below..** }
<?php $js_array = json_encode($myvar['0']);?>
Here is where I need to pass the data:
.forEach(function(d){
var kpi01=<?php echo "var nbcustomers = ". $js_array . ";\n";?>, // No of customers in that state
kpi02= .....
sampleData[d]={kpi01, kpi02};
});
Can anyone help me with suggestions to properly insert the JavaScript code after the while loop within the .forEach?
Don't mess around with trying to generate a bunch of variables with numbers in their names.
Just construct the data structure you need (an array of your SQL query results) in PHP, then use json_encode to convert it to JavaScript.
<?php
$my_array = [];
while($myvar=mysqli_fetch_array($sql_result)) {
$my_array[] = $myvar;
}
$js_array = json_encode($my_array);
?>
<script>
var javascript_array = <?php echo $js_array; ?>;
</script>
edit: I'm now wondering how I can access post ID from within plugin (outside of loop). If I try to get the post id, it returns 0.
How does one access a specific page's PHP variables within a plugin JS file?
I originally had the JS in the page template file but have moved it to a plugin. Now I am unsure how to access that page's PHP variables. Maybe move the PHP logic to a plugin function?
content-course.php (JS)
<?php
$user_id = get_current_user_id();
$course_id = $post->ID;
$vimeo_progress = 0;
$vimeo_seconds = 0;
if ( is_user_logged_in() ) {
// Run WP query to retrieve user progress
$row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d AND course_id = %d;", $user_id, $course_id) );
if ($row) {
$vimeo_seconds = $row->seconds_played;
$vimeo_progress = $row->progress_percent;
}
}
?>
<script>
jQuery(document).ready(function($) {
var progress = <?php echo $vimeo_progress; ?>;
var seconds = <?php echo $vimeo_seconds; ?>;
var userProgress = <?php echo $vimeo_seconds; ?>; //example user data retrieved
var lastUpdateProgress = <?php echo $vimeo_progress; ?>;
var videoUrl;
var courseID = <?php echo $course_id; ?>;
</script>
How would the JS script be able to access the PHP variables if moved to the plugin? Do I need to move the PHP above the script to a plugin function.. because then I am not sure how it would pass the data to the JS.
Wordpress have a classified function for the job
wp_localize_script()
Take a look. It's very easy to do.
http://codex.wordpress.org/Function_Reference/wp_localize_script
If I pass an hard coded numeric value from php to javascript, all works perfectly. But if i pass the numeric value from a variable, i get an error:
javascript file (gallery.js)
function goto_anchor(id)
{
var anchor = $("#anchor_" + id);
$('html,body').animate({
scrollTop: anchor.offset().top - 20
}, 1200);
}
php file
....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="js/gallery.js" type="text/javascript"></script><?php
$get_cat = 4;
if (isset($get_cat)) { ?>
<script>
$(document).ready(function() {
goto_anchor(4); // this will work PERFECTLY!!!
goto_anchor(<?php echo $get_cat; ?>); // this will NOT work !!!
});
</script><?php
} ?>
I need to pass the $get_cat variable in my php, not the harcoded numeric value. How ??
Thanks
I have such kind of problems before, can not fill
javascriptfunction(<?php echo $phpvirable ?>)
inside javascript function that causes error; Instead , according to your code, can echo it to javascript virable first before using it;
echo '<script> var get_cat = '.$get_cat.'</script>';
into your php
<?php $get_cat = 4; ?>
surely, Your php $get_cat can be captured from such as $_REQUEST['cat'] dynamic value from form submit event towards this page. then u convert it to javascript virable to use in function.
<?php
if(isset($getcat)):
echo '<script> var get_cat = '.$getcat.'</script>';
endif;
?>
// javascript function read predefined javascript virable that confirm work.
// u also avoid using mixed php and javascript statements which looks messy
<script>
$(document).ready(function() {
goto_anchor(get_cat); // this will work then.
});
</script>
I have a php page to creates a multi-dimentional array called $results.
I would like to:
catch submit of a form button
override default behavior of the submit using jQuery
copy and process $results on separate php using $.post
I have this which is not currently working and am not sure why?:
<form id='download_to_excel' method="post">
<input type="image" name="submit" value="submit" id='xls_download_button' src='images/common/buttons/download.png'>
</form>
<?php
$json_results = json_encode($results);
?>
<script type='text/javascript'>
$(document).ready(function(){
alert($json_results);
$("#xls_download_button").click(function(e){
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
});
</script>
When selecting the xls_download_button, the alert() never fires nor does any data get passed to export_data_to_excel.php
The export_data_to_excel.php file has the following:
<?php
$results = json_decode($_POST['json_data']);
#include the export-xls.class.php file
require_once('export-xls.class.php');
$date = date('Y-m-d');
$filename = "contacts_search_$date.xls"; // The file name you want any resulting file to be called.
#create an instance of the class
$xls = new ExportXLS($filename, $results);
#lets set some headers for top of the spreadsheet
$header = "Searched Contact Results"; // single first col text
$xls->addHeader($header);
#add blank line
$header = null;
$xls->addHeader($header);
$header = null;
$row = null;
foreach($results as $outer){
// header row
foreach($outer as $key => $value){
$header[] = $key;
}
// Data Rows
foreach($outer as $key => $value){
$row[] = $value;
}
$xls->addRow($header);//add header to xls body
$header = null;
$xls->addRow($row); //add data to xls body
$row = null;
}
# You can return the xls as a variable to use with;
# $sheet = $xls->returnSheet();
#
# OR
#
# You can send the sheet directly to the browser as a file
#
$xls->sendFile();
?>
I do know that the $json_results does display proper JSON encoded values when echoed. But from there are not sure why the rest of the javascript does not run; the alerts never fire nor does the JSON data get passed?
Can you see why this isn't working?
Your PHP-supplied json is not stored as a javascript variable in your js.
$(document).ready(function(){
var json_results = <?php echo $json_results; ?>;
...
This code shouldn't run:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
It is invalid (the ; doesn't belong there). Try this code:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results});
}
Right now you are just setting a php variable called $results you need to transfear it to you javascript.
<script type="text/javascript">
// set javascript variable from php
var $results = "<?php echo json_decode($json_data); ?>";
</script>
For sure you have an error in your javascript code (you were not closing the parenthesis after $.post), should be:
$(document).ready(function() {
alert($json_results);
$("#xls_download_button").click(function(e) {
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls() {
$.post('./libs/common/export_data_to_excel.php', {
json_data: json_results
});
}
});
Then you should assign your JSON to a javascript variable inside document.ready
$(document).ready(function() {
var json_results = <?php echo($json_results);?>;
You can't pass a PHP variable to the JavaScript like that: there live in totally different worlds. Use Ajax to get the JSON data from JS.