PHP inside Jquery - php

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>

Related

How to use cookie in ajax file

I have code that uses ajax in order to pull and print data from DB.
ajax run PHP file that does that. This file read data from the cookie and use it, but because I'm using ajax and run file "away" from the website I don't think it can call to cookies...
how can I read cookie inside the ajax file?
AJAX FILE
switch ($_COOKIE['user_lang'])
{
case "ES":
$langDir = SPANISH
break;
case "EN":
$langDir = ENGLISH
break;
}
You can try it .
function readCookie(cname) {
var name = cname+"=";
var cookies = decodeURIComponent(document.cookie).split(';');
var cval = [];
for(var i=0; i < cookies.length; i++) {
if (cookies[i].trim().indexOf(name) == 0) {
cval = cookies[i].trim().split("=");
}
}
return (cval.length > 0) ? cval[1] : "";
}
switch (readCookie(['user_lang']))
{
case "ES":
$langDir = SPANISH
break;
case "EN":
$langDir = ENGLISH
break;
}

php and js-ajax acting funny (explanation inside)

I am having trouble with this ajax. The return is funny. The switch seems to always evaluate as though #about is true. And include the rest of the switch statement in the #page variable. For instance my PHP code prints this (as well as the #about that it is supposed to) the code at the bottom should clarify what I mean.
To recap it echoes everything past the first $page ='
on my page I see this below what it is supposed to echo
';
break;
case '#register' :
$page = 'k';
break;
case '#contact' :
$page = 'a';
break;
case '#a' :
$page = ' b';
break;
case '#b' :
$page = '<p> c</p>';
break;
default;
echo "def";
}
echo $page;
Not to mention it wont even work for #contact, or #a, #b...etc. I am not sure why. Regardless of the url passed it appears as though #about is called with what it returns (even though it returns about and more).
I would really appreciate some help! Thank you
Here is my code:
the js =]
$(document).ready(function () {
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Seearch for link with REL set to ajax
$('a[rel=ajax]').click(function () {
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content
$('#content').hide();
console.log(this.href);
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
console.log("k");
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('slow');
}
});
}
the php =]
switch($_GET['page']) {
case '#about' :
$page = ' HTML stack overflow formats it, anyways';
break;
case '#register' :
$page = 'k';
break;
case '#contact' :
$page = 'a';
break;
case '#a' :
$page = ' b';
break;
case '#b' :
$page = '<p> c</p>';
break;
default;
echo "def";
}
echo $page;
thank you again!
Also in the php file, try putting this on top of the script:
header("Content-Type: text/html");

Insert Large html markups inside jquery variable error

im builng a web game and im stuck tryning to append the html-markup for a jquery-ui dailog box.I am currently getting the Uncaught SyntaxError: Unexpected number error in chrome. I have tryed the appendTo method for large blocks of data before,but i was wondering is the a limit on the amount of html-elements you can place inside a jquery varable? because i find myself having to work around this every day ant tips?
note: please read the question carefully before you answer . Is there a way to store large blocks of (html code/ text) static or dynamic, inside a jquery variable?
jquery code :
<script>
var vari = "<?= $UserSpacesAvA ; ?>";
var btn = "<button id='d_pis_btn'>Place in shop</button>";
$(vari).appendTo(document).dialog({
closeOnEscape: false,
modal : true,
draggable : false,
height : 400,
width : 500,
resizable : false,
title : 'Give Your new <?=ucfirst($morph); ?> A Home!',
buttons : [
{
text: 'Done!',
click: function() {
$(this).dialog("destroy").remove();
}
},
],
open: function(event, ui) { $(".ui-dialog-titlebar-close").remove(); },
});
$('.popi select').chosen({});
$(btn).appendTo('.set').on("click",function(){
});
</script>
Php code :
function UserPlaces($userData,$dataExpected,$type){
$dat = "<div class='popi' id='pop'><fieldset class='set'><legend>Location:</legend>";
$x = explode(",",$type);
foreach($x as $s){
switch($s){
case 'rooms':
// bring out rooms
$dat .= "<label>Room:</label><select id='d_room_select'>";
if(count($userData["locations"]['r']) < 1){
$dat .= "Insufficient Space";
}else{
$int = 1;
foreach($userData["locations"]['r'] as $x){
$dat .= "<option value=\"$x\">Room Number $int</option>";
$int++;
}
}
$dat .= "</select><br><br>";
break;
case 'shops':
// bring out shops
$dat .= "<h4>Is this snake for sale ?</h4><br><label>Shop:</label><select id='d_shop_select'>";
if(count($userData["locations"]['r']) < 1){
$data .= "No Shops";
}else{
$int = 1;
foreach($userData["locations"]['s'] as $x){
$dat .= "<option value=\"$x\">Shop Number $int</option>";
$int++;
}
}
$dat .= "</select><br><br><label>Price:</label>
<input id='d_shop_price_snake' name='d_shop_price_snake'><br><br>
";
break;
case 'shows':
// bring out shows
break;
}
}
$dat .= "</fieldset></div>";
return $dat;
}
This doesn't answer your question on limits, but try using jQuery Templates:
http://api.jquery.com/category/plugins/templates/

element in form is empty in IE

The following code is working in FF but not in IE. There is no value of document.myform["parameters"].value in IE.
The code:
function form_elements()
{
if(document.myform.elements["parameters"].value == '')
{
myform_values = ......
}
}
<form method="post" name="myform">
<div id="parameters_info">
<select id="parameters" name="parameters" onfocus="e =form_elements();" >
<?php
foreach($params_name as $name)
{
if($name == $param_posted)
{
echo "<option selected>$name</option>";
}
else
{
echo "<option>$name</option>";
}
}
?>
</select>
</div>
</form>
I tried also document.myform["parameters"].value but the value is empty.
My options are like:
<option>1234</option>
<option>234a</option>
And i want that the value of the option will be in the function.
10x,
Ronny
You need to give a value to each option. Also, you cannot get the selected option using the value of the select tag. You need to use:
var selectedOption = document.myform.parameters.options[document.myform.parameters.options.selectedIndex].value;
<option>1234</option>
1234 - is a text of an option.
<option value="1234">1234</option>
Now 1234 - is a text and value.
That should be:
document.forms["myform"].elements["parameters"].options[document.forms["myform"].elements["parameters"].selectedIndex].text
...or you can use a function like this, which returns an array of values from any field type:
function getFieldValueArray(fld, frm) {
// fld may be a field object or a field name
// frm may be an index or a name, defaults to document.forms[0] when needed and not supplied
//function returns an array of values
var form = frm ? document.forms[frm] : document.forms[0];
var field = (typeof(fld) == "object") ? fld : form.elements[fld];
var valueArray = new Array();
var multinode = (field.length>1) ? true : false;
var type = field.type;
if (!type) {
type = field[0].type;
}
switch(type) {
case "radio": //fall-through intentional
case "checkbox":
if (multinode) {
for (i=0; i<field.length; i++) {
if (field[i].checked) {
valueArray.push(field[i].value);
}
}
}
else {
if (field.checked) {
valueArray.push(field.value);
}
}
break;
case "select-one": //fall-through intentional
case "select-multiple":
var options = field.options;
for (i=0; i<options.length; i++) {
if (options[i].selected) {
valueArray.push(options[i].value ? options[i].value : options[i].text);
}
}
break;
case "text": //fall-through intentional
case "file":
valueArray.push(field.value);
break;
case "hidden":
valueArray = field.value.split(";");
break;
case "textarea":
valueArray = field.value.split("\n");
default:
alert("Field not found -- atGetField(" + fld.toString() + ")");
}
return valueArray;
}
The function comes in rather handy when you can't be certain what type the field may be (for instance, if the field is an editable type under some circumstances and hidden under others), but once written it's an easy fallback, particularly for selects, radios and checkboxes.

acessing PHP variables in javascript

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.

Categories