How to insert php code inside javascript - php

Kindly pls have a look at the code below ! Its working perfectly except the php code is not giving any output. When i insert the output of the php , the script work perfectly.
<script type="text/javascript">
function LoadVideoBar() {
var videoBar;
var barContainer = document.getElementById("videoBar");
var options = {
largeResultSet : false,
horizontal : true,
autoExecuteList : {
cycleTime : GSvideoBar.CYCLE_TIME_SHORT,
cycleMode : GSvideoBar.CYCLE_MODE_LINEAR,
executeList : [ "<?php $cat = get_the_category(); $cat = $cat[0]; echo $cat->cat_name; echo "-"; echo wp_title(); ?> "]
}
}
new GSvideoBar(
document.getElementById("videoBar"),
document.getElementById("videoPlayer"),
options
);
}
GSearch.setOnLoadCallback(LoadVideoBar);
When i replace the php code
<?php $cat = get_the_category(); $cat = $cat[0]; echo $cat->cat_name; echo "-"; echo wp_title(); ?>
with some text like : categoryname-title name
The script works perfectly.
Can somebody help me out with this small issue ...
Many Thanks in Advance!

If you ever need to pass data between the two. Put the PHP value into a hidden field. then read it like you did with bar container
Save the value from PHP:
<?php $cat = get_the_category(); $cat = $cat[0]; ?>
<input id="executeListValue" type="hidden"
value="<?php echo $cat->cat_name."-".wp_title();?>" >
read it in js:
var executeListValue = document.getElementById("executeListValue").value;
//...
autoExecuteList : {
cycleTime : GSvideoBar.CYCLE_TIME_SHORT,
cycleMode : GSvideoBar.CYCLE_MODE_LINEAR,
executeList : executeListValue
}

if the php code is replaced and the script works fine means php is having some error while executing. can you please try to see the source code of the html page. this may be happening because of some php error happening and those error message string could be making some syntax error to javascript.
try to put the php code outside the javascript tag and see the output generated from it.
<?php
$cat = get_the_category();
$cat = $cat[0];
$output= $cat->cat_name."-".wp_title();
?>
and then try to print the output in the javascript.
executeList : [ "<?php print $output; ?>"]
}
by this way you can see if any php error is encountered.

Replace "-" with '-' in Javascript code in line:
[ "<?php $cat = get_the_category(); $cat = $cat[0]; echo $cat->cat_name; echo "-"; echo wp_title(); ?> "]

Related

Dynamic PHP variable into a Javascript function

I am trying to pass $post; a variable created in a mysql query, to javascript function showDiv.
Currently this doesnt work.
$post = $row['id'];
?>
<script type="text/javascript">
function showDiv() {
var note = "<?php echo $post ?>";
document.getElementById("<?php echo $post; ?>").style.display = "inline";
}
</script>
<?php
$addnote = '<input type="button" value="addnote" onclick="showDiv()"><div id="'.$postid.'" style="display:none;" class="'.$postid.'"> WELCOME</div>';
But if I change $post to have a html value e.g
$post = '11';
then this code works.
I am novice in javascript so please be gentle,
Any help is greatly appreciated.
Thank you.
If you are in a loop, I think JS doesn't like redeclare your function "showDiv()". Try this :
$post = $row['id'];
$addnote = '<input type="button" value="addnote" onclick="showDiv('.$post.')"><div id="'.$post.'" style="display:none;" class="'.$post.'"> WELCOME</div>';
And the javascript NOT in the loop :
<script type="text/javascript">
function showDiv(note) {
document.getElementById(note).style.display = "inline";
}
</script>
check your $row['id'] if it's returning something.
<?php echo $row['id']; ?>
or check your source code.
your code might look something like
<script type="text/javascript">
function showDiv() {
var note = "";
document.getElementById("").style.display = "inline";
}
</script>
Assuming that: $post = $row['id'] has a value. You want var note to have a value of a string. JS wraps strings in single or double quotes. so wrap <?php echo $post ?> in a string like this:
var note = "'"+<?php echo $post ?>"'";
This will prepend and append the quotes around the $post value so that JS can recognize it as a string.

Passing a variable from jquery to php

I am trying to pass a variable from jquery to php
My jquery code:
<script>
$(window).load(function(){
$.get("as.php",url="http://www.wired.co.uk/news/archive/2013-01/10/chinese-desert-mystery", function(data,status){
$('#lax').html(data);
});
});
</script>
<div id="lax" >
</div>
And my "as.php" file is as follows:
<?php
include('phpQuery.php');
$file = mysqli_real_escape_string($dbc, strip_tags(trim($_GET['url'])));
phpQuery::newDocumentFileHTML($file);
$titleElement = pq('title');
$title = $titleElement->html();
echo '<a href="" >' . htmlentities( $title) . '</a><br/>';
foreach(pq('meta') as $li)
if ((pq($li)->attr('name')=='description')||(pq($li)->attr('name')=='Description')){
echo '<p>'.pq($li)->attr('content').'</p>';
}
?>
I am tryin to pass 'url' variable from jquery code to my "as.php" file , but not able to do so. Where must be I going wrong?
You need to create an object
url="http://www.wired.co.uk/news/archive/2013-01/10/chinese-desert-mystery"
Should be:
{url :"http://www.wired.co.uk/news/archive/2013-01/10/chinese-desert-mystery"}
jQuery docs
I don't see you opening a database connection, so with the code you posted $dbc will be NULL.
That causes mysqli_real_escape_string to return NULL as well.
As you are not doing any database operations, you should get rid of mysqli_real_escape_string completely.
in you jquery:
<script>
$(window).load(function(){
$.get("as.php",
{url:"http://www.wired.co.uk/news/archive/2013-01/10/chinese-desert-mystery"}, function(data){
$('#lax').html(data);
});
});
</script>
in your php try using $_REQUEST
<?php
include('phpQuery.php');
$file = mysqli_real_escape_string($dbc, strip_tags(trim($_REQUEST['url'])));
phpQuery::newDocumentFileHTML($file);
$titleElement = pq('title');
$title = $titleElement->html();
echo '<a href="" >' . htmlentities( $title) . '</a><br/>';
foreach(pq('meta') as $li)
if ((pq($li)->attr('name')=='description')||(pq($li)->attr('name')=='Description')){
echo '<p>'.pq($li)->attr('content').'</p>';
}
?>

Problems with "onload" and XHTML Validation

My name is Manuel, I am a web design student and am starting to take my first steps with web design. Recently I tried to validate
this site:
http://accesosnormalizados.com
I used the W3C validator, at first I found about 30 errors, and can correct them all except one that says: 'there is no attribute
"onload"'.
Apparently not support XHTML onload tag, and I use a Joomla extension called Vertical Menu using onload. This is a free extension and works well but I have found it has some bugs, especially when validating the website.
This is the PHP code for extension:
get( 'menutype', 'mainmenu' );
$qry = "SELECT id, name,parent, link,type,browserNav FROM #__menu WHERE menutype = '".$menutype."' AND published = 1 ORDER BY ordering";
$database->setQuery($qry);
$rows = $database->loadObjectList();
if(isset($GLOBALS['vertical_menu'])) $GLOBALS['vertical_menu']++;
else $GLOBALS['vertical_menu'] = 0;
function getMenuChildList($rows, $parentId) {
$childRows = array();
foreach ($rows as $row) {
if ($row->parent == $parentId) {
$childRows[] = $row;
}
}
return $childRows;
}
function drawVerticalMenu($rows, $showsubcats, $parentId = 0) {
$categories = $showsubcats || !$parentId ? getMenuChildList($rows, $parentId) : array();
if ($parentId) {
if (!count($categories)) {
echo '';
return;
} else echo '';
echo '';
} else echo '';
echo '';
foreach ($categories as $category) {
$link = $category->link. (preg_match("/^http:\/\/|^https:\/\//",$category->link)? "" : '&Itemid='.$category->id);
$blank = $category->browserNav? ' target="_blank" ' : ' ';
echo 'id.'" class="menu">'.$category->name.' ';
drawVerticalMenu($rows, $showsubcats, $category->id);
}
echo '';
if ($parentId && count($categories)) echo '';
}
$document = &JFactory::getDocument();
$document->addScript('https://ajax.googleapis.com/ajax/libs/dojo/1.5.0/dojo/dojo.xd.js');
$document->addScript('modules/mod_vertical_menu/script/menu.js');
$document->addStyleSheet('modules/mod_vertical_menu/style/menu.css');
$document->addCustomTag('
div#MenuContainer'.$GLOBALS['vertical_menu'].' table#VerticalMenu'.$GLOBALS['vertical_menu'].' {
width: '.$params->get('categorymenu_width', 150).'px;
opacity: '.$params->get('categorymenu_out', 0.8).';
FILTER: progid:DXImageTransform.Microsoft.Alpha(Opacity='.($params->get('categorymenu_out', 0.8)*100).');
}
');
echo '';
drawVerticalMenu($rows, $params->get('show_subcats', 1));
echo 'get('categorymenu_out', 0.8).',over : '.$params->get('categorymenu_over', 1).',duration : '.$params->get('categorymenu_fade', 300).',id : '.$GLOBALS['vertical_menu'].',width : '.$params->get('categorymenu_width', 150).'});" alt=""/>';
echo '';
?>
The problem is at the end:
echo '';
drawVerticalMenu($rows, $params->get('show_subcats', 1));
echo 'get('categorymenu_out', 0.8).',over : '.$params->get('categorymenu_over', 1).',duration : '.$params->get('categorymenu_fade', 300).',id : '.$GLOBALS['vertical_menu'].',width : '.$params->get('categorymenu_width', 150).'});" alt=""/>';
echo '';
?>
I think the extension uses the onload event to display the sub-menus when the user moves the mouse pointer over it.
What I want is to replace the onload with other event handler or some other label that is supported by XHTML and that is as similar to onload.
I would appreciate your help ...
You can remove the onload attributes and then add some simple javaScript to your page to run some functions when the page finishes loading.
It would look something like this:
<script>
window.onload=function(){
new WW.VerticalMenu({out : 1,over : 1,duration : 300,id : 0,width : 180}); // example of one of the functions being run
};
</script>
Good luck with your studies
It appears the source comes out like this right
<img src="/modules/mod_vertical_menu/images/center.gif" style="display:none" onload="new WW.VerticalMenu({out : 1,over : 1,duration : 300,id : 0,width : 180});" alt=""/>
As that looks like imho an unsavoury method of instantiating the menu I would try and loose that attribute completely by removing the offending php echo section and instead add javascript to load
as this is using dojo maybe this will help -- sorry I do not use dojo
http://mail.dojotoolkit.org/pipermail/dojo-interest/2012-May/066106.html
so php wise this would be
echo '<img src="modules/mod_vertical_menu/images/center.gif" style="display:none" alt=""/>'; echo '</div>';
echo "<script>" ."javascript or dojo script here ".</script>"
I would even suggest removing the image and using the window onload advocated below if you can

SlickGrid error: Slick.Editors.Text is not a constructor

I'm trying to implement SlickGrid on the edit page of a CakePHP project, and when the page loads I get this error in the javascript console:
slick.grid.js:2173TypeError:'Slick.Editors.Text is not a constructor' (evaluating 'new (editor || getEditor(activeRow, activeCell))')
The data renders correctly in the grid on my page, but when I click on a cell to edit it, it just turns white and I can't type anything. If I click on another cell, that cell will turn white and the first one will stay white.
Here is my php/jQuery code:
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-1.7.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery.event.drag-2.0.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-ui-1.8.16.custom.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.core.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.grid.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.editors.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.formatters.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.dataview.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellselectionmodel.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangedecorator.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangeselector.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.rowselectionmodel.js"); ?>
<?php // Setup rows and cols array for grid
$columns = array();
foreach($route['Stop'] as $stop) {
$columns[] = array( "name" => $stop['name'],
"field" => $stop['id'],
"id" => $stop['id'],
"editor" => "Slick.Editors.Text");
}
$tripId = 1;
$thisTrip['id'] = $tripId;
foreach($route['RouteTrip'] as $routeTrip) {
if($routeTrip['trip_id'] != $tripId) {
$rows[] = $thisTrip;
$tripId = $routeTrip['trip_id'];
$thisTrip['id'] = $tripId;
}
else {
$thisTrip[$routeTrip['stop_id']] = $routeTrip['time'];
}
}
?>
<?php
echo $this->Html->scriptBlock('
var rows = '.json_encode($rows).';
var columns = '.json_encode($columns).';
var options = { rowHeight:21,
defaultColumnWidth:100,
editable:true,
enableAddRow:true,
enableCellNavigation:true,
asyncEditorLoading:false,
autoHeight:true,
autoEdit:true
};
slickgrid = new Slick.Grid($("#scheduleTable"), rows, columns, options);
slickgrid.setSelectionModel(new Slick.CellSelectionModel());
slickgrid.updateRowCount();
slickgrid.render();
');
?>
The $rows and $columns are correctly formatted, and each column has an "editor" attribute with "Slick.Editors.Text" as its value.
Help?
I have also got this error initially when i started working with slickgrid.
The error is because you have specified the editor as string and not as a class.
So, remove the double quotes in "editor" => "Slick.Editors.Text" and give as "editor" => Slick.Editors.Text
This solved the error for me. Hope this solution will solve yours too.
Include the slick.editors.js file.
Also, make sure that the editor is being specified as a class, not as a string (I'm not familiar with PHP, so it's not obvious to me from the source code, but I suspect that's the case).

Dynamically add options to a list through a hidden iframe

I want to dynamically add options to a list through a hidden iframe; I suspect my mistake is in the PHP below:
<?php echo 'var oInner = document.createTextNode("'.$donnees["name"].'");'; ?>
because my code works perfectly with:
<?php echo 'var oInner = document.createTextNode("Newoption");'; ?>
I don't know why createtextnode doesn't want to take my PHP var... I thought it could be a same origin policy since the database is located on a server outside my website.
I don't know.
You'll find enclosed the complete code:
In my HTML I have:
//select or change a country will trigger the javascript part
<select name="countrym" id="countrym" onchange="validcountry();">
<option value"France">France</option>
</select>
//Empty region list
<select name="regionm" id="regionm">
</select>
//My Iframe
<iframe name="upload_iframe2" id="upload_iframe2" frameborder="0"></iframe>
In my Javascript I have:
//My function triggering the PHP through the Iframe
function validcountry() {
var countrym = document.getElementById('countrym');
var choixco = countrym.options[countrym.selectedIndex].value;
document.getElementById('upload_iframe2').src = 'region.php?choix='+choixco;
In my PHP region.php file, I have:
<?php
// Get my choice
$codepays = $_GET['choix'];
//Retrieve the regions corresponding to the country
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO(XXX);
$req = $bdd->prepare('SELECT name FROM regions WHERE country = :country');
$req->execute(array('country' => $codepays));
$donnees = $req->fetch();
while($donnees)
{
// I checked the format of the data (no problem so far)
echo var_dump ($donnees['name']);
?>
//I add an option through Javascript
<script language="JavaScript" type="text/javascript">
var oOption = document.createElement("option");
//Here is my big issue:
<?php echo 'var oInner = document.createTextNode("'.$donnees["name"].'");'; ?>
oOption.value = "none";
oOption.appendChild(oInner);
var parDoc = window.parent.document;
var regionm = parDoc.getElementById("regionm");
regionm.appendChild(oOption);
</script>
<?php
$donnees = $req->fetch();
}
$req->closeCursor();
exit();
?>
Have you tried simply oOption.innerHTML = '<?php echo $donnees["name"] ?>'; ?
I am suspecting that the indexed element cannot be found. But is all cases, this below should work.
<?php echo 'var oInner = document.createTextNode("'. (isset($donnees["name"]) ? $donnees["name"] : '') .'");'; ?>
Found the solution: it was the php inserting \n so the solution is to do the following:
$desc= 'var oInner = document.createTextNode("'.$donnees["name"].'");';
$desc= str_replace("\n", "",$desc);
$desc= str_replace("\r", "",$desc);
Thanks everybody

Categories