Good morning everyone,
I am reading a textfile from our server which changes its content every 10 seconds. I am displaying it using this code:
<div id="textfile">
<?php
$file = $_SERVER['DOCUMENT_ROOT'] . "/resources/file.txt";
$content = file_get_contents($file);
echo $content;
?>
</div>
I am using jquery in updating the content and displaying it.
setInterval(function() {
$('#textfile').load(document.URL + " #textfile");
}, 10000);
However if it is updated, it creates another < div >.
Previously it looks like this..
<div>Content</div>
But after it refreshes, it looks like this..
<div>
<div> Content </div>
</div>
Can anyone tell me what is wrong with this code and please help me so that it won't create another < div > after it refreshes..
You can load the text file directly, and reload it every 10 seconds.
<div id="textfile"></div>
<script src="path/to/the/jquery/lib.js"></script>
<script>
$(function() {
setInterval(function() {
$('#textfile').load('path/to/the/text/file.txt');
}, 10000);
});
</script>
Related
<html>
<head>
<script type="text/javascript">
function showdivv(el, idclicked) {
var iddd = idclicked;
var display = document.getElementById(el).style.display;
if(display == "none")
document.getElementById(el).style.display = 'block';
else
document.getElementById(el).style.display = 'none';
}
</script>
<?php $showw = "<script>document.write(iddd)</script>"; ?>
</head>
<body>
<div id="myDiv" style="display: none;">ID Selected: <?php echo $showw; ?></div>
<?php $variable = 4; ?>
<button type="button" onclick="showdivv('myDiv', '<?php echo $variable; ?>')">Show / Hide</button>
</body>
I'm trying to make a way when a person presses the button pass the variable, in this case ID, to JavaScript and then show the hidden div in PHP. It does not work, can someone help me? THX
If you're okay with the page reloading, you can simply do
window.location.href('php_script_that_needs_your_input.php?id=input_id_from_js');
If not, I absolutely recommend using JQuery as it makes Ajax queries a breeze.
Inside the <head> tags:
<script src='http://code.jquery.com/jquery-2.2.0.min.js'></script>
Upload the script to your own server for production purposes, obviously.
in the <body>, where you want the results from the PHP script to appear (skip this if you don't want output from PHP):
<div id="phpResult"><!--content to be set by ajax--></div>
and put this JS directly below this <div>:
function ajax_on_button_press(resultDiv, id) {
var phpUrl = "php_script.php?id="+id+"&other_variable=cheese&more_info=rats";
$(resultDiv).load(phpUrl);
}
I have used example values here, but you can easily use variables from JavaScript like this:
var other_variable=$('#otherVariableInput').val(); //gets input from a textbox with the html id otherVariableInput
var phpUrl = "php_script.php?id="+id+"&other_variable="+other_variable+"&more_info=rats";
To start the process, you need a button that runs this script. Change your button markup to
<button type="button" onclick="ajax_on_button_press('#phpResult', '<?php echo $variable; ?>')">Show / Hide</button>
If I have understood you correctly, that should solve your problem.
I am having a problem with jQuery where by it is not loading inside a requested div.
Setup:
On index.php I have 4 Morris charts on 4 tabs all working fine.
On each tab there is a list. Each item in the list is a link
Upon clicking the link the div within the tab reloads with new data
via post:
$(document).ready(function () {
$('.click5').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company5-'+companyId+' .clickthrough5').val(),
ref_date_from5: $('#company5-'+companyId+' .ref_date_from5').val(),
ref_date_to5: $('#company5-'+companyId+' .ref_date_to5').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
The new div contains a back button to take you back to a replica of the 1st graph but on a different page (donut1.php), for my personal ease:
$(document).ready(function () {
$('.backref2').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut1.php', {
clickthrough6: $('#company6-'+companyId+' .clickthrough6').val(),
ref_date_from6: $('#company6-'+companyId+' .ref_date_from6').val(),
ref_date_to6: $('#company6-'+companyId+' .ref_date_to6').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
All this code works fine up until landing on donut1.php.
At this point I proceeded to pull out chunks of my hair for several hours looking through Inspect Element in Chrome to identify the issue.
1 bald person later I realised the jQuery was not loading although it is correctly requested in a script tag.
I confirmed this by placing the following on both donut1.php and donut5.php:
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
donut5.php displays the output fine while donut1.php does not.
I then tried to load an external source and a different version using the Google snippets found here but this still did not work.
Some points to note:
I currently have jquery loading in my header and footer as part of trying to work this out.
As the 2 pages donut1.php and donut5.php do not include header or footer I have manually included them both in there. Same exact way in both files. donut5.php works donut1.php does not.
Order is index.php > donut5.php > donut1.php and then you continue to cycle between donut5 and donut 1 - or you would if the post on click was working in donut1.php.
Any help would be greatly appreciated!
EDIT: donut1.php:
<?php
include("../../../includes/config.php");
$selected = $_POST['clickthrough6'];
$date_from = $_POST['ref_date_from6'];
$date_to = $_POST['ref_date_to6'];
?>
<script src="../../../js/jquery-1.11.0.js"></script>
<script>
$(document).ready(function () {
$('.click7').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company7-'+companyId+' .clickthrough7').val(),
ref_date_from5: $('#company7-'+companyId+' .ref_date_from7').val(),
ref_date_to5: $('#company7-'+companyId+' .ref_date_to7').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
</script>
<div id="tabs2">
<div id="tabs-1" class="donut5">
<h4>Top 5 Referrers - Quotes <br /><small>Total number of Quotes between <?php echo date("d/m/Y", $date_from); ?> to <?php echo date("d/m/Y", $date_to); ?></small></h4>
<div class="statgrid">
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
<?php $quotes_q="SELECT
c.case_id,
co.name AS company_name,
co.company_id AS company_id,
COUNT(c.case_id) 'quote_count'
FROM
(`case` c,
`panel_company` pc,
`panel` p)
LEFT JOIN company co ON (co.company_id = pc.company_id)
WHERE pc.panel_id = " .$RegisteredUser['panel_id']. " AND
p.company_id = pc.company_id AND
c.panel_id = p.panel_id AND
c.insert_date > ".$date_from. " AND
c.insert_date < ".$date_to. "
GROUP BY p.panel_id
ORDER BY quote_count DESC, co.company_id
LIMIT 5";
$result=$mysqli->query($quotes_q); ?>
<div class="col-2-6">
<div id="morris-donut-chart6"></div>
</div>
</div>
<div class="statgrid">
<?php while ($row=$result->fetch_array()) { ?>
<div class="col-4-6">
<div id="company7-<?php echo $row['company_id'];?>">
<input type="hidden" class="ref_date_from7" value="<?php echo $date_from; ?>" />
<input type="hidden" class="ref_date_to7" value="<?php echo $date_to; ?>" />
<input type="hidden" class="clickthrough7" value="<?php echo $row['company_id'] ?>" />
<a><div id="<?php echo $row['company_id'];?>" class="click7 col-5-6"><?php echo $row['company_name']; ?></div></a>
<div class="col-1-6"><?php echo $row['quote_count']; ?></div>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
<?php
$quotes_q = "SELECT
c.case_id,
co.name AS company_name,
COUNT(c.case_id) 'quote_count'
FROM
(`case` c,
`panel_company` pc,
`panel` p)
LEFT JOIN company co ON (co.company_id = pc.company_id)
WHERE pc.panel_id = ".$RegisteredUser['panel_id']." AND
p.company_id = pc.company_id AND
c.panel_id = p.panel_id AND
c.insert_date > ".$date_from." AND
c.insert_date < ".$date_to."
GROUP BY p.panel_id
ORDER BY quote_count DESC, co.company_id
LIMIT 5";
$result = $mysqli->query($quotes_q);
?>
<script>
var donut_data6 = [
<?php while ($row = $result->fetch_array()) { ?>
{
label: '<?php echo substr($row['company_name'],0,15); ?>',
value: '<?php echo $row['quote_count']; ?>'
},
<?php } ?>
];
var donut6 = {
element: 'morris-donut-chart6',
data: donut_data6,
resize: false
}
donut6 = Morris.Donut(donut6)
</script>
EDIT2:
Not too sure if this makes a different but in Network tab I have 2 listings for jquery the initial one loaded from the header which loads 304 Not Modified and the 2nd one which loads on calling donut5.php which loads as 200 OK. Seems that after this I cannot request jquery again perhaps?
EDIT3: in donut1.php I have removed everything except for the jquery script request and the Hello World inside the div I am trying to retrieve. Network tab still shows that jquery is not loading. The strange thing is I have this exact setup, minus the charts, working on the same page (different div classes of course), and this does load jquery fine.
EDIT4: Substituted jQuery for JS as a test and not even basic stand alone JS will work, added in:
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
Nothing :( - Looping in JS world
EDIT5: Suppose <script> is a HTML tag so looping in them too.
EDIT6: When adding console.logo(data) to the function in list item 4 above I get back the following (obviously I have excluded a lot for testing:
<script src="../../../js/jquery-1.11.0.js"></script>
<script src="../../../js/jquery-ui.js"></script>
<!--
<script>
$(document).ready(function () {
$('.click7').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company7-'+companyId+' .clickthrough7').val(),
ref_date_from5: $('#company7-'+companyId+' .ref_date_from7').val(),
ref_date_to5: $('#company7-'+companyId+' .ref_date_to7').val()
},
function (data) {
$('.donut5').html(data);
});
});
});
</script>
-->
<div id="tabs2">
<div id="tabs-1" class="donut5">
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello JavaScript!";
</script>
<div id="divTest1"></div>
<script type="text/javascript">
$("#divTest1").text("Hello, world!");
</script>
</div>
</div>
EDIT7:
Placing code here to confirm if I have correctly inplemented KevinB's suggestion.
var
contentSelector = '.donut5',
$content = $(contentSelector),
contentNode = $content.get(0);
var documentHtml = function (html) {
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi, '</div>');
// Return
return $.trim(result);
};
$(document).ready(function () {
$('.click5').click(function () {
companyId = $(this).attr('id');
$.post('./ajax/donut5.php', {
clickthrough5: $('#company5-' + companyId + ' .clickthrough5').val(),
ref_date_from5: $('#company5-' + companyId + ' .ref_date_from5').val(),
ref_date_to5: $('#company5-' + companyId + ' .ref_date_to5').val()
},
function (data) {
var
$data = $(documentHtml(data)),
$dataBody = $data.find('.donut5'),
$dataContent = $dataBody.find(contentSelector),
$menuChildren, contentHtml, $scripts;
// Fetch the scripts
$scripts = $dataContent.find('.document-script');
if ($scripts.length) {
$scripts.detach();
}
// Fetch the content
contentHtml = $dataContent.html() || $data.html();
$scripts.each(function () {
var $script = $(this),
scriptText = $script.text(),
scriptNode = document.createElement('script');
if ($script.attr('src')) {
if (!$script[0].async) {
scriptNode.async = false;
}
scriptNode.src = $script.attr('src');
}
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
console.log(data);
});
});
});
EDIT8:
After trying the code above in EDIT7 the .donut5 in no longer being pulled from donut5.php to index.php which was originally working. I can see that jquery doesn't duplicate anymore on Network tab when clicking the link for donut5.php (even though the call to it is still there). Currently either I assume I have not mapped a div correctly above as I did remove part of the class find code for :first as I felt it was not required or somehow I have managed to make things worse!
When you pass an htmlstring to .html, one of two things happen. It either gets inserted using .innerHTML, or it gets inserted using .empty().append(htmlString). Which one is chosen is based on the complexity of the htmlstring passed in.
If it's relatively simple, .innerHTML will be used and scripts will execute in the way you expected.
However, if it is more complex, the elements are first parsed and appended to a docFragment before being appended to the document. This middle step is what causes your problem because the javascript will be executed before the elements are part of document.
The only way to fix this issue is to forcibly delay the execution of the javascript by either coding the javascript in such a way that it's execution is in a callback that later gets called, or by removing the javascript from the htmlstring before appending it and then executing it after.
Below is an example of the former:
(function divTestLooper () {
if (!$("#divTest1").length) {
// the element didn't exist, lets wait a little longer...
return setTimeout(divTestLooper, 10);
}
$("#divTest1").text("Hello, world!");
})();
Here is an example of the latter:
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L60-L70
and
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L123-L135
and
https://github.com/browserstate/ajaxify/blob/master/ajaxify-html5.js#L158-L167
Of course, the best solution is likely to avoid this problem entirely by not including javascript in your partials.
I want when the user click on submit button the content disappear (random text 3) until the user logs off. The JS works fine but, if I refresh the page, the content appears. Can anyone help me achieve this or can anyone convert my code to PHP so that I can use a session variable to achieve this?
<style type="text/css">
div.something{
/*random code;/*
}
</style>
<script type="text/javascript">
function hideSomething(){
document.getElementsByClassName("something")[2].style.display = "none";
}
</script>
<div class="something">random text 1</div>
<div class="something">random text 2</div>
<div class="something">random text 3</div><br />
<input type="submit" value="Disappear" onclick="hideSomething()" />
well the professional way is to record it on cookie or store in database with user information like IP or you can use rough way to just forward it to another page where that div not appear thou some dont allow cookies to store let me know which one you like and i will fill my answer with it sample
Use a cookie and store the status of the div there.
You can easily read and write a cookie using javascript.
A nice tutorial can be found here: http://www.w3schools.com/js/js_cookies.asp.
For example, in the hideSomething() function do the following:
document.cookie="display_div=true";
Then, when the page is loaded, call a javascript function that shows or hide the div based on the value of the cookie:
if(cookie_value == "true")
//Hide your div
else
//Show your div.
end
So first we create a form with a hidden text box, once user click on button Close Attendance the value of hidden textbox is submited and a session variable is created:
if(isset($_POST['hidden'])){
$_SESSION['closed'] = TRUE;
}
Then we check is session is set, if yes display attendance close, if not display content.
<?php if(isset($_SESSION['closed'])){
echo "attendance closed.";
}
else {
echo "<form name='test' action='attendance.php' method='post'>
<input type='hidden' name='hidden'/>
<button> Close Attendance </button>
</form>";
}
?>
try the following code, it should give you a very clear glimpse on how to do it.
<!DOCTYPE html>
<html>
<head>
<title>ZUUS: Ironman</title>
</head>
<script type="text/javascript">
function hideSomething()
{
document.cookie="hide_div=true";
myFunction();
}
function myFunction()
{
var cookie_value = getCookie("hide_div");
alert(cookie_value);
if(cookie_value == "true")
document.getElementById("test_div").style.display = "none";
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
</script>
<body onload="myFunction();">
<div id="test_div" style="background-color: blue;" onclick="hideSomething();">
this is a test
</div>
</body>
</html>
Alright, I'm working on a learning website and have come to a big obstacle I haven't been able to get over for the past few days, though trying to work through this got me through some other obstacles, I'm now stuck...
If anyone knows any tutorials or anything that would be extremely helpful, I'm finding it hard to find tutorials to help me out, I can find bits and pieces but nothing that has been able to help me figure out a solution.
What I want to happen:
When the person goes to the lesson page, it will pull 5 items from the question list and will present them to the person 1 at a time, when they press enter it takes them to the next item, when they've been through 5 items it will leave the page.
What does work:
pulling 5 question ID's using MySQL
What I'm needing:
Putting the 5 question ID's into javascript arrow
Load data into page based on first array number
Iterate through array loading data onto page without a total refresh
This is the lesson.php page I have so far, minus the few things I've tried which were just code snippets and such I found from stackoverflow that I tried to make work with my setup:
<!doctype html>
<?php
include ("Connections/localhost.php");
//Get up to five questions that user hasn't seen
$sql = "SELECT quest_id FROM questions LEFT OUTER JOIN answers ON questions.quest_id = answers.ans_question WHERE answers.ans_question IS null and questions.quest_level <= (SELECT user_level FROM users WHERE username = '".$_SESSION['username']."' LIMIT 5);";
$qresult = mysql_query($sql);
//Get number of lessons available
$result = mysql_query("SELECT COUNT(*) AS total FROM questions LEFT OUTER JOIN answers ON questions.quest_id = answers.ans_question WHERE answers.ans_question IS null and questions.quest_level <= (SELECT user_level FROM users WHERE username = '".$_SESSION['username']."');");
$les = mysql_fetch_assoc($result);
?>
<html>
<head>
<meta charset="utf-8">
<title>Lesson</title>
<script>
function play_audio() {
document.getElementById('id1').play();
}
var lessons = <?php echo $les['total']; ?>;
var i = 1;
if(lessons > 5) {
lessons = 5
}
function next_question() {
if(i<lessons) { //if there are still reviews to do
//call webpage to get new information
i++;
}
else {
//Load finished page
}
}
</script>
<link href="review.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="text_display">
<p><?php echo "Question Appears Here" ?></p>
</div>
<div id="looking">
What is the <?php echo "Meaning?" ?>
</div>
<div id="input_bar">
<form>
<input type="text" name="textfield" id="txt_input">
</form>
</div>
<div id="audio">
<form>
<input name="audio" type="button" id="btn_audio" value="Audio" onClick="play_audio()">
</form>
</div>
<div id="info">
<audio id="id1" src="audio/" style="display:none"></audio>
<h2>Information</h2>
<p></p>
</div>
</body>
</html>
I have a getitem.php page that will pull the selected question info from the database so that I can pull info from it and update the lesson page without having to reload it.
<?php
include ("Connections/localhost.php");
//Get item from url
$question = $_GET["ans_question"];
//Make sure to get UTF-8
$change = "SET NAMES 'utf8'";
mysql_query($change) or die("The change did not work: $change");
//Pull that question from the database
$sql = mysql_query("SELECT * FROM questions WHERE quest_id = '".$question."'");
$item= mysql_fetch_assoc($sql);
?>
<html>
<meta charset="utf-8">
<body>
<div id="text"><?php echo $item['quest_text']; ?></div>
<div id="type"><?php $qtype = $item['quest_type']; echo $qtype ?></div>
<div id="question"><?php echo $item['quest_question']; ?></div>
<div id="answer"><?php $ans = $item['quest_ans']; echo $ans?></div>
<div id="qaudio"><?php $qaudio = $item['quest_audio']; echo $qaudio?></div>
<div id="qinfomation"><?php echo $item['quest_info'];?></div>
</body>
</html>
It will do you a lot of good to use a framework like laravel to help you simplify things though if you are new to php and web development in general, it will make sense play around with core php propgramming and mysql queries. Laravel on the other is very easy to learn and simple to install. With that said you could also decide to return your resultset from mysql a json data to you webpage and using jquery to capture it.
What you should be looking at is how to build Ajax application and for this i highly recommend using Jquery library.
<?php
echo '
<script type="text/javascript">
$(function() {
var refresh = setInterval(function() {
$("#content").html("'.rand().'");
}, 3000);
});
</script>
<div id="content"></div>
';
?>
This will update the div "content" with a random number after 3 seconds, however it only updates once. Why does it not continually generate a new number every three seconds, and how can I make it do precisely that?
Thank you in advance for any assistance rendered.
Ha. PHP is run on the SERVER side. JS is on the client.
you need to generate the rand on the JS side not he php side...
js code:
<script type="text/javascript">
$(function() {
var refresh = setInterval(function() {
var randomnumber = Math.floor(Math.random()*11);
//where 11 dictates that the random number will fall between 0-10
$("#content").html(randomnumber);
}, 3000);
});
</script>
<div id="content"></div>