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");
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/
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.
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.