Get all data from mysql display in div php javascript - javascript

Hello my problem is simple , i have a table news , i have a button bt1 , and a div to show the results , i want to display all rows from table when i click the button,i only get the first row , how can i display all results ?
<script>
function shownews(id) { <? php
include('db.php');
$query = mysql_query("SELECT * FROM news");
while ($row = mysql_fetch_array($query)) {
$a = $row['news_title'];
} ?>
var ab = <? php echo json_encode($a); ?> ;
id.innerHTML = ab;
}
</script>
<div id="results"></div>
<button id="btn1" onclick="shownews(results)">See news</button>

try
$a = array();
while ($row = mysql_fetch_array($query)) {
$a[] = $row['news_title'];
} ?>
// print array
print_r($a);

Your echo json_encode($a); is not in your while loop, so you only render 1 line.
Also if i understand what you're doing, you want your PHP to be executed only when you trigger your button click ? This is not the way to do it... php is a server language where javascript is executed only by your browser.
I didn't
Try this :
<script type="text/javascript">
function shownews(id) {
document.getElementById(id).innerHTML = document.getElementById('news').innerHTML ;
}
</script>
<div id="news" style="display:none ;">
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
echo $row['news_title'] . '<br />' ;
}
?>
</div>
<div id="results"></div>
<button id="btn1" onclick="shownews('results')">See news</button>

You are overwriting $a, hence you will only get the last row.
Change
while($row=mysql_fetch_array($query)){
$a=$row['news_title'];
}
to
$a = array();
while($row=mysql_fetch_array($query)){
array_push($a, $row['news_title']);
}
Edit: Royal_bg is correct - extra info:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function. http://us2.php.net/array_push

You execute all the while before writing anything. Try to change the closing bracket after writing the answer...
<script>
function shownews(id){
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
$a=$row['news_title'];
?>
var ab = <?php echo $a; ?>;
id.innerHTML += ab;
<?php
}
?>
}
</script>
<div id="results"></div>
<button id="btn1" onclick="shownews(results)">See news</button>

function shownews(id){
<?php
include ('db.php');
$query=mysql_query("SELECT * FROM news");
while($row=mysql_fetch_array($query)){
$a[]=$row['news_title'];
}
?>
id.innerHTML=<?php echo json_encode($a); ?>;
}

Related

Using variable on php to create another variable in JS

I'm having a hard time getting the value of a specific variable in php to use in js. This is my code in php:
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
}
?>
I want to get the value of this ($result['status']) and pass it on the variable pos in js. This is my js code:
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
var pos = $('PHP VARIABLE HERE').val();
alert(pos);
}
Thanks for your help.
The easiest way is to output it to javascript directly:
?>
<script type="text/javascript">
window.MY_PHP_VAR = <?php echo json_encode($myPhpVar); ?>;
</script>
...
window.MY_PHP_VAR now contains your php variable
if your javascript code is on same page where the result is comming then you can use this
var pos = `<?php echo $result['status'] ?>`;
var pos = `<?= $result['status'] ?>`;
===============
// refresh.php
===============
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
echo "<script> alert('". $result['status'] ."'); </script>";
/* If the $result['status'] is 'success' the above line will be converted to:
echo "<script> alert('success'); </script>";
*/
}
?>
so, every time the refresh.php loads, the script is going to get executed.
However, I suggest you to assign a id or class attribute to your h4 where you are echoing your status and access the value using the selectors in the javascript.
you could try giving an id or class to the status.
then in JavaScript you could then get the value of the id or class.
PHP
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<h4> <span class="status">' . $result['status'] . '</span></h4>';
}
?>
JavaScript
var oldStatus = '';
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
// note that since we used a class, you will get the value of the first element only.
var pos = $('.status').text(); // use .text() instead of .val()
if (pos.toLowerCase() == 'out' && pos != oldStatus){
oldStatus = pos;
alert(pos);
}
}

Output value in javascript from php loop

I'm not sure how to search this, but I have an array in php numbered 1 to 20. I have a foreach loop to output the values and have the user be able to click on the numbers. After clicking the number, the page would then output the number clicked.
HTML:
<div id="chapters" onclick="getChapter()">
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" id="currChapter">Chapter <?php echo $chapter;?></p>
<?php
}
?>
</div>
Javascript
function getChapter() {
chapter = document.getElementById("currChapter").id;
document.write(chapter);
}
I'm not able to output the number that the user clicks on.
I have tried putting
id=<?php $chapter?>
, but that does not work as well as replacing id with value and name.
I would recommend passing the $chapter as parameter of a function "Onclick" event :
<div id="chapters">
<?php
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" onClick="getChapter(<?php echo $chapter;?>)">Chapter <?php echo $chapter;?></p>
<?php
}
?>
and the Javascript:
function getChapter(chapterNumber) {
alert(chapterNumber);
}
I don't really understand what you want to do, seems you explanation just a example, but may be this will help. You can call function getChapter with parameter ( onClick="getChapter(<?php echo $chapter;?>) ) :
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" id="currChapter" onClick="getChapter(<?php echo $chapter;?>)">Chapter <?php echo $chapter;?></p>
<?php
}
function getChapter(chapter) {
document.write(chapter);
}

Javascript could not change data in HTML tag ( Using PHP via AJAX )

I'm making a quiz website, for that questions and answers will be fetched from database and using PHP and MySQL.
I've stored the options in one single column using JSON.(Stored as string array) Question is displaying correctly but options couldn't; I've written them in similar manner.
quiz.php
echo '
<div id="ques_block">
<br>
<p id="ques"></p>
';
for($i=0; $i<$_SESSION["opt_size"]; $i++)
echo '<p class="opt" id="opt'.$i.'"></p>';
echo '
<div id="nav-for"><img src="next.png" alt="Next =>"></div>
</div>
';
next.php will be called using AJAX when NEXT is clicked.
next.php
$sql = "SELECT QUESTION, ANSWER, OPTIONS FROM user_quiz WHERE CUST_NO=$cust_no AND QUES_NO=$new_ques_no;";
$res = mysqli_query($conn, $sql) or die("bad Query: $sql");
if(mysqli_num_rows($res)==0)
echo "END";
else
{
$row = mysqli_fetch_assoc($res);
$ques = $row["QUESTION"];
$opts = $row["OPTIONS"];
$opt = json_decode($opts);
$resRows = sizeof($opt);
echo '
<script type="text/javascript">
document.getElementById("ques").innerHTML="'.$ques.'";
</script>
';
for($i=0; $i<$resRows; $i++)
echo '<script type="text/javascript">
document.getElementById("opt'.$i.'").innerHTML = "'.$opt[$i].'";
</script>
';
}
Edited:
#ADyson I'll try your method, Thanks,
BTW This is AJAX code as requested:
$(document).ready(function(){
$("#nav-for").click(function(){
$.post("nextQues.php",
{custNo: $("#custNo").val(), quesNo: $("#quesNo").val()},
function(data){
$("#ques").html(data);
}
);
});
});

Change the value of external Javascript with PHP in foreach loop

How can I change the value of a js variable in a PHP foreach loop?
The js needs to be external.
This is a piece of the index.php here I want to get the output $prozent in the javascript, I don't know how to get a PHP variable to execute a js every time in a loop, the js is a chart. I get the chart in the loop in the echo'<div class="chart-wrapper"> with a this chart js.
<?php
$sql = //SQL query
$res = mysql_query($sql);
$i = 0;
$survey = array();
while ($row = mysql_fetch_assoc($res)) {
$survey[$i]['label'] = $row['Label'];
$i++;
}
foreach ($survey as $survey) {
echo '<div class="col-md-4">';
echo '<div class="front face">';
echo "<h3> ".$survey['label']."<br>";
$sql = //SQL Query
$res = mysql_query($sql) ;
$sql = //SQL Query
$resSum = mysql_query($sql) ;
while ($row = mysql_fetch_array($resSum)) {
$survey['ausgabe'] = $row['sum(a.answer)'];
}
$anzahlreihen = mysql_num_rows($res);
if ($anzahlreihen > 0) {
$prozent = $anzahlreihen * $survey['ausgabe'];
//bunch of ifelse statements
//This is the variable i want to get in the js
echo (round( $prozent, 2));
echo '</font>';
}
}
echo '</div>';
echo '<div class="back face center">';
echo'<div class="chart-wrapper">
}
There are two ways PHP and Javascript can interact.
Use AJAX to request a PHP script which returns JSON or have PHP output the following example HTML;
<script type="text/javascript">
var variable = value;
</script>

php code to get count from multiselect listbox and store in database

Below is my textbox values....i am unable to put my screen shots here..
i used multiple input tag jquery from this site..
http://loopj.com/jquery-tokeninput/demo.html
and second option of this demo. plz visit demo link ...
but i used multiple input textbox..in which we select multiple tags in one textbox okay.
like 700X 701X 702X
I need to get this textbox value and store in 3 rows..
FOR EX - in above screenshot there are 3 values 700,701,702 ok...now i need to ask you...when i click save i need to store this values in 3 different rows...
Rows No - used_receipt
1 700
2 701
3 702
i try like below but wont work...
textbox code
<input id="demo-input-local" type="text" value="<?php echo $data['used_receipt'];?>" name="used_receipt" />
javascript
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-local").tokenInput([
<?php
$receipt = $database->getRows("SELECT DISTINCT SM.receipt_no FROM scheme_master SM Inner join book_issue BI ON BI.book_no = SM.Book_no2 where SM.receipt_no not in (select used_receipt from book_return)");
foreach($receipt as $row){ ?>
{name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
]);
});
</script>
php code to insert multiple values in database
$used_receipt = $_POST['used_receipt'];
$arr = explode(",", $used_receipt);
$max = count($arr);
for ($i = 0; $i < $max; $i++)
{
$insertrow = $database->insertRow("INSERT INTO book_return (book,surveyor,used_receipt,city,return_date,created)
VALUES (:book,:surveyor,:used_receipt,:city,:return_date,:created)",
array(':used_receipt'=>$arr[$i]);
}
Instead of
foreach($receipt as $row){ ?>
{name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
Try this
$r = array();$i=1;
foreach($receipt as $row){
$r[]['name'] = $row['receipt_no'];$r[]['id'] = $i++;
}
echo "JSON.parse(\"".json_encode($t)."\")";
below is script which i used
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-local").tokenInput([<?php
$receipt = $database->getRows("SELECT DISTINCT SM.receipt_no FROM scheme_master SM Inner join book_issue BI ON BI.book_no = SM.Book_no2");
foreach($receipt as $row){ ?>
{id:<?php echo $row['receipt_no']; ?>,name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
]);
});
</script>
and get this input in like
$used_receipt = $_POST['used_receipt'];
$arr = explode(",", rtrim($used_receipt));

Categories