acessing PHP variables in javascript - php

OK, so I'm not a programmer so please don't beat me up too much... I have a situation where I have some javascript (for jqgrid) that I would like some of the values to be populated from a PHP variable. What I did to get around this is to use PHP and put all the javascript code within a 'here document'. All looks to work well but I thought I'd reach out to all of you to see if there is a way to streamline my programming. The code is below for reference.
global $database;
$switchesStr = "";
$sql = "SELECT id,name FROM switch ORDER BY name asc";
$result = $database->query($sql);
while($row = mysql_fetch_array($result,MYSQL_NUM)) {
$switchesStr .= $row[0].":".$row[1].";";
}
$switchesStr = substr_replace($switchesStr,"",-1);
$vlansStr = "";
$vlansStr = "0:System Default;";
$sql = "SELECT id,vlan_description FROM vlan ORDER BY default_name asc";
$result = $database->query($sql);
while($row = mysql_fetch_array($result,MYSQL_NUM)) {
$vlansStr .= $row[0].":".$row[1].";";
}
$vlansStr = substr_replace($vlansStr,"",-1);
echo <<<DOC
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#htmlTablePorts").jqGrid({
url:'crud_ports.php',
editurl:'crud_ports.php',
datatype: 'json',
mtype: 'POST',
colNames:['id','switch','Switch IP','Switch Name','Port Name','up','Comment','restart_now','Auth Profile','VLAN','Shutdown','Last Seen'],
colModel :[{
name:'id'
,width:55
},{
name:'switch'
,index:'switch'
,editable:true
},{
name:'ip'
,index:'ip'
,width:70
},{
name:'sname'
,index:'sname'
,width:120
,edittype:'select'
,editoptions:{value:"$switchesStr"}
},{
name:'pname'
,index:'pname'
,width:65
},{
name:'up'
,index:'up'
,width:80
},{
name:'comment'
,index:'comment'
,width:125
,editable:true
},{
name:'restart_now'
,index:'restart_now'
,width:110
},{
name:'auth_profile'
,index:'auth_profile'
,width:110
,editable:true
,edittype:'select'
,editoptions:{value:"0: ;1:Static;2:Dynamic"}
},{
name:'vlan_description'
,index:'vlan_description'
,width:110
,editable:true
,edittype:'select'
,editoptions:{value:"$vlansStr"}
},{
name:'shutdown'
,index:'shutdown'
,width:110
,editable:true
,edittype:'checkbox'
,editoptions:{value:"Yes:No"}
},{
name:'last_monitored'
,index:'last_monitored'
,width:110
}],
pager: jQuery('#htmlPagerPorts'),
rowNum:20,
rowList:[10,20,30,50,100],
sortname: 'switch',
sortorder: "asc",
viewrecords: true,
height: "auto",
imgpath: 'themes/steel/images',
caption: 'Port Management',
multiselect: false,
afterInsertRow: function(rowid, aData){
switch (aData.shutdown) {
case '0': jQuery("#htmlTablePorts").setCell(rowid,'shutdown','No',{}); break;
case '1': jQuery("#htmlTablePorts").setCell(rowid,'shutdown','Yes',{}); break;
}
switch (aData.auth_profile) {
case '0': jQuery("#htmlTablePorts").setCell(rowid,'auth_profile',' ',{}); break;
case '1': jQuery("#htmlTablePorts").setCell(rowid,'auth_profile','Static',{}); break;
case '2': jQuery("#htmlTablePorts").setCell(rowid,'auth_profile','Dynamic',{}); break;
}
switch (aData.up) {
case '2': jQuery("#htmlTablePorts").setCell(rowid,'sname','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'pname','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'auth_profile','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'shutdown','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'ip','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'comment','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'vlan_description','',{background:'red',color:'white'});
jQuery("#htmlTablePorts").setCell(rowid,'last_monitored','',{background:'red',color:'white'});
break;
}
switch (aData.shutdown) {
case '2': jQuery("#htmlTablePorts").setCell(rowid,'sname','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'pname','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'auth_profile','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'shutdown','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'ip','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'comment','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'vlan_description','',{color:'red'});
jQuery("#htmlTablePorts").setCell(rowid,'last_monitored','',{color:'red'});
break;
}
}
}).navGrid('#htmlPagerPorts',
{add:false}, //options
{height:130,reloadAfterSubmit:true}, // edit options
{height:130,reloadAfterSubmit:true}, // add options
{reloadAfterSubmit:true}, // del options
{} // search options
).hideCol(["id","switch","auth_profile","up","restart_now","shutdown"]);
});/* end of on ready event */
</script>
DOC;

I believe the best way to do this would be to inside your javascript echo out what you need. For example with json_encode:
<?php $name = 'Ben'; ?>
<script type="text/javascript">
var name = <?php echo json_encode($name); ?>;
alert(name);
</script>
Or if you know the type of the value and it is not complex (like a string):
<script type="text/javascript">
var name = "<?php echo $name; ?>";
alert(name);
</script>

You could have PHP write in the information at runtime...
<script type="text/javascript" language="<strong class="highlight">javascript</strong>">
<!--
<?php
echo("firstVar = $var1;");
echo("2ndVar = $var2;");
?>
// -->
</script>

Well, if you are confortable with this way, continue. Style is always personal...
The methods by BenMills and Urda are ok too. And, when the vars in javascript are strings, don't forget to quote it too.

Related

Issue using dependsOn on jTable

I want to create a cascade dropdown on jTable using PHP on the server side. I've been following the demo provided in the API, but despite my efforts I don't seem to get it working. Using firebug I found out the AJAX request to fill the second dropdown is not being made. Anyway, here's part of the code I have. Hope you can throw some light on this.
The first dropdown is called "Region" and the second one "Trabajo", depending on the Region I want to pull from the database the workplaces that belong to it.
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'Colaboradores',
paging: true,
sorting: true,
defaultSorting: 'no_empleado ASC',
actions: {
listAction: 'usuariosActions.php?action=list',
createAction: 'PersonActionsPagedSorted.php?action=create',
updateAction: 'PersonActionsPagedSorted.php?action=update'
},
fields: {
no_empleado: {
title: 'Numero de colaborador',
key: true,
edit: false,
},
nombres: {
title: 'Nombres',
},
apellido_paterno: {
title: 'Apellido paterno',
},
apellido_materno: {
title: 'Apellido materno',
},
genero: {
title: 'Genero',
type: 'radiobutton',
options:{'0':'FEMENINO','1':'MASCULINO'},
list:false
},
fecha_nacimiento: {
title: 'Fecha de nacimiento',
type: 'date',
displayFormat: 'yy-mm-dd',
list:false
},
estado_civil: {
title: 'Estado civil',
options:{ '-1':'','1': 'CASADO', '2': 'DIVORCIADO', '3': 'SOLTERO','4':'UNION LIBRE','5':'VIUDO' },
list:false
},
dependientes: {
title: 'Número de dependientes',
options:{ '-1':'','0':'0','1': '1', '2': '2', '3': '3','4':'4','5':'5','6':'6','7':'7','8':'8','9':'9','10':'10','11':'11','12':'12','13':'13','14':'14','15':'15','16':'16','17':'17','18':'18','19':'19','20':'20' },
list:false
},
seguro_social: {
title: 'Número de seguridad social',
list:false
},
RFC: {
title: 'RFC',
list:false
},
calle: {
title: 'Calle',
list:false
},
no_ext: {
title: 'No. Ext',
list:false
},
no_int: {
title: 'No. Int',
list:false
},
colonia: {
title: 'Colonia',
list:false
},
mun_del: {
title: 'Del/Mun',
list:false
},
zip: {
title: 'Zip',
list:false
},
telefono: {
title: 'Telefono',
list:false
},
entidad_federativa: {
title: 'Entidad federativa',
list:false
},
fecha_antiguedad: {
title: 'Fecha ingreso',
type: 'date',
displayFormat: 'yy-mm-dd',
list:false
},
fecha_puesto: {
title: 'Fecha de inicio en el puesto',
type: 'date',
displayFormat: 'yy-mm-dd',
list:false
},
escolaridad: {
title: 'Escolaridad',
options:{ '-1':'','1': 'PRIMARIA', '2': 'SECUNDARIA', '3': 'PREPARATORIA','4':'UNIVERSIDAD','5':'ESPECIALIDAD','6':'POSGRADO','7':'MAESTRIA' },
list:false
},
puesto: {
title: 'Puesto',
list:false
},
contrato: {
title: 'Contrato',
options: {'-1':'','1':'Contrato por Tiempo Indeterminado','2':'Contrato por Tiempo Determinado','3':'Contrato por Obra Determinada','4':'Contrato por Tiempo Determinado'},
list:false
},
ocupacion:{
title: 'Ocupacion',
type: 'textarea',
list:false
},
region: {
title: 'Región',
options: 'usuariosActions.php?action=region',
list:false
},
trabajo: {
title: 'Centro de trabajo',
dependsOn: 'region',
options: function(data){
if(data.source == 'list'){
return 'usuariosActions.php?action=workplaces&region=0';
}
return 'usuariosActions.php?action=workplaces&region=' + data.dependedValues.region;
},
list:false
}
}
});
$('#LoadRecordsButton').click(function (e) {
e.preventDefault();
$('#PeopleTableContainer').jtable('load', {
no_empleado: $('#no_empleado').val()
});
});
//Load person list from server
$('#LoadRecordsButton').click();
});
</script>
And here's the PHP code
<?php
require_once("dbconnect.php");
if($_GET["action"] == "list")
{
//Get record count
if(isset($_POST['no_empleado']) && $_POST['no_empleado'] != ""){
$sql_result = 'SELECT
c.`no_empleado`,
c.`nombres`,
c.`apellido_paterno`,
c.`apellido_materno`,
c.`fecha_nacimiento`,
c.`fecha_antiguedad`,
c.`fecha_puesto`,
c.`estado_civil`,
c.`dependientes`,
c.`seguro_social`,
C.`escolaridad`,
C.`puesto`,
C.`RFC`,
C.`genero`,
C.`contrato`,
C.`ocupacion`,
C.`calle`,
C.`no_int`,
C.`no_ext`,
C.`colonia`,
C.`zip`,
C.`mun_del`,
C.`telefono`,
C.`entidad_federativa`,
c.`id_workplace` as trabajo,
r.`id_region` as region
FROM `colaboradores` AS c
INNER JOIN `workplaces` AS w
ON w.`id_workplace` = c.`id_workplace`
INNER JOIN `regiones` AS r
ON r.`id_region` = w.`id_region`
WHERE `no_empleado`= '.$_POST["no_empleado"].';';
$sql_count = 'SELECT COUNT(*) AS RecordCount FROM `colaboradores` WHERE `no_empleado`= '.$_POST["no_empleado"].';';
}
else{
$sql_result = 'SELECT
c.`no_empleado`,
c.`nombres`,
c.`apellido_paterno`,
c.`apellido_materno`,
c.`fecha_nacimiento`,
c.`fecha_antiguedad`,
c.`fecha_puesto`,
c.`estado_civil`,
c.`dependientes`,
c.`seguro_social`,
C.`escolaridad`,
C.`puesto`,
C.`RFC`,
C.`genero`,
C.`contrato`,
C.`ocupacion`,
C.`calle`,
C.`no_int`,
C.`no_ext`,
C.`colonia`,
C.`zip`,
C.`mun_del`,
C.`telefono`,
C.`entidad_federativa`,
r.`id_region` as region,
c.`id_workplace` as trabajo
FROM `colaboradores` AS c
INNER JOIN `workplaces` AS w
ON w.`id_workplace` = c.`id_workplace`
INNER JOIN `regiones` AS r
ON r.`id_region` = w.`id_region`
ORDER BY ' . $_GET["jtSorting"] . ' LIMIT ' . $_GET["jtStartIndex"] . ',' . $_GET["jtPageSize"] . ';';
$sql_count = 'SELECT COUNT(*) AS RecordCount FROM `colaboradores`';
}
$result = $mysqli->query($sql_count);
$row = $result->fetch_assoc();
$recordCount = $row['RecordCount'];
//Get records from database
$result = $mysqli->query($sql_result);
//Add all records to an array
$rows = array();
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
if($_GET["action"] == "region"){
$sql_count = 'SELECT `id_region` as Value ,`nombre_region` as DisplayText FROM `regiones`;';
$result = $mysqli->query($sql_count);
$rows = array();
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
//Get records from database
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Options'] = $rows;
print json_encode($jTableResult);
}
if($_GET["action"] == "workplaces"){
$region=$_GET['region'];
if ($region == "")
$result = $mysqli->query("SELECT `id_workplace` as Value, `nombre_workplace` as DisplayText FROM `workplaces` ");
else
$result = $mysqli->query("SELECT `id_workplace` as Value, `nombre_workplace` as DisplayText FROM `workplaces` WHERE `id_region` = '".$region."'");
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Options'] = $rows;
print json_encode($jTableResult);
}
I was right, dependsOn was not sending any sort of event signal and therefore the ajax call wasn't being made. I was using the min.js that came with the zip but it wasn't the newest version, 2.4.0, it was 2.2.0. it seems this functionality was not implemented yet on that version or was buggy.
Anyway, stick to version 2.4.0 and make sure to take a look into the js version if you run into trouble.

ExtJS 5.1, grid load data from database with PHP

I am doing an online course of Ext JS 5.1 and in this exercise I have a service.php file which connects to database and returns JSON Data. I try to show this data but it never gets displayed (doesn't show any error message in firebug) and I can`t find what is the problem with the code.
This is the code of the store:
var storeUsuario = Ext.create('Ext.data.Store', {
model : 'js.clase.Usuario',
proxy: {
type: 'rest',
url: 'service.php?method=getUsuarios',
reader: {
type: 'json',
}
},
autoLoad: true
});
This is the code of the grid:
Ext.create('Ext.grid.Panel', {
renderTo: Ext.getBody(),
store: storeUsuario,
width: 600,
height: 400,
title: 'Grid Usuarios',
columns: [
     {
text: 'id',
dataIndex: 'id'
},{
            text: 'nombre',
            width: 100,
            dataIndex: 'nombre'          
},{
        text: 'apellidos',
        dataIndex: 'apellidos'
},{
        text: 'email',
        dataIndex: 'email'
},{
        text: 'nacionalidad',
        dataIndex: 'nacionalidad'
},{
        text: 'rutaAvatar',
        dataIndex: 'rutaAvatar'
}
]
});
and the service.php method:
<?php
header('Content-Type: text/html; charset=utf-8');
$conexion = mysql_connect("127.0.0.1", "root", "");
mysql_select_db("usertest", $conexion);
$method = $_GET['method'];
switch($method) {
case "getUsuarios":
$query = "SELECT * FROM Usuario ORDER BY id ASC";
$result = mysql_query($query, $conexion) or die(mysql_error());
$numRows = mysql_num_rows($result);
$usuarios = array();
if ($numRows > 0) {
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$usuarios[$i] = $row;
$i++;
}
}
$usuariosJSON = json_encode($usuarios);
echo $usuariosJSON;
break;
}
?>
Your PHP code doesn't return a valid JSon.
See this fiddle works correctly: https://fiddle.sencha.com/#fiddle/q9k
According to this post you should specify the header.
And I suggest you to return a "hand formed" json like this:
$data = /** whatever you're serializing **/;
$data_length = /* the length of the result according to the request response */;
header('Cache-Control: no-cache, must-revalidate'); // just to be sure
header('Content-Type: application/json');
echo "{ \"success\": true, \"total\": $data_length, \"records\": " . json_encode($data) . " }";
The json data could need []...
echo "{ \"success\": true, \"total\": $data_length, \"records\": [ " . json_encode($data) . " ] }";

json is not retrieving data

I'm new to json and I'm having problems retrieving this information i think is a cross domain issue but I can't get it to work.
PHP FILES:
include ('tew.php');
$converter = new Encryption;
$query="SELECT tbl_pizarra.idpizarra, tbl_pizarra.titulo, tbl_pizarra.imagenchica FROM tbl_pizarra ORDER BY idpizarra DESC LIMIT 3";
$sql=mysqli_query($tew,$query);
$datosJSON = '{"pizarra": [';
while($row=mysqli_fetch_array($sql)) {
$datosJSON .= '{
"idpizarra":"'.$converter->encode($row['idpizarra']).'",
"titulo":"'.$row['titulo'].'",
"imagenChica":"'.$rutaImagenes.$row['imagenchica'].'"
},';
}
$datosJSON .= ']}';
echo $datosJSON;
include ('tew.php');
$converter = new Encryption;
$query="SELECT tbl_pizarron.idpizarron, tbl_pizarron.titulo, tbl_pizarron.imagen FROM tbl_pizarron ORDER BY idpizarron DESC LIMIT 3";
$sql=mysqli_query($tew,$query);
$datosJSON = '{"pizarron": [';
while($row=mysqli_fetch_array($sql)) {
$datosJSON .= '{
"idpizarron":"'.$converter->encode($row['idpizarron']).'",
"titPizarron":"'.utf8_encode($row['titulo']).'"
},';
}
$datosJSON .= ']}';
echo $datosJSON;
JSON DATA:
{"pizarra": [{ "idpizarra":"xET8dKAk_F-4RlUq7brYPpGV3LvuC7pRBPm722FJQpU", "titulo":"Bienvenida y Agradecimiento casa 22", "imagenChica":"http://tuedificiowebdemo.com/images/pizarras/tew_Caminadora Suspiro 21386344709.JPG" },{ "idpizarra":"Nkblz3he-ABmNFbQNInKN89Mx6NWVar-YFqeUNjyWBM", "titulo":"proyecto Plantas", "imagenChica":"http://tuedificiowebdemo.com/images/pizarras/tew_foto1380142984.jpg" },{ "idpizarra":"ZaKIOE6yAVB8Q0YBNn13b-wdI9FYGoriIvMwumY7LdU", "titulo":"COMPRA DE LA CUBIERTA DE LA ALBERCA", "imagenChica":"http://tuedificiowebdemo.com/images/pizarras/tew_CubiertaDeAlberca21378356769.jpg" },]}
{"pizarron": [{ "idpizarron":"I0jks9aMm3znH1Mg__od5sd_buDp5H8zbisrPQkQj3o", "titPizarron":"FECHAS CORTES JARDINES" },{ "idpizarron":"dfa-LPljkeJWagSDMy5bjES3y6Drqn0EOxd568mYWy8", "titPizarron":"Cuota de Mantenimiento 2014" },{ "idpizarron":"yce4YmZ2ridNmkYr5Y1dU2TmTNI7EtdA2667F_5nEyQ", "titPizarron":"PROXIMAS FECHAS DE CORTE JARDINES" },]}
HTML FILE IM USING TO GET THE INFORMAITON:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$.getJSON("http://tuedificiowebdemo.com/tewMobile/php/noticiasPizarra2.php?jsoncallback=?",function(data) {
$.each(data.pizarra, function(i,data) {
var div_data = "<a href='documentos_detalles.html?id="+data.idpizarra+"' class='notiClick'><div><img src='images/alert.png' width=100' align='absmiddle'>"+" "+data.titulo+"</div></a>";
$(div_data).appendTo("#pizarra");
});
}
);
$.getJSON("http://tuedificiowebdemo.com/tewMobile/php/noticiasPizarron2.php?jsoncallback=?",function(data) {
$.each(data.pizarron, function(i,data) {
var div_data = "<a href='documentos_detalles.html?id="+data.idpizarron+"' class='notiClick'><div>"+data.titPizarron+"</div></a>";
$(div_data).appendTo("#pizarron");
});
}
);
return false;
});
});
</script>
<div id="pizarra"></div>
<div id="pizarron"></div>
ANY SUGESTION....
thanks.
Create an array in PHP and use json_encode $json = json_encode($array) to create a string with json data.
You are outputting 2 independent json strings which will not be read correctly. Both getJSON will get the same double invalid json string.
Invalid like your example:
{/*data here*/}
{/*data here*/}
Valid:
[
{/*data here*/},
{/*data here*/}
]
If it is a cross domain issue...include this header in the php page
header('Access-Control-Allow-Origin: *');

Issues Rendering Highcharts - Populating through PHP/MySQL

I'm hoping someone can help me here, I've been looking at highcharts as a way of graphing my dynamic data from my sql db....What I've come up with so far is below, it's strange, it seems correct, the data is correct, however, I can't get my chart to render, now I've tried viewing the chart through both Chrome and IE but with no results, can anyone see where I might've gone wrong, or where there is an error...my data is passing into the JS arrays, so there's an issue with the rendering end... Any help would be much appreciated. I have closed off my html tag, but for some reason it isn't displaying in this post...if anyone has any suggestions I would be happy to hear them!
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src='highcharts.js' type='text/javascript'> </script>
<script src='exporting.js' type='text/javascript'> </script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"type="text/javascript"></script>
</head>
<body>
<?php
include "connect_db.php";
$SQL1 = "SELECT review.reviewForum AS reviewForum,
COUNT(CASE WHEN mom.result = 'Approved' THEN 'yes' ELSE NULL END) AS Approved,
COUNT(CASE WHEN mom.result = 'NOT Approved' THEN 'yes' ELSE NULL END) AS Not_Approved,
COUNT(CASE WHEN mom.result = 'Cancelled' THEN 'yes' ELSE NULL END) AS Cancelled
FROM review INNER JOIN mom ON mom.reviewId = review.reviewId GROUP BY review.reviewForum";
$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
$data1[] = $row['reviewForum'];
}
$result2 = mysql_query($SQL1);
$data2 = array();
while ($row = mysql_fetch_array($result2)) {
$data2[] = $row['Approved'];
}
$result3 = mysql_query($SQL1);
$data3 = array();
while ($row = mysql_fetch_array($result3)) {
$data3[] = $row['Not_Approved'];
}
$result4= mysql_query($SQL1);
$data4 = array();
while ($row = mysql_fetch_array($result4)) {
$data4[] = $row['Cancelled'];
}
?>
<script type="text/javascript">
$(document).ready(function() {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'TC REVIEW RESULT STATS'
},
xAxis: {
categories: [<?php echo join($data1, ',') ?>],
},
yAxis: {
min:0
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 50,
y: 35,
floating: true,
shadow: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [ {
name: 'Approved',
data: [<?php echo join($data2, ',') ?>],
pointStart: 0
//pointInterval
},
{
name: 'Unapproved',
data: [<?php echo join($data3, ',') ?>],
pointStart: 0
//pointInterval
},
{
name: 'Cancelled',
data: [<?php echo join($data4, ',') ?>],
pointStart: 0
//pointInterval
},
]
});
});
</script>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
I suggest you start trying to render one without generated code. If that doesnt work, you might want to share that on jsfiddle and we can have a look :-). If it does work, you should compare it with the generated code.
{
name: 'Cancelled',
data: [<?php echo join($data4, ',') ?>],
pointStart: 0
//pointInterval
}, // This comma is a syntax error
]
Do you see that comma? You don't put commas before '}', because you have that in multiple places.
Take out the comma after the categories statement under xAxis.
 xAxis:  {
categories: [<?php echo join($data1, ',') ?>],
},
Should be
xAxis:  {
categories: [<?php echo join($data1, ',') ?>]
},
I think thre real reason is here:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"type="text/javascript"></script>
<script src='highcharts.js' type='text/javascript'> </script>
<script src='exporting.js' type='text/javascript'> </script>
First load jQuery, then Highcharts.

PHP inside Jquery

I am developing a wordpress theme and now I am working on the theme options page. I added an option with "select" method to give the user the option to change the slider's fx. Now... this is the output of a text input that sets the fx duration <?php echo get_option('wis_fx_speed'); ?> and works fine! My problem is that <?php echo $fxSample ?> don't work.
Tried everything I knew and imagined (syntax, order, put the switch inside the jquery script etc) , searched the web but found nothing... Could you help me? Thanks in advance!
<?php
switch (get_option('wis_fx_slider')) {
case "opacity":
$fxSample = "opacity : 'toggle',";
break;
case "width":
$fxSample = "width : 'toggle',";
break;
case "opawidth":
$fxSample = "opacity : 'toggle', width : 'toggle',";
break;
case "blink":
$fxSample = "opacity : 'show',";
break;
}
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$("#photo-rotator").tabs({fx:{<?php echo $fxSample ?>
duration: <?php echo get_option('wis_fx_speed'); ?> }}).tabs("rotate", 2000);
});
</script>
OUTPUT:
<
script type="text/javascript">
jQuery(document).ready(function($){
$("#photo-rotator").tabs({fx:{ duration: 3000 }}).tabs("rotate", 2000);
});
</script>
EDIT
Works if I make it with radio.
When I need to pass some data to JavaScript, I find it helpful to build a PHP array first, then use json_encode to convert it to JavaScript. This avoids a lot of potential issues:
<?php
$tab_options = array(
'duration' => get_option('wis_fx_speed'),
'fx' => array()
);
switch (get_option('wis_fx_slider')) {
case 'opacity':
$tab_options['fx']['opacity'] = 'toggle';
break;
case 'width':
$tab_options['fx']['width'] = 'toggle';
break;
case 'opawidth':
$tab_options['fx']['opacity'] = 'toggle';
$tab_options['fx']['width'] = 'toggle';
break;
case 'blink':
$tab_options['fx']['opacity'] = 'show';
break;
}
?>
<script type="text/javascript">
var tabOptions = <?php echo json_encode($tab_options); ?>;
jQuery(document).ready(function($) {
$('#photo-rotator').tabs(tabOptions).tabs('rotate', 2000);
});
</script>
Benefits:
Much cleaner code (easier to read).
You don't have to worry about getting the commas, quotes, and other syntax right for all the possible cases. For example, as other people have mentioned, you don't have a default case. This approach will at least generate valid JavaScript if an option value is invalid.
To safely output any PHP value into a JavaScript value, use json_encode.
...{fx:<?php echo json_encode($fxSample); ?>, duration: <?php echo json_encode(get_option("wis_fx_speed")); ?>}...
Note also that you are missing a , and have an extra } in your code. Always look at the generated result to look for syntax errors.
You need a semicolon after each php line
...
$("#photo-rotator").tabs({fx:{<?php echo $fxSample; ?>
...
What about a default case value?
Try to debug doing a
var_dump(get_option('wis_fx_slider'));
var_dump($fxSample);
Maybe is it a scope problem? Try defining
$fxSample = "";
at the beggining, before the switch
Is get_option('wis_fx_slider') returning one of the options in the switch case?
You haven't sepcified a "default" so $fxSample will go undefined.
<?php
switch (get_option('wis_fx_slider')) {
case "opacity":
$fxSample = "opacity : 'toggle',";
break;
case "width":
$fxSample = "width : 'toggle',";
break;
case "opawidth":
$fxSample = "opacity : 'toggle', width : 'toggle',";
break;
default: // blink or anything else
$fxSample = "opacity : 'show',";
}
?>
Is your duration a string or number? If it's a string you need quotes like
duration: '<?php echo get_option('wis_fx_speed'); ?>' }}).tabs("rotate", 2000);
What happens when you view source? Is the PHP laying out the dynamically generated javascript correctly? Can you post the output?
Also, formatting
<?php
switch (get_option('wis_fx_slider')) {
case "opacity":
$fxSample = "opacity : 'toggle',";
break;
case "width":
$fxSample = "width : 'toggle',";
break;
case "opawidth":
$fxSample = "opacity : 'toggle', width : 'toggle',";
break;
case "blink":
$fxSample = "opacity : 'show',";
break;
}
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$("#photo-rotator").tabs({
fx: {
<?php echo $fxSample ?>
duration: <?php echo get_option('wis_fx_speed'); ?>
}
}).tabs("rotate", 2000);
});
</script>

Categories