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>
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>";
}
?>
ok so I have this in my HTML code:
<script type="text/javascript" src="load2.php"> </script>
I saw somewhere you could call a php file like that and the javascript contained in it will be rendered on the page once echoed.
So in my PHP file i have this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['DayNum']; }
$length = count($storeArray);
I connected to my database and stuff and pulled those records and stored them in an array. Now my problem is alerting them using js. This is what I have:
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
The test() function is being onloaded in my HTML page, but for nothing the values in the array won't alert. Any help please?
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
This code is literally writing what you have written above. It's not completely clear, but I believe your intent is to loop over the contents of your database data, and alert that to the browser with alert() function.
You can achieve this in a couple of ways.
Write multiple alert statements
echo "function test() {"; //Outputting Javascript code.
for($i = 0; $i<$length; $i++){ //Back in PHP mode - notice how we aren't inside of a string.
$value = $storeArray[$i];
echo "alert($value)"; //Outputting Javascript code again.
}
echo "}"; //Outputting Javascript code to close your javascript "test()" function.
Write a Javascript array, then loop over it in Javascript
echo "function test() {";
echo " var storeArray = ['" . implode("','", $storeArray) . "'];";
echo " for (var i = 0; i < storeArray.length; i++) {";
echo " alert(storeArray[i]);";
echo " };";
echo "}";
Finally, you could use AJAX and JSON to load the data, rather than outputting a JS file from PHP. That is an entirely different topic, though, and you should search StackOverflow for more examples as there are numerous questions and answers involving it.
Unless your array contains only number, you probably have JS error. You should put your $storeArray[i] in quotes in the alert function so it considered as a string in js.
alert('$storeArray[i]');
Once printed out, the JS will look something like this
alert('foo');
alert('bar');
Whereas with your code, it would've printed it like this
alert(foo);
alert(bar);
in your php file include load2.php
header("Content-Type: text/javascript");
in the in the top. so your browser get what it wants.
$i=0;
$storeArray = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[$i] = $row['DayNum'];
$i++;
}
echo "var arr = Array();";
echo "function test() {";
foreach ($storeArray as $key=>$item) {
echo "arr[".$key."] = ".$item.";";
}
echo "}";
echo "alert(arr);";
actually you can comment out the two echos containing the <script></script> part when including the file as <script src="load2.php" type="text/javascript" ...
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/
Basically by clicking the "comment" link the last result of the query should show and by clicking again it should be hidden. I have tried Rocket's code as well but I get an error message in the bottom of the browser and when I click "comments" it just takes me to the top of the page. I would apprieciate some advice on this
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
This is a loop, echoing the same thing over and over, thus making all the divs have the same ID, something2.
IDs need to be unique, you gonna have to make unique IDs for each div.
Something like: <div id='something$i' style='display: none;'> (remembering to increment $i).
Also, you're gonna to escape the quotes in your onclick attribute.
<a href='#' onclick=\"toggle_visibility('something$i');\">
The code should look something like this:
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
Escape the quotes :
$blah = "onclick='toggle_visibility(\"something2\");'>Comments</a>"
There is an easier way to hiding / showing the next sibling ....
try this
<div style="display:none">some hidden content</div>
function toggle(el,ev) {
ev.preventDefault(); // prevent the link from being followed
el = next(el); // get the next element
if (el.style.display == "none") { // toggle the display
el.style.display = "block";
} else {
el.style.display = "none";
}
}
/*
Credit to John Resig for this function
taken from Pro JavaScript techniques
*/
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
Working example
You can throw in a counter into your code as the while loop is executing to dynamically generate unique id's for each comment div. Or, you can pull a unique field out of the query result for the id's, as long as you hook up to it appropriately later if it ends up being used and remain consistent in the rest of the code.
either
$count = count($result);
...
while (...){
$count--;
echo '... id="something'. $count .'" ...'
}
or...
while (...){
echo '... id="something'. $row['ID'] .'" ...'
}
I have a php loop that is echoing out geolocation values. How can I get it to write those values to a javascript array, so I can then use them to plot points on an HTML5 canvas?
The php loop is as follows
<ul id = "geo-list">
<?php foreach($data as $phrase) { ?>
<li><?php
if ($phrase->geo != false) {
echo " | From (";
echo $phrase->geo->coordinates[0];
echo ",";
echo $phrase->geo->coordinates[1];
echo ")";
} else {
echo " | No Location Data";
}
?>
</li>
<?php } ?>
</ul>
Did you try
var myJavascriptData = <?= json_encode($php_data) ?>;
You might want to take advantage of the JSON library for PHP.
The cleanest way to pass data to a browser's javascript program is to put it into a "hidden" html table.
The html should look something like
echo "\n<TABLE style='display: none;' id='DATTAB' >" ;
get_rows();
while ($cf = next_row()) {
echo "\n <TR>";
echo "\n<TD>" . $cf['KEY'] . "</TD>";
echo "\n<TD>" . $cf['COL1'] . "</TD>";
echo "\n<TD>" . $cf['COL2'] . "</TD>";
echo " </TR>";
}
echo "\n</TABLE>";
This table is then easily accessable from your javascript:-
var dtab = document.getElementById("DATATAB");
var rows = dtab.getElementsByTagName("tr");
for (var r = 0; r < rows.length ; r++) {
row = rows[r];
item_key = row.cells[0].innerHTML;
item_col1 = row.cells[1].innerHTML;
item_col2 = row.cells[2].innerHTML;
// do your thing here ......
}
Alternatively you could look at using the AJAX libraries like prototype or dojo
which have the all javascript components for accessing data from a "REST" type service.
You then need to write a separate service which gets the XML or JSON required for your page.
My suggestion is to dump a script block to the output and set them in a variable there.
The array definition will have to actually be in the javascript code that gets output to the page.
e.g., you'll need an output of something like:
<script type="text/javascript">
var coords = new Array(2);
coords[0] = new Array(2);
coords[0][0] = 123.45;
coords[0][1] = 987.65;
coords[1] = new Array(2);
coords[1][0] = 234.56;
coords[1][1] = 876.54;
</script>
There are more efficient ways to create this array statically, but this is just an example.
A more efficient way (in terms of code) would be to build up a string that defined the literal array, then dump out a javascript definition. The output would be something like:
<script type="text/javascript">
var coords = [[123.45,987.65],[234.56,876.54]];
</script>
so in your loop within php, you'd build up a string which would ultimately contain var coords = [[123.45,987.65],[234.56,876.54]]. Outside your loop, you wrap it in the script blocks and output it to the page.