Functioncall to javascript not working - php

i'm using php to generate some button that have their Id and the Id of the text they should show as parameters. But for some reason the function call doesn't seem to be working.
while($row=$query->fetch(PDO::FETCH_BOTH))
{
$reviewDoor=$row[0];
$korteTekst=$row[1];
$langeTekst=$row[2];
echo "<article><h4>Review van $reviewDoor</h4>";
echo "<section>$korteTekst</section>";
if (!empty($langeTekst))
{
echo "<section id='LongReview$teller' class='LongReviews'>$langeTekst</section>";
echo "<button id='LeesMeerKnop$teller' class='LeesMeerKnoppen' onclick='readMoreLess(LeesMeerKnop$teller,LongReview$teller)'>Lees meer...</button>";
}
echo "</article>";
$teller++;
}
the file link is working
<script src="script.js" type="text/javascript"></script>
and this is the function I'm trying to call
function readMoreLess(knopId,tekst) {
var knop=getElementById(knopId);
var review=getElementById(tekst);
window.alert("hallo");
if (knop.textContent ==="Lees meer...")
{
knop.textContent="Minder tekst...";
review.style.display="block";
}
else if (knop.textContent ==="Minder tekst...")
{
knop.textContent="Lees meer...";
review.style.display="none";
}
}

Looks like missing quotes on params values in function call:
echo "<button id='LeesMeerKnop$teller' class='LeesMeerKnoppen' onclick='readMoreLess(\"LeesMeerKnop$teller\",\"LongReview$teller\")'>Lees meer...</button>";

Related

Concatenate variable to a link in PHP

I would like to link a variable to a link.
The variable looks something like this which I grab from json.
The json variable for $movieSeat is : A1,A2,B3,V4
Below is the code that I've tried out.
The issue that I am currently having is, the link doesn't seem to be working. It seems like something to do with . and +.
I'm also not too sure when to use . and + for the linking.
<?php
echo "<script> function movieBTN(x) { location.href = 'http://movie.com/movieOne?seatNum=" . $movieSeat. "'; } </script>";
for ($i = 0; $i < $jsonCounter; $i++) {
$movieSeat = $jsonValue[$i]->seatID;
echo "<button onclick = movieBTN(".$movieSeat.")> Movie Seat </button>";
}
?>
First of all, if you're echoing the function from PHP, make sure you use JS variables and not PHP's:
echo "<script> function movieBTN(x) { location.href = 'http://movie.com/movieOne?seatNum=' + x; } </script>";
So it will output:
<script>
function movieBTN(x) { location.href = 'http://movie.com/movieOne?seatNum=' + x; }
</script>
Next, you need to wrap the variable passed to that function with ':
echo "<button onclick = movieBTN('".$movieSeat."')> Movie Seat </button>";
So it will output as:
<button onclick = movieBTN('A1')> Movie Seat </button>

Pass href onclick variable to function in PHP

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>";
}
?>

load() isn't working within PHP echo

I have the following snippet on my index page so that all links clicked on within the navbar will load within the 'content' div:
$(document).ready(function()
{
$("a.link").click(function() {
return false;
});
$("#navbar a").click(function(){
var a_href = $(this).attr('href');
$("#content").load(a_href);
});
});
This snippet works fine... But upon loading the page, I check with PHP to see if the index page has an argument to direct it to a specific page, which doesn't seem to work:
<?php
if(array_key_exists('page',$_GET)){
echo "<script>$('#content').load('" . $_GET['page'] . "', 'content')</script>";
} else {
echo "<script>$('#content').load('home.php')</script>";
}
?>
It may be a simple case of "it's staring you in the face but you've been looking at it for too long", but I can't seem to get the PHP snippet to work.
EDIT: I wrapped it in document.ready(), and it doesn't seem to have had an effect:
echo "
<script>
$(document).ready(function()
{
$('#content').load('home.php');
});
</script>";
Try this
<?php
echo "<script>"
echo "$(document).ready(function () {";
if(array_key_exists('page',$_GET)){
echo "$('#content').load('" . $_GET['page'] . "', 'content');";
} else {
echo "$('#content').load('home.php');";
}
echo "});";
echo "</script>";
?>

Is there a way to apply the button() jquery ui function to a button when it's loaded?

Basically. I have a javascript loop that posts to a php script. To append on the response to a DIV in a log. The response has a button inside it. The problem is, when a new response is made and appended, the jquery button function makes all the previous appended buttons larger. (Probably because it's calling the jquery button() function again on the same DIV elements.)
Is there a way to apply the button() jquery ui function to a button when it's loaded? (Instead of applying it to every element with the same name?)
This php is quite similar to the following (but this is shortened.) Just to give you an idea of what the php script does.
<?php
echo "<script type='text/javascript'>
function addButton(x) {
x = this;
$(x).button({
icons: {
primary: 'ui-icon-alert'
}
});
}
</script><div id='chat_wrap' class='message".$id."' hidden='true'>";
if ($query_run = mysql_query($finalchatq)) {
if (mysql_num_rows(mysql_query($finalchatq)) > 0) {
$counter = 0;
$amount = array();
while ($query_rows = mysql_fetch_assoc($query_run)) {
$time1 = $query_rows['time'];
$time2 = substr_replace($time1, " : ", 10, 1);
$time = str_ireplace('.', '/', $time2);
$text = str_ireplace('removem', '', $query_rows['text']);
$id = $query_rows['id'];
if($query_rows['type']=='notice') {
echo "<div selectable='false'><div id='date'><div id='notice'>NOTICE:</div>Sent At: ".$time."</div><div id='Nchat_message'><div id='chat_text'>".$text."</div><img id='charhead' src='camperhead.php?id=".$query_rows['who']."' id='charhead'></img></div>";
echo "<div id='controls'>";
if(userIsA('admin')||userIsA('mod')) {
echo "<input hidden='hidden' name='idtodel' value='".$id."'></input><input type='button' value='DELETE' id='delete_button'></input>";
} else {
}
echo "</div></div></div><br/><br/>";
}
if($query_rows['type']=='normal'){
echo "<div selectable='false'><div id='date'><div id='by'>".getUserFieldById($query_rows['who'], 'camper_name').":</div>Sent At: ".$time."</div><div id='chat_message'><div id='chat_text'>".$text."</div><img id='charhead' src='camperhead.php?id=".$query_rows['who']."' id='charhead'></img>";
echo "<div id='controls'>";
if(userIsA('admn')||userIsA('md')) {
echo "<button id='delete_button' class='dpp2' onclick='delCom(".$id.")'>Delete</button>";
} else {
echo "<button id='report_button' onload='addButton(this)' onclick='reportCom(".$id.")'>REPORT</button>";
}
echo "</div></div></div></div></div><br/><br/>";
}
}
echo "</div>";
}
}
}
?>
I hope I've made my question clear enough, if you have any concerns please post a comment and I'll reply as soon as I can.
Try using the .on() function in jQuery to define it when created http://api.jquery.com/on/

Calling a JS function in PHP

I know it`s possible to call javascript functions in php and it has worked but when i try to call checkSecondValue, nothing happens. I have included my variations on calling the function.
Edit: If i try to call it at the bottom without activating the onChange event in the select, it won`t work.
<!--<html>
<head>
<script type="text/javascript" src="validation.js"></script>
</head>
</html>
<script src="validation.js" type="text/javascript"></script>
-->
<?php
//retrieve all the bris for the drop down
include '../../inc/database.php';
$res = BbqcDatabase::getInstance()->doQuery('SELECT * FROM T_TOURNOI_BRIS');
$str = "<select name='ddlBrisSelected' id='ddlBrisSelected' onChange='checkSecondValue()'>";
$bris = ($_GET['bris']);
if($bris == 4)
{
$bris2 = "autre";
}
if($bris == null)
{
$str .= "<option value='' selected></option>";
}
else
{
$str .= "<option value=''></option>";
}
$i = 0;
while($data = mysql_fetch_assoc($res))
{
if($data['F_BRISID'] == $bris)
{
$str .= "<option value='" . $data['F_BRISID'] . "' selected '>" . $data['F_BRISTITLE'] . "</option>";
}
else
{
$str .= "<option value='" . $data['F_BRISID'] . "'>" . $data['F_BRISTITLE'] . "</option>";
}
}
if($bris2 == "autre")
{
$str .= "<option value='autre' selected>Autre</option>";
}
else
{
$str .= "<option value='autre'>Autre</option>";
}
$str .= "</select>";
echo $str;
if(is_numeric($bris))
{
/* echo "<SCRIPT language=\"JavaScript\" SRC=\"validation.js\">checkSecondValue();</SCRIPT>"; */
/* echo "<script> checkSecondValue();</script>"; */
/* echo "<script type=\"text/javascript\">checkSecondValue();</script>"; */
/* echo '<script type="text/javascript">', 'checkSecondValue();', '</script>'; */
/* echo "<SCRIPT LANGUAGE='javascript'>checkSecondValue();</SCRIPT>"; */
}
?>
You can't call client-side javascript functions from PHP, but you can echo code that makes the client call the function on a specific (client-side) event.
Just look at the generated HTML you get from your PHP, and from there, try to see why checkSecondValue() isn't executed on an onChange event.
At the very least, you want your function call to happen only after the page is loaded. This can be done by embedding the function in the body tag during onload:
<body onload="checkSecondValue();">
The function call is going to execute on the client-side, after the entire page has been processed by PHP. You can't communicate back-and-forth between JavaScript and PHP during the process of the page.

Categories