Javascript functions are being called all at once - javascript

The purpose of my code is to randomly display four icons and depending on which one the user clicks on, a small amount of text will be appended to a text file. My problem is that, after an icon is clicked on, all four of the functions are called which writes to the txt file four times. How can I get it so that only the correctly corresponding function is called.
<div style="text-align:center" "padding-left: 60px">
<form action="(im hiding the URL)construct/index.html" id="formid" onclick= function() {myFunction()}>
<form>
</form>
</form>
</div>
<script>
document.getElementById("icon_1.png").onclick = function writeTo1(){
<?php
$file = fopen("icon_select.txt","a");
echo fwrite($file,"-Icon 1-");
fclose($file);
?>
}
document.getElementById("icon_2.png").onclick = function writeTo2(){
<?php
$file = fopen("icon_select.txt","a");
echo fwrite($file,"-Icon 2-");
fclose($file);
?>
}
document.getElementById("icon_3.png").onclick = function writeTo3(){
<?php
$file = fopen("icon_select.txt","a");
echo fwrite($file,"-Icon 3-");
fclose($file);
?>
}
document.getElementById("icon_4.png").onclick = function writeTo4(){
<?php
$file = fopen("icon_select.txt","a");
echo fwrite($file,"-Icon 4-");
fclose($file);
?>
}
</script>

Looks to me like the 4 bits of PHP are running when the page is requested, and therefore adding to the text file at that time. Then the functions are empty when the JavaScript runs so it has no effect. Check the page source in the browser to see what the functions look like to the browser and after page load but before clicking on an icon check to see if the text has been added to the file.

Related

Update content with Ajax. How to separate the output in HTML <div>

I am updating my site content with AJAX by using this method i have found here: https://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html
This works very well but according to this tutorial i have to echo the values i want to show as an updated value in the background running "record_count.php". Later all values are shown up in my frontend file "index.php" within the specific <div id="xxx">. my problem is now that in my background "record_count.php" i have several values i echo but in need them in separate HTML <div id="1, 2, ...> In my example it is $name and $city. How can i connect the values to a specific HTML <div id="1, 2, ...> ? (Please ignore the old query method i have copy/paste here. In my code i am using prepared statements with PDO)
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php?q=<?php echo $id; ?>').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
<body>
<div id="load_tweets"> </div>
</body>
</script>
record_count.php
<?php
include("db.php");
$search_word=$_GET['q'];
$sql = mysqli_query($db,"Select name, city FROM users where id = $id");
$record_count=mysqli_num_rows($sql);
//Display count.........
echo $city;
echo $name
?>

PHP, HTML, JS conflicting execution order

I have having big issues with the execution order of my code.
HTML sample:
<div id="toast-container" class="toast-top-right"><div id="toast-type" class="toast" aria-live="assertive" style=""><div id="snackbar">message</div></div></div>
.
.<!--Somewhere more down the line-->
.
.
<div class="col_half col_last">
<label for="job-ctc-frm-heard-about">How did you find out about us?</label>
<input type="text" id="job-ctc-frm-heard-about" name="job-ctc-frm-heard-about" value="<?php echo $discovered;?>" class="sm-form-control" />
</div>
Javascript function:
<script>
function Toast(message, messagetype)
{
var cont = document.getElementById("toast-container");
cont.classList.add("show");
var type = document.getElementById("toast-type");
type.className += " " + messagetype;
var x = document.getElementById("snackbar");
x.innerHTML = message;
setTimeout(function(){ cont.classList.remove("show")}, 3000);
}
</script>
PHP sample:
<?php
$discovered ="";
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$message = 'Let the games begin';
echo "<script type='text/javascript'>Toast('$message', '$Success');</script>";
$discovered = test_input( $_POST["job-ctc-frm-heard-about"] );
......
?>
Now heres my problem. My php uses a function Toast. My function Toast accesses the HTML div toast-container to set a message. The other div uses the php variable $discovered to remember the entered value on a failed form submit. If i position the JS anywhere before the DOM then var cont will be null so it has to be below.
However if I position the code order as PHP -> HTML -> JS then the function is undefined in PHP so it has to be after JS. But if i position it as HTML -> JS -> PHP then the variable $discovered won't be displayed in the HTML. The orders are conflicting with one another. Is there any work around for this?
The simplest would be to just move the relevant parts to where you need them. You need $discovered to be available throughout your file (when PHP is executed server-side) and you need it to echo the script specifically after your Toast-declaration:
<?php
$discovered ="";
if($_SERVER["REQUEST_METHOD"]=="POST") {
$message = 'Let the games begin';
$discovered = test_input( $_POST["job-ctc-frm-heard-about"] );
// ...
}
?>
<!-- HTML referencing $discovered here -->
<script>
function Toast(message, messagetype)
{
var cont = document.getElementById("toast-container");
cont.classList.add("show");
var type = document.getElementById("toast-type");
type.className += " " + messagetype;
var x = document.getElementById("snackbar");
x.innerHTML = message;
setTimeout(function(){ cont.classList.remove("show")}, 3000);
}
</script>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST") {
echo "<script type='text/javascript'>Toast('$message', '$Success');</script>";
}
?>
If you want to control these things from client-side, you can json_encode your PHP objects, meaning they will be sent in plain-text as if you had hard-coded them into the file. As #FZs mentions, PHP runs on the server and "prepares" the file by executing all <?php ... ?> blocks. When the result reaches the browser, it contains the resulting text and not PHP (browsers don't understand PHP).

Link to Code Automatic with Custom Text

I had last time asked that how to get an automatic generated link on the body of website of file uploaded on ftp-server.
Link is this Link to Code Automatic.
But my father wanted that it should not display the filename. Instead it should display that name that he would feed on some other page.
My main storyline is that when i go to that page, it asks me to enter a name that is to be displayed and next to it after <br>, it should give a dropdown menu of the files on the ftp-server and ask me to select the one for which i gave the name. Further on submitting, it displays the link to the file with the name i game.
Kindly help me solve this problem because i am a beginner at PHP and SQL.
Thanks
For the first page, use what was suggested in the first question, but use a HTML select instead:
<?php
// page1.php
// ...
// create a form element
echo '<form action="page2.php" method="get">';
// create the 'name' input
echo 'Enter the displayed name: <input name="name" placeholder="displayed name"><br />';
// start the dropdown
echo 'Enter the file the link should point to: <select name="file">';
// get all files that should be displayed
$files = scandir(__DIR__);
$files = array_diff($files, array('.', '..'));
foreach ($files as $file) {
// add an option to the dropdown
echo '<option value="' . $file . '">' . $file . '</option>';
}
// close the dropdown and the form
echo '</select>';
// add a submit button to the form
echo '<button type="submit">Submit</button>';
echo '</form>';
// ...
?>
On the second page, display the link:
<?php
// page2.php
// ...
$name = $_GET['name'];
$file = $_GET['file'];
echo '' . $name. '<br>';
// ...
?>

Using PHP inside of HTML to redirect to a random site [duplicate]

This question already has an answer here:
How Can I Create a Button that links to multiple websites randomly?
(1 answer)
Closed 6 years ago.
I need to be able to have the user click a button, and be redirected to a random page.
I tried putting the PHP inside of JavaScript, and that inside of HTML, like this:
<script>
<button onclick="var jsVar = "<?php
$urls = array("www.site1.com", "www.site2.com", "www.site3.com","www.site4.com");
$url = $urls[array_rand($urls)];
header("Location: http://$url"); ?>"">Click</button>
</script>
I know this may have many errors, and help is very appreciated. Thank you!
Try this,
<?php
$urls = array("www.site1.com", "www.site2.com", "www.site3.com","www.site4.com");
$url = $urls[array_rand($urls)];
?>
<button onclick="myfunction();">Click</button>
<script>
function myfunction(){
var href = "<?php echo $url?>";
window.location.href = "http://"+href;
}
</script>
PHP script will generate random URL, when you click on the button, it will call randsite($url) JavaScript function, that function will redirect you to random sites.
<?php
$urls = array("http://www.site1.com", "http://www.site2.com", "http://www.site3.com","http://www.site4.com");
// select random url
$rand = $urls[mt_rand(0, count($urls) - 1)];
?>
<button onclick="randsite(<?php echo "'".$rand."'"; ?>)">Click</button>
<script type="text/javascript">
function randsite($url){
window.location = $url;
}
</script>
PHP + HTML + JS :
<?php $url = "http://....."; ?>
<button name="redirect"onclick="redirectFunc(<?php echo $url; ?>);">Redirect with button</button>
<script>
function redirectFunc($url){
window.location.href = "<?php echo $url?>";
}
</script>
Redirect HTML + PHP:
http://www.w3schools.com/php/php_forms.asp
Suppose your php file is located at the address:
http://www.yourserver.com/form-action.php
In this case, PHP_SELF will contain: "/form-action.php"
<form method="post" action="<?php $_PHP_SELF ?>">
// type means what should button do submit -> submit your post
// name how you will recognize which post was sended
// value value of button which you can get
<button type="submit" name="redirect" value="redirectValue" id="redirect">Redirect with button post</button>
</form>
and then you handle your post on button click
<?php
if(isset($_POST['redirect'])) {
// rand your url
// echo $_POST['redirect']; will output redirectValue
header('Location: http://....');
}
?>
Or with ahref:
http://www.w3schools.com/html/html_links.asp
//or you can use ahref e.g
<?php $url = "http://...";
// code for randoming url
?>
Redirect with a href</p>
HTML + JS:
<button id="buttonID">redirect</button>
<script type="text/javascript">
// here you can rand your urls and choose one of them to redirect
document.getElementById("buttonID").onclick = function () {
location.href = "http://...";
};
</script>

Executing php file from another php file

Can I trigger the execution of a php file from another php file when performing an action? More specific, I have an anchor generated with echo, that has href to a pdf file. In addition of downloading the pdf I want to insert some information into a table. Here's my code, that doesn't work:
require('./database_connection.php');
$query = "select author,title,link,book_id from book where category='".$_REQUEST['categorie']."'";
$result = mysql_query($query);
$result2 = mysql_query("select user_id from user where username='".$_REQUEST["username"]."'");
$row2 = mysql_fetch_row($result2);
while($row= mysql_fetch_row($result))
{
echo '<h4>'.$row[0].' - '.$row[1].'</h4>';
if(isset($_SESSION["username"]) && !empty($_SESSION["username"]))
{
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo ' <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function insert_download() {
$.ajax({
type: "GET",
url: "insert_download.php" ,
success : function() {
location.reload();
}
});
}
</script>
<a onclick="insert_download()" href="'.$row[2].'" download> download </a>';
}
And here's the insert_download.php:
<?php
require('./database_connection.php');
$query = "insert into download(user_id,book_id,date)values(".
$_REQUEST["id_carte"].",".
$_REQUEST["id_user"].",".
date("Y-m-d h:i:s").")";
mysql_query($query,$con);
mysql_close($con);
?>
Can anyone help me with this? Thanks!
As I understand correctly, you want to display a link, and when the user clicks that link,
some data is inserted into a database or something;
the user sees a download dialog, allowing him to download a file?
If this is correct, you can use this code:
On your webpage:
download
result.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "";
?>
<!DOCTYPE html>
<html>
<head>
<title>Downloading...</title>
<script type="text/javascript">
function redirect(url) {
//window.location.replace(url);
window.location.href = url;
}
</script>
</head>
<body>
Download is starting...
<script type="text/javascript">
redirect("http://example.com/download.php?file=dummy.pdf");
</script>
</body>
</html>
download.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "nullfile";
$file_url = "download_dir_or_something/".$file;
// Put some line in a log file...
file_put_contents("logfile.txt", "successful on ".date("Y-m-d H:i:s")."\n", FILE_APPEND);
// ...or anything else to execute, for example, inserting data into a database.
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".basename($file_url)."\"");
readfile($file_url);
?>
Why not use a redirection instead of "complicated" AJAX?
<!-- in your first document -->
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo 'download';
and in download_pdf.php
<?php
require('./database_connection.php');
...
mysql_close($con);
header("location: " . $_GET['redirect']);
You're lacking basic skill of debugging. If I was you, I should:
Use a browser which supporting, ex: Chrome with "Network" inspecting tab ready
Try click on the link <a onclick="insert_download()" ... and see if the ajax request is performed properly (via Network inspecting tab from your chrome). If not, re-check the generated js, otherwise, something wrong with the download_pdf.php, follow next step
Inspecting download_pdf.php: turn on error reporting on the beginning (put error_reporting(E_ALL); and ini_set('display_errors', 1); on top of your file) try echoing something before and/or after any line you suspect that lead to bugs. Then you can see those ajax response from your Network inspecting tab... By doing so, you're going to narrow down which line/scope of code is causing the problem.
Note that the "echoing" trick can be avoid if you have a solid IDE which is supporting debugger.
Hope it can help

Categories

Resources