I've echoed the following php and it shows up properly in HTML so that can't be a problem:
PHP
if (mysqli_num_rows($result) > 0) {
//create the drop down menu
$list ="";
while($row = mysqli_fetch_assoc($result)) {
$list = '<div class="dropOption">'.$row["item"].'</div>';
}
This outputs three rows - apple, pear, strawberry - in the right div format.
And when I put the following php script into the jquery function below, the menu does contain the value strawberry (the last), however the first two are missing.
JavaScript
//drop down menu
$(document).ready(function(){
function createDropdown(){
var drop = $('#customDropdown');
var i;
var htmlString = '<div id="dropContainer">';
htmlString += '<?php echo $list;?>';
htmlString += '</div>';
drop.append(htmlString);
}
createDropdown();
I'm new to jquery and php so forgive me if the error is simple; however I'm pretty sure it's right, functionally speaking, because I'm getting something; so I figured the syntax must get be wrong somewhere. Can anybody help? Thanks in advance.
In your php it should be
$list .= '<div class="dropOption">'.$row["item"].'</div>';
and then output just like this <?=$list;?> in your js part
. is used to concatenate strings in php
You're only assigning the last item to the $list variable. You need to concatenate them all together.
Try:
if (mysqli_num_rows($result) > 0) {
// Create the drop down menu
$list = "";
while($row = mysqli_fetch_assoc($result)) {
$list .= '<div class="dropOption">' . $row["item"] . '</div>';
}
}
Note the $list .= instead of $list = part.
Related
I am trying to insert html code through a php variable in javascript. I am getting the following error below. Please can someone advise?
Error Message: "Unexpected Identifier 'Inactive'" ($option has values 'Inactive'/ 'Active')
PHP
$tr_active_Options = '';
$sql1 = "SELECT status FROM tr_active";
$result = $mysqli -> query($sql1);
while($row = $result -> fetch_assoc()){
$option = $row['status'];
$option = '<div class="dpOtions" onclick="track.addChosenOption(\''.$option.'\', \'act_ui\')">'.$option.'</div>';
$tr_active_Options .= $option;
}
$tr_active = '<div class="drpClass"><div class="dropOptionsDiv" id="actList_ui">'.$tr_active_Options.'</div></div>';
JAVASCRIPT
document.getElementById('anchor').innerHTML = '<div id="editWrap"><?php echo $tr_active; ?></div>';
The ' in your string are terminating the JavaScript string you've started with '.
You can safely have PHP generate a string for use in JavaScript using json_encode, like so:
document.getElementById('anchor').innerHTML =
'<div id="editWrap">' +
<?php echo json_encode($tr_active); ?> +
'</div>';
Note how the JavaScript string ends, then we use + to join it with the one that PHP will output (json_encode will handle the strings), then we + it with another JavaScript string after it. What the browser will see will look like this:
document.getElementById('anchor').innerHTML =
'<div id="editWrap">' +
"contents of $tr_active here" +
'</div>';
...which is valid.
That said: Using PHP to generate HTML with embedded JavaScript inside attributes is asking for a world of hurt. Separate those concerns! :-)
OK, I'm fairly new to javascript and am trying to make this script work. I don't know the terms of javascript enough to search for this I guess because it seems like a fairly easy thing to do, but it is not working. The links are supposed to open a side menu that slides across the screen and displays different data depending on which link is clicked.
My Script:
/* Open the sidenav */
function openNav(boxid) {
document.getElementById(boxid).style.width = "100%";
}
/* Close/hide the sidenav */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
My Body:
include('dbconn.php');
$sql = 'SELECT * FROM joblist';
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo '<span onclick="openNav(mySidenav- '.$row['jobname'].')">'.$row['jobname'].'</span><br>';
echo '<div id="mySidenav-'.$row['jobname'].'" class="sidenav">';
echo '×';
$eachrow = explode("," , $row["itemlist"]);
$arrlength = count($eachrow);
for($x = 0; $x < $arrlength; $x++) {
echo $eachrow[$x];
echo "<br>";
}
echo "</div>";
}
I'm not sure why boxid isn't sending the variable I place in each onclick
Look at what you're doing:
echo '<span onclick="openNav(mySidenav- '.$row['jobname'].')">'.$row['jobname'].'</span><br>';
That'll generate some html that looks like
<span onclick="openNav(mySidenav- jobname)">jobname</span><br>
That opennav call is doing a mathematical subtraction of two undefined variables, and sending the result of that undefined operation as an argument to the function.
You probably want something more like:
echo '<span onclick="openNav(\'mySidenav'.$row['jobname'].'\')">'.$row['jobname'].'</span><br>';
^^----------------------------^^
Note the extra (escaped) quotes, which now produces
<span onclick="openNav('mySideNav-jobname')">jobname</span><br>
Now your argument is a string, not a math operation.
So I'm trying to populate a select box within my html with array objects using JSON results, I've been looking at all this code so long I don't think I'm seeing the simple solution to my problem. This is my callback function where I'm populating the select box. The JSON request has went through fine but I am stuck with a blank select box everytime.
function getArtistsCallBack()
{
if (req.readyState == 4) {
if (req.status == 200) {
// TO DO: populate artistlist select box using JSON
var response = req.responseText.parseJSON();
var artistSelect = document.getElementById("artistlist");
for (i=0;i<response.artistsarray.length;i++){
var artist_id = response.artistsarray[i].artist;
var artist = response.artistsarray[i].artist;
artistSelect.options[artistSelect.options.length] = new Option(artist, artist_id, false, true);
}
}
}
}
Here is the select box within the HTML for reference just in case;
<div id="artistscontent">
<select id="artistlist"></select>
</div>
This is artists.php where a database is queried for an array of objects, the array that is used previously;
<?php
// Include utility files
require_once 'include/config.php';
// Load the database handler
require_once BUSINESS_DIR . 'database_handler.php';
// Load Business Tier
require_once BUSINESS_DIR . 'collection.php';
$artistsarray = Collection::GetArtists();
print json_encode($artistsarray);
$jsonresponse='{"artistsarray":[';
foreach($artistsarray as $artist => $row)
{
$artist_id=$artist+1;
$artist=$row['artist'];
$jsonresponse .= '"artist_id":"' . $artist_id . '"},';
$jsonresponse .= '"artist:"' . $artist . '"},';
}
$jsonresponse .= ']}';
echo $jsonresponse;
?>
Any help would be much appreciated! Thanks!
You need to use the json length for the options array and do it outside of the for loop. Then use options.add
var json = [{key:'1', value:'value1'},{key:'2', value:'value2'}]
var artistSelect = document.getElementById("artistlist");
artistSelect.options[json.length];
$.each(json, function(key, value){
console.debug(value);
artistSelect.options.add(new Option(value.key, value.value));
});
Check out this plunker:
http://plnkr.co/edit/i3A6mo672CskXvbstWsu?p=preview
The artistSelect.options is not an array, you need to use the add method:
var opt = new Option(artist, artist_id);
artistSelect.options.add(opt);
I'm trying to pass a variable from JS to PHP but so far no luck. I've been searching here for solution, but it seems that nothing helps..
Ok, I have php file with pagination:
$pagination .= '<li>'.$i.'</li>';
Paginate_click launches js function:
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("views/fetch_articles.php", {'page':(page_num-1)}, function(){
$(window).scrollTop(0);
});
$.post('views/articles_list.php', {'page':(page_num)});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
In php file I need information which page of pagination I'm currently on so I want to retrieve page_num value back to my php. I tried this:
$.post('views/articles_list.php', {'page':(page_num)});
And in php:
$page_number = $_POST["page"];
I tried also many other options, but nothing helps. I thought it will be easier :/
As you probably noticed there's another php file (fetch_articles.php) and in this case $_POST["page"]; works. But for articles_list.php I can't use load function.
EDIT: What I want and entire code.
I have simple and nice pagination. The only problem is that it has no option for prev/next and it shows all the buttons. It's a problem when you have a lot of pages. So my idea is to shrink it down and instead of heaving 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,15,16,17,18,19 and so on I want this:
prev,1,2,3...67,68,next. To do this I need to pass to my php file an information about actual page. With this variable I can calculate everything and organize my pagination with for/if/else statements.
The code.
articles_list.php:
<?php
include("../config/connection.php");
include('../config/css.php');
$results = mysqli_query($dbc_connection,"SELECT COUNT(*) FROM articles");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '<li>'.$page_number.'</li>'; // only to check if variable is passed
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="js/pagination.js"></script>
</head>
<body>
<?php $page_number = $_POST["page"];
echo $page_number; // only to check if variable is passed ?>
<div id="results"></div>
<?php echo $pagination; ?>
</body>
</html>
pagination.js:
$(document).ready(function() {
$("#results").load("views/fetch_articles.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("views/fetch_articles.php", {'page':(page_num-1)}, function(){
$(window).scrollTop(0);
});
$.post('views/articles_list.php', {page:page_num}, function(data){});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
fetch_articles.php:
<?php
include("../config/connection.php"); //include config file
//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$result = mysqli_query($dbc_connection,"SELECT * FROM articles ORDER BY id DESC LIMIT $position, $item_per_page");
//output results from database
while($row = mysqli_fetch_array($result))
{
?>
<h2><?php echo $row['title']; ?></h2>
<p><i><?php echo 'By '.$row['author']; ?></i></p>
<p><?php echo $row['header']; ?></p>
Read<br>
<hr>
<?php
}
?>
Try removing the parenthesis around page_num:
$.post('views/articles_list.php', {'page':page_num});
You didn't said in which one of the requests you can't get the value you're trying to pass. So, I'm guessing it is in the first one:
$("#results").load(...);
The problem here is that you're using the .load() method, which is equivalent to .get(). So, when you try, in the PHP file to get $_POST["page"], it will not be there, because it is actually in the $_GET array.
I may be missing something here, but couldn't you just append a query string to the url manually?
$.post('views/articles_list.php?pn=' + page_num);
Then in your fetch_articles.php you just pull it off with
$page_number = $_GET["pn"];
If that fails you can always use a cookie.
Instead of
$.post('views/articles_list.php', {'page':(page_num)});
try
$.post('views/articles_list.php', {page:page_num}, function(data){
console.log(data);
},'json');
And also double check if 'views/articles_list.php' is the correct path. If you were using Chrome, kindly read the parsing via right click -> inspect elements -> Network.
Addition(After posted your edit code) :-
Please remove the Doctype and HTML and leave something like this.
<?php
include("../config/connection.php");
include('../config/css.php');
$results = mysqli_query($dbc_connection,"SELECT COUNT(*) FROM articles");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '<li>'.$page_number.'</li>'; // only to check if variable is passed
$pagination .= '</ul>';
}
//Assuming you're doing ajax here. so either pagination or page number posting back? if both try below.
$page_number = $_POST["page"];
echo json_encode(array("pagination"=>$pagination,"pageNumber"=>$page_number));
?>
Hope it helps.
I have multiple tables on one page and an array of numbers from array_keys.
I have given each <tr> an incremental ID, starting at 0. If my array returns 0,1,3,5 I would want the <tr> with an ID of 2 and 4 to hide. Usually I would use CSS and apply a style: display=none.
I presume I need to use jQuery .find() within a array loop such as this:
$arr = array_keys($floor_item, $po); //floor_item is my array & po is the value I'm searching
foreach($arr as $key => $item){
print "<tr id='" . $item . "'><td>" . $item . "</td></tr>"; //this will show me the id's I want
//just guessing here
$( "tr" ).find( "$item" ).hide();
}
If you need to use client side code to hide the elements, try something like this:
var jsArray = [<?php echo(implode(",", $ids_you_want_to_show_array); ?>];
$("#your_table_id tr").hide();
$.each(jsArray, function(key, value) {
$("#tr_" + value).show();
});
Assuming your td's ids are "tr_0", "tr_1", and so on.
By the way, don't use numbers as ID.
Try this:
$arr = array_keys(1,2,3,4,5,6,7,8,9,10);
$i == 0;
foreach ($arr as $item) {
if ($i%2 != 0 || $i == 0) {
//this will show me the id's I want
print "<tr id='pref_" . $item . "'><td>" . $item . "</td></tr>";
}
$i++;
}
Anyway, you need to learn php from basics before you start to use that.
In arrays, if you want key/value pairs you can define it like:
$array = array(
'key1' => 'value',
7 => 'other value',
...
);
or
$array['key1'] = 'value';
$array[7] = 'other value';
And as i mentioned, you can not use jQuery/javascript code in your php code.