Echo two separate javascript getElementById's from php - javascript

I have PHP code that looks something like this which works fine on its own.
echo "<script type='text/javascript'>document.getElementById('flightTime3').innerHTML = </script>Dep: ";
However if I want to set the innerHTML of another element like so:
echo "<script type='text/javascript'>document.getElementById('flightDate3').innerHTML = </script>Arr: ";
The browser interperates it as setting the innerHTML of the first element only. So, the element with id flightTime3 shows "Dep: Arr: " and the element with id flightDate3 shows nothing.
How can I break up the javascript within the PHP so that it is recognised as two separate commands?

You are closing <script> tags before assigning a strings to .innerHtml by Javascript. Place assignment before you close the <script> tag.
echo "<script type='text/javascript'>document.getElementById('flightTime3').innerHTML = 'Dep:';</script>";

Related

How to add php variable/function into a javascript function [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I cant seem to add a php function / variable into my javascript. I need it to set options into a dynamic select form I have in javascript.
I tried "" inside the javascript which everyone recommended.
<?php
function options(){
include "connection.php";
$sql="SELECT DISTINCT PartID, PartName FROM parts";
$result = mysqli_query($conn,$sql);
if ($result) {
while ($row=mysqli_fetch_assoc($result)){
echo "<option value='{$row['PartID']}'>{$row['PartName']}</option>";
}}}
?>
<script>
$(function(){
$('p#add_part').click(function(){
counter_part += 1;
$('#container').append(
'<strong>Part No.'+ counter_part + '</strong><br />');
$('#container').append(
'<select><option>Select a Part</option>((((((HERE)))))
</select>');
});
});
</script>
The whole function does not work in relation to the methods I keep trying. When ever I add a '' inside the script to add a variable inside the option, the whole function stops working. However its possible to add a counter variable. Btw I have some other functions above the script etc that was irrelevant.
You can try storing it in an HTML element in PHP, then you can read it from JavaScript and then delete it from JavaScript. You can also set it at the bottom of the page and set the text color the same as the background color so you can't see it. I don't know much about PHP, but I do for JavaScript and HTML, so, sorry but I can only add the JavaScript and HTML.
HTML:
<span style="background-color:white; color:white;" id="phpVariable"></span>
JavaScript:
var element = document.getElementById("phpVariable"); // Get the element
var phpString = element.textContent; // Get a string
var phpInteger = parseInt(element.textContent) // Get an integer
var phpFloat = parseFloat(element.textContent) // Get a float
element.parentNode.removeChild(element); // Delete the element
For the PHP, you just have to append the HTML element above to the bottom of the page. If you're background is a different color, then you can just set both the background color and the text color to the background color of the page. Doing this will make the text invisible by just looking at it until the JavaScript picks it up and deletes the element.
Just echo your JavaScript function with PHP, and you can easily insert function variables with string concat. In example echo 'alert("'.$var.'"); or something like this!
I'm not sure that is what you want, but you can use PHP values of variables in your JS with simple echo to text. I just edited your to work. Declaring options into $options variable and return it in function is giving possibility to write them into JS with echo. You could do it with $options directly, without options() function.
PHP code works only once, then your echo values counted as hardcoded text in html file. Use this only if you need to get value once.
<?php
function options(){
include "connection.php";
$sql="SELECT DISTINCT PartID, PartName FROM parts";
$result = mysqli_query($conn,$sql);
if ($result) {
$options = '';
while ($row=mysqli_fetch_assoc($result)){
$options .= "<option value='".$row['PartID']."'>".$row['PartName']."</option>";
}
}
return $options;
}
?>
<script>
$(function(){
$('p#add_part').click(function(){
counter_part += 1;
$('#container').append(
'<strong>Part No.'+ counter_part + '</strong><br />');
$('#container').append(
"<select><option>Select a Part</option><?php echo options() ?></select>");
});
});
</script>

PHP altering HTML on first connection

Currently I have a php-page using include to show an html-page.
What I want to do is use a variable the php-page received when being called and project data into a field of the html-page depending on this variable. The problem is that I can't seem to pass the variable from php to html without using html to call php.
I know that I can simply echo the php-part, but because I can't echo straight into one of the html-page's divs it ends up putting the echo at the beginning or end of the page.
What I want to accomplish is for the html-page to load the php-part into one of the div's the first time the php includes the html-page. Is there any way to do such a thing?
If this isn't possible, then how do I get the javascript in the html-page to use the variable from the php-file? Is the best option really the href?
As requested some of the code:
php:
if (filter_input(INPUT_GET, "event", FILTER_SANITIZE_STRING))
{
include "../Html/EventPage.html"; //target page
$temp = filter_input(INPUT_GET, "event", FILTER_SANITIZE_STRING); //get the variable
include "../PHP/Connector.php"; //include the connection page
$value = callFunction(Connect(), $temp); //call connection page and return value
echo "<div class = 'cant select div in html'>" . $value . "</div>"; //echo value in location
}
html:
<div id = "dynamic">
this should have the php
</div>
I assume you use some code like this to display the page:
include('page.html');
A safer way would be to prevent evaluation in page.html:
echo file_get_contents('page.html', true);
You can then do any string modification you want for the content:
$replacement = 'MY REPLACEMENT';
echo str_replace('<div id="my-div">', '<div id="my-div">' . $replacement, file_get_contents('page.html', true));

echo variable to document via button click

First time here so apologies if I'm doing something wrong.
I have the following php code:
<?php
$quoteFile = "quotes.txt"; //File holding qoutes
$fp = fopen($quoteFile, "r"); //Opens file for read
$content = fread($fp, filesize($quoteFile));
$quotes = explode("\n",$content); //Put quotes into array
fclose($fp); //Close the file
srand((double)microtime()*1000000); // randomize
$index = (rand(1, sizeof($quotes)) - 1); //Pick random qoute
?>
The code fetches a random quote from a text file by randomly choosing one of the lines of the .txt file.
I then echo out the result using:
echo $quotes[$index];
However what I want to achieve and don't seem to be able to is to have a button (html) that when clicked executes the echo $quotes[$index]; to the current page. So that each time the button is clicked it prints/echo's out a random quote from the .text file.
I did mess about with just setting a button up to refresh the page which by default made a new random quote display but it sometimes just reloaded a blank so I'm hoping someone can help me achieve this better or prompt me in the right direction. Thank tou.
You can try saving that variable into a session variable like this:
$_SESSION['quote'] = $quote['index'];
Then create an anchor element that redirects to current page:
Refresh
And print the result on the page:
<span><?php echo $_SESSION['quote']; ?></span>
To do all of this, you need to set a session. At top of your php file write:
session_start();
Hope that helps. :)
Your TXT file might have an empty line in it at the end or anywhere else. A second explanation of this, is that the way you are generating randomness is quite questionable.
Check out this simple example by W3 Schools.
$a=array("red","green","blue","yellow","brown");
$random_keys=array_rand($a,1);
echo $a[$random_keys[0]]."<br>";
The array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.
Or, simply:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r(array_rand($a,1));
?>
Full Post: http://www.w3schools.com/php/func_array_rand.asp
Happy coding !

PHP Simple HTML DOM Parser not displaying alt tag as text

<?
include('simple_html_dom.php');
// Create DOM from URL or file
$html = file_get_html('http://www.saie.bolognafiere.it/it/partner/media-partner');
// Find all images
foreach($html->getAttribute('ul#slider356 alt') as $element)
echo $element->plaintext . '<br>';
?>
Actually I would like that all the alt tag content contained in the " ul id="slider356 " are displayed as text but my code is not working can someone help me ?
Thank you
To complete Sean's comment, there is two ways to get the attribute's value:
$node->attribute;
$node->getAttribute('attribute');
So, in your case, try this:
$html = file_get_html('http://www.saie.bolognafiere.it/it/partner/media-partner');
// Find all images inside ul#slider356
foreach($html->find('ul#slider356 img') as $element)
// Print alt value
echo $element->alt . "<br/>";
// $element->getAttribute('alt') should work as well
Working code
Please check the Manual for more info...

JQuery seems to be blocked by something else

JQuery seems to be blocked
Hello there, I've been confronting this problem for several days, I just can't find a way to get this fixed, or around it.
What I want to do is simple, I want to read out every sub-folder of a big Project folder. Then assign a thumbnail image and a figcapture to this folder. With a simple for loop, php builds this for me. Everything works perfect and quick. The only thing is that the jquery won't respond. Even though I have created various menus with this technique. As you can see in my code, in the "script" tags, I have the jquery code which doesn't seem to work.
I don't know wheter php puts in a space somewhere or I just looked too long at this code for seing the error.
I appreciate any help.
<?php
/*Because of the "ease of use" aspect of this site, I prefered to write it completely in PHP,
advantage of that:
Images are loaded directly out of the folder, so I can just drag and drop something onto the server without having to write aditional code.
As you see, it can save a lot of time.*/
echo "<h1>Referenzen</h1><br>";
$projects = scandir('../src/sub/credentials'); //The credentials directory is being scanned and converted into an array.
$projectsSize = count($projects); //$size is being created. It counts the number of objects in the array which has been created above.
$projectsCaptions = file('../src/sub/captionsOfCredentials.txt'); //Edit the name of the figcaption in the "captionsOfCredentials.txt".
for($i = 2; $i < $projectsSize; $i++){ /*Simple "for" loop, that creates $i with the size of two, because PHP is 0-index based and has the "dot" and the "dotdot" folder. The loop stops at the end of the array($size).*/
echo '<a href="index.php#PRJ'.trim($projectsCaptions[$i]).'" class="ID'.trim($projectsCaptions[$i]).'">
<div class="projectFolder">
<img src="src/sub/credentialsThumb/project_00'.$i.'.jpg" width="100%" />
<figcaption>'
.$projectsCaptions[$i].
'</figcaption>
</div>
</a>';
/*Project folder level starts here.*/
$images = scandir('../src/sub/credentials/project_00'.$i);
$imagesSize = count($images);
for($k = 3; $k < $imagesSize; $k++){
$tempID = ('ID'.trim($projectsCaptions[$i]).'.php'); //$tempID is the entire file name including the .php part.
$handle = fopen($tempID, "a") or die ('Unable to open '.$tempID.' , please contact admin A.S.A.P..');
$imagesCode = 'test';
fwrite($handle, $imagesCode);
}
//end second for-loop
echo "
<script>
$(document).ready(function () {
$('#ID".$projectsCaptions[$i]."').click(function () {
$('#mainContent').load('de-DE/".$tempID."');
});
});
</script>";
}
//end first for-loop
?>
You're selecting an element by id when you need to use class. Change the JS block to this:
$(document).ready(function () {
// Note ".ID" not "#ID"
$('.ID".$projectsCaptions[$i]."').click(function () {
$('#mainContent').load('de-DE/".$tempID."');
});
});
UPDATE
It seems like you've also got an illegal character in $projectsCaptions[$i]. It's most likely a newline character. Try wrapping the above reference above in trim():
$('.ID" . trim($projectsCaptions[$i]) . "').click(function () {

Categories

Resources