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.
Related
I am trying to pass variables stored in href links to a function. Im able to define the variables from the query results. My problem is passing it to the function once the hyperlink is clicked. This is my code:
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row)
{
echo "<a href='#' onclick='hrefClick(".$row['courseID'].");'/>".$row['courseID']."</a><br>";
}
?>
This is the function:
<script>
function hrefClick($course){
$newCourse=$course;
}
</script>
PHP Code :
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row)
{
echo "<a href='#' onclick='hrefClick(".$row['courseID'].");'/>".$row['courseID']."</a><br>";
}
?>
Function should be as:
<script>
function hrefClick(course){
// You can't define php variables in java script as $course etc.
var newCourse=course;
alert(newCourse);
}
</script>
We will be using two file here. From file1.php onclicking the link we will send the data via Ajax to file2.php. It is a Jquery based solution.
//file1.php
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row){
echo '<a href="javascript:void()" data-href="'.$row['courseID'].'"/>'.$row['courseID'].'</a><br>';
}
?>
<script>
$('a').click(function(){
var hrefData = $(this).attr('data-href');
if (typeof hrefData !== typeof undefined && hrefData !== false) {
alert(hrefData);
//or You can post the data
$.post( "file2.php", { courseid:hrefData} );
}
});
</script>
You can retrieve the result on file2.php
//file2.php
<?php
if(isset($_POST['courseid'])){
$newCourse = $_POST['courseid'];
}
?>
I was able to find a way to get it done? It seems pretty straightforward. This is what I came up with.
<?php
foreach($pdo->query('SELECT * FROM sk_courses ORDER BY courseID') as $row){
echo "<form name='course".$row['courseID']."' action='index.php' method='GET'/>";
echo "<a href='javascript: document.course".$row['courseID'].".submit();'/>".$row['courseID']."</a>";
echo "<input type='hidden' name='courseID' value='".$row['courseID']."'/><br>";
echo "</form>";
}
?>
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(); ?> "]
I want to change the innerHTML with PHP code. But I cannot get it to work, and I do not understand why. I want it to change some text on the page but from another file. And so I thought that I could use this:
document.getElementById ("page"). innerHTML = "<? php echo $ home?>";
But it does not work.
Here is my code:
<?php
$home = file_get_contents("home.php");
?>
<script type="text/javascript">
function ChangePage(page)
{
if(page == "home")
{
document.getElementById("page").innerHTML = "<?php echo $home ?";
}
}
</script>
There are many small typos. Try removing the space between $ and 'home' and before 'php'. This is the right statement:
document.getElementById ("page"). innerHTML = "<?php echo $home?>";
Also, where's your closing php tag?
<?php
$home = file_get_contents("home.php");
?>
<script type="text/javascript">
function ChangePage(page)
{
if(page == "home")
{
document.getElementById("page").innerHTML = "<?php echo $home; ?>";
}
}
</script>
Although this is a bad practice. Why would you want to do this instead of simply loading the php in the right place? Also, you do realize that 'page' should be the id of a pre-existing div in your html, right? Something like this would be better:
<html>
<body>
<div id = "page">
<?php echo file_get_contents("home.php"); ?>
</div>
</body>
</html>
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>';
}
?>
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