slide show using javascript using php variable - javascript

I am trying to get member photos from my sql and show as a slide. i am trying this with DHTML slideshow script- © Dynamic Drive DHTML code library (www.dynamicdrive.com) check the basic code here basic code
now i change the code to get the image url from mysql using php
my code :
Here is the html and script code.
<html>
<head>
<script type="text/javascript">
/***********************************************
* DHTML slideshow script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice must stay intact for legal use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
var photos = new Array()
<?php
$mid=$_POST['mid'];
//echo $mid;
$mid=$_POST['mid'];
require_once("datacon.php");
$result = $data->query("SELECT * FROM tempregist where id= $mid ");
$row = mysqli_fetch_array($result) or die(mysqli_error());
$folde= "uploads/thumb/";
$folder=utf8_encode($folde);
//echo $folder;
$mid1 =$row['mid'];
require_once("datacon.php");
$result = $data->query("SELECT image_name FROM tbl_images where mid= '$mid1' ");
$phparray = array();
$count = mysqli_num_rows($result);
if($count>=1)
{
while($crow = mysqli_fetch_array($result))
{
$i=0;
$phparray[$i] = $folder. $crow['image_name'];
$i++;
?>
photos<?php echo"[".$i."]" ;?> = <?php echo '"'. implode( $phparray) . '"'."\n" ;
} }
?>
var photoslink = new array
var x
x =<?php echo json_encode($count) ?>;
var which=0
/
//Specify whether images should be linked or not (1=linked)
var linkornot=0
Set corresponding URLs for above images. Define ONLY if variable linkornot equals "1"
photoslink[0]=""
photoslink[1]=""
photoslink[2]=""
//do NOT edit pass this line
var preloadedimages=new Array()
for (i=0;i<photos.length;i++){
preloadedimages[i]=new Image()
preloadedimages[i].src=photos[i]
}
function applyeffect(){
if (document.all && photoslider.filters){
photoslider.filters.revealTrans.Transition=Math.floor(Math.random()*23)
photoslider.filters.revealTrans.stop()
photoslider.filters.revealTrans.apply()
}
}
function playeffect(){
if (document.all && photoslider.filters)
photoslider.filters.revealTrans.play()
}
function keeptrack(){
window.status="Image "+(which+1)+" of "+photos.length
}
function backward(){
if (which>0){
which--
applyeffect()
document.images.photoslider.src=photos[which]
playeffect()
keeptrack()
}
}
function forward(){
if (which<photos.length-1){
which++
applyeffect()
document.images.photoslider.src=photos[which]
playeffect()
keeptrack()
}
}
function transport(){
window.location=photoslink[which]
}
</script>
</head>
<body>
<div align="center">
<img src="images/logo.jpg" border = "2" align="center" alt="no logo">
</div>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100%" colspan="2" height="22"><center>
<script>
if (linkornot==1)
document.write('<a href="javascript:transport()">')
document.write('<img src="'+photos[0]+'" name="photoslider" style="filter:revealTrans(duration=2,transition=23)" border=0>')
if (linkornot==1)
document.write('</a>')
</script>
</center></td>
</tr>
<tr>
<td width="50%" height="21"><p align="left">Previous Slide</td>
<td width="50%" height="21"><p align="right">Next Slide</td>
</tr>
</table>
<p align="center"><font face="Arial" size="-2">Free DHTML scripts provided by<br>
Dynamic Drive</font></p>
</body>
</html>
Now i am getting out put as follows
var photos = new Array()
photos[0] = "uploads/thumb/220816_1412135472.jpeg"
photos[0] = "uploads/thumb/312840_1412135511.jpeg"
photos[0] = "uploads/thumb/589453_1412135511.jpeg"
photos[0] = "uploads/thumb/467341_1412135630.jpeg"
photos[0] = "uploads/thumb/800658_1412135790.jpeg"
photos[0] = "uploads/thumb/366793_1412135826.jpeg"
But i need the out put like this
photos[0] = "uploads/thumb/220816_1412135472.jpeg"
photos[1] = "uploads/thumb/312840_1412135511.jpeg"
photos[2] = "uploads/thumb/589453_1412135511.jpeg"
photos[3] = "uploads/thumb/467341_1412135630.jpeg"
photos[4] = "uploads/thumb/800658_1412135790.jpeg"
photos[5] = "uploads/thumb/366793_1412135826.jpeg"
i tried so much. please any one help.

while($crow = mysqli_fetch_array($result))
{
$i=0;
You're resetting $i in your loop

$result = $data->query("SELECT image_name FROM tbl_images where mid= '$mid1' ");
{
$count = mysqli_num_rows($result);
if($count>=1)
{
$i=0;
while($crow = mysqli_fetch_array($result))
{
$phparray[$i] = $folder. $crow['image_name'];
echo $i. "\n";
$i++;
}
}
use $i=0 initialization outside while

finally i found it with help of Hammerstein and Dhanush Bala. i mingled two persons suggestion i got it here is the answer
$phparray = array();
$count = mysqli_num_rows($result);
if($count>=1)
{
$b=0;
while($crow = mysqli_fetch_array($result))
{
$i=0;
$phparray[$i] = $folder. $crow['image_name'];
$i++;
$b++;
?>
photos<?php echo"[".$b."]" ;?> = <?php echo '"'. implode( $phparray) . '"'."\n" ;
} }
now the out put is:
photos[1] = "uploads/thumb/220816_1412135472.jpeg"
photos[2] = "uploads/thumb/312840_1412135511.jpeg"
photos[3] = "uploads/thumb/589453_1412135511.jpeg"
photos[4] = "uploads/thumb/467341_1412135630.jpeg"
photos[5] = "uploads/thumb/800658_1412135790.jpeg"
photos[6] = "uploads/thumb/366793_1412135826.jpeg"
thanks Hammerstein and Dhanush Bala

Related

Live data search using ajax. How to display another query when input is empty [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I am trying to create a live search using ajax, jquery, php and mysql.
The user enter some inputs, it send the search to form_livesearch.php. I got that part worked. Else if the input is empty, then display other query. (I need help with this part)
<div id="container" class="col-md-12">
<div class="row">
<h2>Quick Search</h2>
<input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="" id="searchresult">
</h2>
</div>
</div>
$(document).ready(function(){
$("#live_search").keyup(function(){
var input = $(this).val();
if(input != ""){
$.ajax({
url:"form_livesearch.php",
method:"POST",
data:{input:input},
success:function(data){
$("#searchresult").html(data);
$("#searchresult").css("display","block");
}
});
} else {
// If the input field is empty
// How display another php query here?
}
});
});
Here is the php and mysql I am trying to display when the input field is empty.
<?php
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
$result = mysqli_query($db,$query);
if(!$result){
die("Query Failed " . mysqli_error($db));
}
if(mysqli_num_rows($result) > 0){
?>
<h3>Policies</h3>
<ul>
<?php
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
?>
<li><?php echo $s_name?> <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>
<?php
}
?>
</ul>
<?php
}
?>
form_livesearch.php:
if(isset($_POST['input'])){
$input = $_POST['input'];
//to prevent from mysqli injection
// x'='x
$input = stripcslashes($input);
$input = mysqli_real_escape_string($db, $input);
$input = str_replace('%', ' #', $input);
$input = str_replace("'", ' #', $input);
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE '%{$input}%' ORDER BY id ASC";
$result = mysqli_query($db,$query);
if(mysqli_num_rows($result) > 0){?>
<table class="table table-bordered table-striped mt-4">
<!--
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
-->
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
?>
<tr>
<td style="font-size: 14px;"><?php echo $s_name;?> <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}else{
echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}
}
?>
You should handle this stuff in the PHP file. and by the way, the input can not be empty as you put the ajax in keyup event.
it just happened when the user use the backspace to delete what he search.
So the form_livesearch.php PHP file should be something like this.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$output = "";
if(isset($_POST['input'])){
$input = $_POST['input'];
if(!empty($input)){
$input = str_replace('%', ' #', $input);
$input = str_replace("'", ' #', $input);
$input = "%$input%"; // prepare the $input variable
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE ? ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $input); // here we can use only a variable
$stmt->execute();
}else{
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->execute();
}
$result = $stmt->get_result(); // get the mysqli result
if($result->num_rows > 0){
if(empty($input))
$output = '<table class="table table-bordered table-striped mt-4"><tbody>';
else
$output = '<h3>Policies</h3><ul>';
while($row = $result->fetch_assoc()){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
if(empty($input))
$output .= '
<tr>
<td style="font-size: 14px;">' . $s_name .' <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
</tr>';
else
$output .= '<li>' . $s_name . ' <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>';
}
if(empty($input))
$output .= '</tbody></table>';
else
$output .= '</ul>';
echo $output;
}else{
echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}
}
?>
You can use a separate file to handle 2 types but as they are all about products it's better to have one file.
It's a good practice to return the data and let the frontend build the HTML output but if you want to build HTML in the PHP file, it's better to wrap them in a string.
Also, use the prepare statement of MySQLi to prevent SQL injection. take a look at this example for more information.
And the html file should be something like this:
<div id="container" class="col-md-12">
<div class="row">
<h2>Quick Search</h2>
<input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="" id="searchresult">
</h2>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// will execute once the page load
getData();
$("#live_search").keyup(function(){
let input = $(this).val();
getData(input);
});
});
function getData(input = ''){
$.ajax({
url:"form_livesearch.php",
method:"POST",
data:{input:input},
success:function(data){
$("#searchresult").html(data);
$("#searchresult").css("display","block");
}
});
}
</script>

Google Charts Dynamic Arrays PHP Without SQL

I'm asking this question because all the answers I could find for similar problems were using MySQL whereas I'm not, just a JSON API to get the data, which I then put into arrays that I want to display as a Google graph. All I know is that I have to somehow format the arrays properly in order to get them to display but I have no idea how to do it in my case. I would just like to have a simple pie chart, based on the arrays below. So far I'm getting a blank space on the site. I tried something with Json_encode before but it didn't work so I decided to leave it as it is and come here instead. Here are the arrays after I do print_r:
Array 'name'-
Array ( [0] => Facebook Inc [1] => Alphabet Class A [2] => Apple Inc [3] => Ford Motor Company [4] => Adv Micro Devices [5] => Morgan Stanley [6] => Berkshire Hath Hld B [7] => JP Morgan Chase & Co )
Array 'sumOf'-
Array ( [0] => 5811.63 [1] => 116135.97 [2] => 1564.1 [3] => 1053 [4] => 113.1 [5] => 521.4 [6] => 1960.2 [7] => 1100.4 )
Code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable($name, $sumOf);
var options = {
title: 'Portfolio Allocation'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
How arrays are made:
$name = [];
$lastprice = [];
$y = 0;
$z = '';
$key = "";
// Retreiving information from database
$memberid = $_SESSION['memberID'];
$sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
$result = mysqli_query($conn, $sql);
// Check if databse is empty
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$sym[$y] = $row["stocks_symbol"];
$pri[$y] = $row["price"];
$vol[$y] = $row["quantity"];
$id[$y] = $row["memberid"];
$y += 1;
}
}
// If database empty
else
{
echo "Portfolio Empty";
die();
}
mysqli_close($conn);
// Adding all stock names in one variable to enable API call
for($a=0;$a<$y;$a++)
{
$z = $z.$sym[$a].',';
}
$z = rtrim($z,",");
// API call
$contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
$contents = json_decode($contents, true);
// Check successfull API call
if($contents["status"]["code"] == 200)
{
foreach($contents['results'] as $result)
{
array_push($name,$result['name']);
array_push($lastprice,$result['lastPrice']);
}
}
// If API call unsuccessful
else
{
echo "Error retreiving data. Please try again later.";
die();
}
?>
<!-- Generating Output in tabular format -->
<table id= test class='table table-responsive'>
<tr class='head warning'>
<th>Name</th>
<th>Last Price</th>
<th>Price Bought</th>
<th>Quantity</th>
<th>Change Per Stock</th>
<th>Profit/Loss</th>
<th>Market Value</th>
<th>Amount Invested</th>
</tr>
<?php
$profitOrLossSum = 0;
$dividendRateSum = 0;
$startEqSum = 0;
$sumOf = array();
for($x=0;$x<$y;$x++)
{?>
<tr>
<td class="input"><?php echo $name[$x]; ?></td>
<td class="input"><?php echo $lastprice[$x]; ?></td>
<td class="input"><?php echo $pri[$x]; ?></td>
<td class="input"><?php echo $vol[$x]; ?></td>
<td class="input"><?php
if($pri[$x] > $lastprice[$x])
{
echo $lastprice[$x]-$pri[$x];
}
else if($pri[$x] < $lastprice[$x])
{
echo $lastprice[$x]-$pri[$x];
}
else
echo '0';
?></td>
<td class="input"><?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
$profitOrLossSum += $profitOrLoss;
echo $profitOrLoss;
?></td>
<td><?php
$firstno1 = floatval($vol[$x]);
$secondno1 = floatval($lastprice[$x]);
$sumOf[] = $firstno1 * $secondno1;
$sum1 = $firstno1 * $secondno1;
print ($sum1);
?></td>
<td class="input">
<?php
$starteq = $pri[$x] * $vol[$x];
$startEqSum += $starteq;
echo $starteq;
?>
</td>
</tr>
<?php
}
$arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
$arr1 = array('startEqSum' => $startEqSum);
print_r ($name);
print_r ($sumOf);
echo json_encode($name);
echo json_encode($sumOf);
?>
Here is the working Example of your code you were very close though. Actually, you have to pass only one single parameter as a multidimensional array to arrayToDataTable(); you have to json_encode and JSON_parse your array as well
check https://developers.google.com/chart/interactive/docs/gallery/piechart
No worries its working copy and paste it and you are good to go.
<?php
$name = ['Facebook Inc', 'Alphabet Class A', 'Apple Inc', 'Ford Motor Company', 'Adv Micro Devices', 'Morgan Stanley', 'Berkshire Hath Hld B', 'P Morgan Chase & Co'];
$sumOf = [5811.63, 116135.97, 1564.1, 1053, 113.1, 521.4, 1960.2, 1100.4];
?>
<html>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
var name = <?= json_encode($name) ?>;
var sumOf = <?= json_encode($sumOf) ?>;
var array = name.split(",");
newArr = [['Name', 'Amount']];
array.forEach(function (v, i) {
newArr.push([v, sumOf[i]]);
});
function drawChart() {
var data = google.visualization.arrayToDataTable(newArr);
var options = {
title: 'Portfolio Allocation'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
array_combine was needed to join the two arrays together and then inside of
'function drawChart' a simple foreach loop was required, like this:
<?php
foreach ($array as $name => $allocation):
echo "['$name', $allocation]";
echo ($allocation != end($array)) ? ',' : '';
endforeach;
?>

simplePagination.js not working for php MySQL database search

Used a form to create a php search for a MySQL database in a header.php file.
Attempting to use simplePagination.js with php. I am able to correctly calculate the number of results and display the appropriate amount of page links. However, search.php is not limiting the number of items on the page, and all of the pagination links lead to a blank page.
<form action="search.php" method="POST">
<input type="text" name="search" placeholder="search site">
<button type="submit" name="submit-search"><img src="../assets/search icon-05.png"></button>
</form>
search.php code:
<?php
include 'header.php';
?>
<section class="searchPage">
<div class="searchResults">
<?php
if (isset($_POST['submit-search'])){
$searchTerm = trim( (string) $_POST['search'] );
if (isset( $searchTerm[0] )) {
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
$limit = 10;
$numberOfPages = ceil($queryResult/$limit);
if ($queryResult > 0){
echo $queryResult . " results found";
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='articleItem'>
<h2>".$row['title']."</h2>
<p>".$row['abstract']."</p>
<a href=".$row['link']." target='_blank'>".$row['link']."</a>
</div>";
}
$pageLinks = "<nav><ul class='pagination'>";
for ($i=1; $i<=$numberOfPages; $i++) {
$pageLinks .= "<li><a href='search.php?page=".$i."'>".$i."</a></li>";
};
echo $pageLinks . "</ul></nav>";
}
else {
echo "There are no results matching your search.";
}
}
}
?>
</div>
</section>
<script type="text/javascript">
$(document).ready(function(){
$('.pagination').pagination({
items: <?php echo $queryResult;?>,
itemsOnPage: <?php echo $limit;?>,
currentPage : <?php echo $page;?>,
hrefTextPrefix : 'search.php?page='
});
});
</script>
You don't need to create the page links on your own, because this is what the plugin does through JavaScript events. So you can replace the ul with a div element. This is the reason why you get a blank page.
echo "<nav><div class='pagination'></div></nav>";
In the following is what I added to make it work:
$(document).ready(function(){
var pageParts = $(".articleItem");
pageParts.slice(<?php echo $limit;?>).hide();
$('.pagination').pagination({
items: <?php echo $queryResult;?>,
itemsOnPage: <?php echo $limit;?>,
onPageClick: function(pageNum) {
var start = <?php echo $limit;?> * (pageNum - 1);
var end = start + <?php echo $limit;?>;
pageParts.hide().slice(start, end).show();
}
});
});

How to Pass every Php value to javascript URL (only showing 1 same row record)

Need help on below coding.
However I got few running no, when I press edit button it only show running no '1', other running no like 2 or 3 also showing running no 1 when i press edit on the row 2 and row 3.
I got a problem in index.php file:
<html>
<?php
$rb = $connect->Execute("SELECT * FROM IT_Dept.dbo.testingHeader A LEFT JOIN IT_Dept.dbo.testingDetail B
ON A.invoiceno=B.invoiceno_dt
WHERE A.invoiceno = '".$search."'");
}
$invoiceno = $rb->Fields("invoiceno");
$company = $rb->Fields("company");
$custname = $rb->Fields("custname");
$newadd=str_replace("<br />","\n",$custadd);
//table details
?>
<body>
<?php
echo "<form id= 'form2' method='post'><table id='tabledesc' border=1>
<tr>
<th>Description </th>
<th>Qty</th>
<th >Unit Price(Before GST)</th>
<th>Total(Before GST)</th>
<th >*Total GST</th>
<th >Amount(RM)</th>
<th >Tax input/output</th>
<th >Debit Acc</th>
</tr>";
while(!$rb->EOF) {
$description = $rb->Fields("description");
$invoiceno_dt = $rb->Fields("invoiceno_dt");
$runningno = $rb->Fields("runningno");
$qty = $rb->Fields("qty");
$unitprice = $rb->Fields("unitprice");
$totalb4gst = $rb->Fields("totalb4gst");
$gst = $rb->Fields("gst");
$amount = $rb->Fields("amount");
>Fields("creditacc");
$description = $description->value;
$invoiceno_dt = $invoiceno_dt->value;
$runningno = $runningno->value;
$qty = $qty->value;
$unitprice = $unitprice->value;
$totalb4gst = $totalb4gst->value;
$gst = $gst->value;
$amount = $amount->value;
echo "<tr><td>".$description."</td>";
echo "<td>".$qty."</td>";
echo "<td>".$unitprice."</td>";
echo "<td>".$totalb4gst."</td>";
echo "<td>".$gst."</td>";
echo "<td>".$amount."</td>";
echo "<input type='hidden' name = 'runningno' id='runningno' value = ' $runningno ' >";
echo "<td><button onclick='openedit()'>Edit</button></td>";
invoiceno_dt=".$invoiceno_dt."&runningno=".$runningno."'>Edit</a></td>";
invoiceno_dt=".$invoiceno_dt."&runningno=".$runningno."'>x</a></td><tr>";
echo "<td><button onclick='opendelete()'>Delete</button></td>";
$rb->MoveNext();
}
?>
</table></form></body>
<script type="text/javascript">
var popup;
function openedit() {
var myinvoice = document.getElementById("invoiceno").value;
var no = <?php echo $runningno; ?>;
alert(no);
popup = window.open("edit.php?invoiceno="+myinvoice+'&runningno='+no, "Popup", "width=500,height=600");
popup.focus();
}
popup.focus();
}
</script>
<?php
$rb->close;
$connect->close;
?>
You could add the running number to the page for example by doing this:
<script type="text/javascript">
var no = <?php echo $runningNo; ?>;
</script>
Try this.
echo "<td><button onclick=\"openedit('{$runningno}')\">Edit</button></td>";
Apart from that, you better to remove the spaces in value attribute in input field.
echo "<input type='hidden' name='runningno' id='runningno' value ='$runningno' />";
Use as suggested for template files
<html>
<!-- HTML code is here -->
<input type='hidden' name = 'runningno' id='runningno' value = '<?php print $runningno; ?>'></input>
<!-- Some other html -->
<?php
//your php code here
?>
<!-- HTML again -->
</html>
Same for js inside html
<script type="text/javascript">
var testJsValue = "<?php print $ValueFromPHP; ?>";
</script>
Try this
echo '<td><button onclick="openedit(\''.$runningno.'\')">Edit</button></td>';
I think this code will be work properly.

PHP code not executing when javascript comes between

Here is the situation... Two results are created in the php page.. The results are echoed as json_encode . The results are showing perfectly. But when i insert a javascript code within two php code blocks, then one result is shown while the other is not.. I really have no idea why this is happening.. My code
$action = isset($_GET['action']);
if($action == "get_requests"){
include("../connect.php");
$sql_song_req = "SELECT COUNT(*) FROM `song_requests`";
$sql_select_song = "SELECT * FROM `song_requests` ORDER BY id ASC";
$sql_count = $rad->prepare($sql_song_req);
$sql_count->execute();
$count = $sql_count->fetchColumn();
$select_song_prep = $rad->prepare($sql_select_song);
$select_song_prep->execute();
while($row = $select_song_prep->fetch(PDO::FETCH_ASSOC)){
$id = $row['id'];
$name = $row['name'];
$song = $row['songname'];
$dedicatedto = $row['dedicatedto'];
?>
<script>
function delete_req(id){
alert("hello");
}
</script>
<?php
$data .= ' <tr cellpadding="5" cellspacing="6" align="center" width="60%">
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>'.$song.'</td>
<td>'.$dedicatedto.'</td>
<td>Delete</td>
</tr>';
}
$display = ' <table "cellspacing="4" align="center">
<tr>
<th>ID</th>
<th>Name</th>
<th>Song</th>
<th>Dedicated to</th>
<th>Delete</th>
'.$data.'
</tr>
</table>';
$response = array();
$response['data_from_db'] = $display;
$response['count'] = $count;
echo json_encode($response);
}
Here the response['count'] is showing on my php page but not $response['data_from_db'].
And when I delete the javascript code then both of them are showing.. Help needed.
I should mention that am using NGINX and php5-fpm
You have a brace mismatch.
Add a brace } after $dedicatedto = $row['dedicatedto']; Your while loop wasn't properly closed.
$action = isset($_GET['action']);
if($action == "get_requests"){
include("../connect.php");
$sql_song_req = "SELECT COUNT(*) FROM `song_requests`";
$sql_select_song = "SELECT * FROM `song_requests` ORDER BY id ASC";
$sql_count = $rad->prepare($sql_song_req);
$sql_count->execute();
$count = $sql_count->fetchColumn();
$select_song_prep = $rad->prepare($sql_select_song);
$select_song_prep->execute();
while($row = $select_song_prep->fetch(PDO::FETCH_ASSOC)){
$id = $row['id'];
$name = $row['name'];
$song = $row['songname'];
$dedicatedto = $row['dedicatedto'];
} // <- added. Brace for while loop
?>
<script>
function delete_req(id){
alert("hello");
}
</script>
<?php
$data .= ' <tr cellpadding="5" cellspacing="6" align="center" width="60%">
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>'.$song.'</td>
<td>'.$dedicatedto.'</td>
<td>Delete</td>
</tr>';
$display = ' <table "cellspacing="4" align="center">
<tr>
<th>ID</th>
<th>Name</th>
<th>Song</th>
<th>Dedicated to</th>
<th>Delete</th>
'.$data.'
</tr>
</table>';
$response = array();
$response['data_from_db'] = $display;
$response['count'] = $count;
echo json_encode($response);
}

Categories

Resources