I'm just starting out with PHP, and I am attempting to move some jQuery ajax into PHP. Here is my PHP file:
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT * FROM agency ORDER BY name";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
echo "<li class=\"agency\">$name<ul class=\"agency-sub\"></ul></li>";
}
include 'closedb.php';
?>
Here is my current js function:
//Add Agency content
$("ul.top-level").on("click", "li.agency a", function (event) {
if($(this).next().length) {
var numbs = $(this).attr("href").match(/id=([0-9]+)/)[1];
showContentAgency(numbs, this);
} else {
$(this).closest('ul').find('a').removeClass('sub-active');
}
event.preventDefault();
});
And here is the showContentAgency(); function:
function showContentAgency(id, elem) {
$.post("assets/includes/contentAgency.php?id=id", {
id: id
}, function (data) {
$(elem).addClass("nav-active").parent().find("ul").html(data).show();
});
}
What I'd like to do is have PHP render the unordered list rather than have jQuery insert it. This is how it is currently featured in the above PHP file:
echo "<li class=\"agency\">$name<ul class=\"agency-sub\"></ul></li>"
So I would like the PHP to populate the <ul class="agency-sub"> list.
The structure of your code is a little bit unclear to me, but the broad outline is this: You take whatever function is generating the content in contentAgency.php and call that to get the HTML, then stick that inside when you're building up the list.
Php can not access the DOM of the page like Jquery can. If you wanted to access the DOM with Php, you would have to parse the entire web page, which is probably impractical for what you want to do. Php can only modify the page before it is loaded by the browser. If you want to run code after page load, you have to use javascript.
We might be able to help you more if you post more of your code, as we currently don't know what the page's code looks like.
Is this a list inside list?
By the way you can write php code like below, it is more readable
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT * FROM agency ORDER BY name";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
echo "<li class='agency'><a href='contentAgency.php?id=$id'>$name</a><ul class='agency-sub'></ul></li>";
}
include 'closedb.php';
?>
if you are using double quotes in echo you can use single quotes inside.
I'm uncertain as to what exactly you want but it sounds like you're looking for the 'foreach' loop. When I wanna populate a list of stuff from a result set i simple use:
<ul>
<? foreach($result as $object) ?>
<li><?=$object?></li>
<? endforeach; ?>
</ul>
foreach acts a for loop but doing all the logic in the background. Hope this helps.
Related
<?php
echo get_menu_tree(0);
?>
Here's my PHP tag wherein I'm calling a function that displays all the data (text) from PHP MySQL Database.
The default color when I'm calling the function is white. How do I change the font color into Black?
I just updated my post. Here's my return function. Any ideas?
<?php
function get_menu_tree($parentID)
{
global $con;
$menu = "";
$sqlquery = " SELECT * FROM category where parentID='" .$parentID . "' ";
$res=mysqli_query($con,$sqlquery);
while($row=mysqli_fetch_array($res,MYSQLI_ASSOC))
{
$menu .="<li><a href='index.php?page=category&categoryID=".$row['categoryID']."'>".$row['name']."</a>";
$menu .= "<ul>".get_menu_tree($row['categoryID'])."</ul>"; //call recursively
$menu .= "</li>";
}
return $menu;
}
?>
Thank you!
<?php
function get_menu_tree($parentID)
{
global $con;
$menu = "";
$result = mysqli_query($con, "SELECT * FROM category WHERE parentID = '$parentID'");
while($row = mysqli_fetch_assoc($result)) {
$menu = "<li><a href='index.php?page=category&categoryID =".$row['categoryID']."'></a></li>";
}
$menu = "<ul>".$menu."</ul>";
return $menu;
}
?>
But if you want to output a table with the data i personaly would just use a php file and use this code
<?php
//Define $con here and put the php scripts you need in this file or use require(path/to/file.php) or include(path/to/file.php) to include other php documents
?>
//Some HTML...
<ul>
<?php
$result = mysqli_query($con, "SELECT * FROM category WHERE parentID = '$parentID'");
while($row = mysqli_fetch_assoc($result)) {
echo "<li><a href='index.php?page=category&categoryID =".$row['categoryID']."'></a></li>";
}
?>
</ul>
Let me be a little more generic instead of going straight to the point:
You can think at PHP as a lnaguage to manipulate text effectively and the kind of text you can manipulate is quite generic: in fact you can use PHP to produce any kind of text, also C, C++, ... code even if it is typically used in the Web context hence to produce HTML and CSS
As a result of this, PHP in itself has no understanding of the text it's manipulating, from its perspective it's just text
What you are interested in (color of an element) is something that is defined at CSS level, not at PHP level, however PHP is the tool you can use to produce CSS
To be slightly more complete (and conclude) this Appearance Semantic is defined at CSS level and requires HTML to define the structure first: the example provided by #TSteffenmann is in fact a specific case of this and it's hence correct but you can do something even more generic (i.e. instead of a span you can use p, ... whatever you want and use CSS to style)
I hope someone will be able to shed some light on why I am having this issue. I have created a basic list that is generated from a MySQL database using a PHP class. I am then trying to use some basic jQuery to remove a list item. I could not get it working for a long time eventually finding that if I moved the jQuery include to the end of the HTML file it works but not with it included at the top of the script as I would normally aim to do. I had thought that the jQuery document ready function should have resolved this but it is not for some reason.
Here is the jQuery (very basic as said):
$(document).ready(function(){
$(".completeButton").click(function(){
$(this).closest('li').remove();
});
});
Here is the HTML page body (notice I have the jQuery include near the end rather than in the header where it does not work and remove the item, it works fine with it here though?):
<?php
session_start();
if(isset($_SESSION['user'])) {
include "header.php";
?>
<h2>Task List</h2>
<?php
include_once "DatabaseConn.php";
include_once "taskList.class.php";
$sql = "SELECT `GV_Employee`.`requests`.`req_ID` , `GV_Employee`.`equipment`.`description` , `GV_Employee`.`employees`.`first_name`, `GV_Employee`.`employees`.`last_name`
FROM requests
RIGHT JOIN equipment
ON requests.eq_ID=equipment.eq_ID
RIGHT JOIN employees
ON requests.emp_ID=employees.emp_ID
ORDER BY requests.req_ID;";
$stmt = $db->prepare($sql);
$stmt->execute();
$results = $stmt->fetchALL();
foreach ($results as $row){
$task[] = new tasklist($row);
}
foreach($task as $item){
echo $item;
}
?>
<script src="tasklist.js"></script>
<?php
}else {
session_destroy();
header("Location: http://dunc2/dylanr/Starters&Leavers/index.php");
//header("Location: http://192.168.0.4/Starters&Leavers/index.php");
exit;
}
?>
Here is the class for the dynamic list:
<?php
class taskList {
private $taskData;
public function __construct($task){
if(is_array($task))
$this->taskData = $task;
}
public function __toString(){
return '<li id="task-'.$this->taskData['req_ID'].'" class="taskList">
<div class="text">'.$this->taskData['first_name'].' '.$this->taskData['last_name'].
' requires: '.$this->taskData['description'].'</div>
<div id="button">
Complete
Priority
</div>
</li>';
}
}
?>
I hope this question makes sense, I tried searching the forum but could not find a topic which covered this exact situation apologies if there is one.
Many thanks
James
My PHP script queries a database and returns the rows as li elements to a div in a jQuery Dialog. It does this by building an array in the PHP while loop that processes the query row responses. Each li element has some data, an HTML button, and some javascript to execute on that li element when the button is clicked.
If I write "bad HTML" with the same id for each li element, the javascript executes, but only on the first li element. When I write "good HTML" with a unique id for each li element, I can't get the javascript to execute. I've researched and tried lots of things, but can't find anything this complicated to fix this. What should I do? Here's the stripped down code. The problem seems to be in the lengthy $error_ListActives line, but I'm open to suggestions.
$rowCount = 0;
while ($row = mysql_fetch_array($fetch)) {
$storedStreetAddress = $row["streetAddress"];
$storedCity = $row['city'];
$error_NumberOfActives = "<li>Welcome back. You have . . .</li>";
$errorMessages[0] = $error_NumberOfActives;
$idMaker = "inactive" . $rowCount;
$error_ListActives = "<li> $storedStreetAddress, $storedCity $idMaker
<button type='button' id=$idMaker onclick='makeInactive()'>Pause this</button>
<script type='text/javascript'>function makeInactive()
//do stuff
{document.getElementById($idMaker).innerHTML='Inactive Completed';}
</script> </li>";
$errorMessages[] = $error_ListActives;
$rowCount++;
}
foreach( $errorMessages as $statusMessage ) {
echo $statusMessage;
}
Please be specific, and code is helpful. I don't follow general instructions well in this area, as I'm a newbie with PHP.
You're going to end up with a lot of problems here because you are writing your javascript function inside a while loop. That means that you will get several copies of the same function, and only the last one is going to actually fire!
To fix this, write a generic javascript function for makeInactive(id) and then just call it with the id of the element you are working on.
Outside of the php loop:
<script type='text/javascript'>function makeInactive(id)
//do stuff
{document.getElementById(id).innerHTML='Inactive Completed';}
</script>
Then change the php loop to:
while ($row = mysql_fetch_array($fetch)) {
$storedStreetAddress = $row["streetAddress"];
$storedCity = $row['city'];
$error_NumberOfActives = "<li>Welcome back. You have . . .</li>";
$errorMessages[0] = $error_NumberOfActives;
$idMaker = "inactive" . $rowCount;
$error_ListActives = "<li> $storedStreetAddress, $storedCity $idMaker
<button type='button' id='$idMaker' onclick='makeInactive($idMaker)'>Pause this</button>
</li>";
$errorMessages[] = $error_ListActives;
$rowCount++;
}
Why not:
<button onClick="makeInactive(<?php echo $row['id'] ?>);">...</button>
embed the ID code as a parameter to your MakeInactive() call. Other alternatives are to simply use some DOM, e.g.
<li id="xxx"><button onclick="makeInactive(this);">...</button></li>
<script>
function makeInactive(el) {
el.getParent('li').disable(); // not real code, but shows the basic idea
}
</script>
First of all, you're creating the same exact function multiple times on your page. Your other buttons don't know which makeInactive() function to use. Why don't you give all of your buttons the same class, and then create ONE function that is included on the page that fires when the buttons are clicked.
No offense, but this is kind of bad markup here.
I'm using CodeIgniter and I have a PHP MySQL Statement in a model:
function getAllDevices() {
$query = $this->db->query("SELECT * FROM Device_tbl ORDER BY Manufacturer");
return $query->result();
}
I then pass this through my controller to my view using:
$this->load->model("get_device");
$data['results'] = $this->get_device->getAllDevices();
And output this into a div using the following PHP:
<div class="hold-cont">
<div class="holder">
<div class="image-hold"><img class="image-icon" src="<?php echo base_url(); ?>assets/images/devices/<?php echo $row->Image; ?>"></div>
</div>
<div class="device-name devicename-txt">
<?php $mod = $row->Model;
$model = str_replace(" ","-",$mod);
?><?php echo($row->Manufacturer. ' ' .$row->Model); ?><br>
</div>
</div><?php } ?>
This currently works fine, however I have now incorporated a searchbox into my page which uses the jQuery function autocomplete and uses the JSON Array of $results
What I need to do is "convert" the PHP into Javascript which will enable the page to be populated using the JSON Array. I then need to be able to use this to pass the selection from the search box into a query which will change the content on the page without reloading it.
How can I go about this? I previously mashed together a way of doing it using the ajax function in jQuery, however this requires a URL which contained a PHP MySql statement which I cannot do now. The idea behind doing it like this is so it only runs 1 SQL Query when the page loads and I cannot change this method.
There is nothing to stop PHP "writing" Javascript.
You would need to build up a suitably formatted Javascript object either manually or by using the json_encode method of PHP (which essentially turns a PHP object into it's JSON notation). Assuming your PHP object is in $row then something like:
<code>
<script language="text/javascript">
var jsObject = <?php json_encode($row); ?>
</script>
</code>
Would give you a Javascript object in jsObject containing keys and values corresponding to the properties of the PHP $row object that you can then work with from Javascript.
json_encode();
json_decode();
Turns PHP arrays into a JSON array and back.
http://php.net/manual/en/function.json-encode.php
They work great.
Your ajax page:
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
and fetch this echoed json encoded data in your javascript
this is just a rough code, avoid using mysql function.
EDIT
Due to the overwhelming amount of advice I have received, I have fixed my problem. (After realizing the horrible php code I had written.) :D
Thanks to all!
Is there a reason that a function that is inside an included php file won't work on the parent page? I have two functions inside a php file that is included at the top of the page. However, when I try to call the function, it doesn't do anything. Here's the basic layout:
Main page:
<?php include 'includes/header.php'; ?>
<?php getPosts();?>
<div>Some HTML Code</div>
<?php endPosts(); ?>
Header.php
function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*End while statement */
};
Any idea why this won't work? I'm getting a blank white screen right now.
That code is so not valid. Why are you declaring a function inside of another function? And there aren't supposed to be semicolons on the end of function declarations/loops. The first thing to do is to enable error reporting.
I don't think that kind of stripping in functions will work. Aren't you getting errors from the PHP parser?
You should use something like this:
<?php $res = getPosts() ?>
<?php while ($item = mysql_fetch_array($res)): ?>
<div>Some HTML code</div>
<?php endwhile; ?>
With your getPosts() function like:
function getPosts()
{
$query = mysql_query("SELECT * FROM posts order by id desc");
if (!$query) die('MySQL error');
return $query;
}
I think you are missing the core understanding of what a function is. Variables inside one function cannot be accessed by another function unless passed into the function.
Also you can not start a procedural statement (while loop) in one function and end it within another function.
You're essentially trying to create a parameterless function named endPosts for each row in posts. I don't even know what you're trying but this won't work. You can't declare a function twice.
And even if you could, endPosts doesn't do anything, so even if this would be valid code, it wouldn't output anything (except for the div).
That's not really how PHP works. After including the header file, PHP will see something like this:
<?php
function getPosts() {
$result = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
};
function endPosts() {
} /*This is just an empty function */
}; /*And here is where getPosts ends*/
?>
You seem to be confused between what includes and function calls achieve.
What I think you want to be doing is something like:
<?php
getPosts();
while($row = mysql_fetch_array($result)) {
?><div>Some HTML Code</div><?php
}
?>