i make some sort of a shopping cart that when i press on a table line it suppose to open some details about the item, for this purpose i used a div which is at height 0 and hidden at first which contains the details, the problem is that i think that the browser will load the the info pages regardless of if the line was pressed or not. is there any way to make the browser load the page only when his DIV is visible?
$int = 0;
echo "<table class=\"result_table\" id=\"result_table\">";
foreach($types as $data){
echo "<tr onClick=\"present(".$int.");\" >";
echo "<td align=\"right\">";
echo $data['number'];
echo "</td>";
echo "<td align=\"right\">";
echo $data['item_name'];
echo "</td>";
echo "<td align=\"right\">";
echo $data['amount'];
echo "</td>";
echo "<td align=\"right\">";
echo "17";
echo "</td></tr>";
echo "<tr class=\"info_row\"><td colspan=\"4\"><div id=\"div_num_".$int."\" style=\"height:0px\">
<object type=\"text/html\" data=\"page.php\" style=\"width:100%; height:100%; margin:0%;\">
</div></td></tr>";
$int++;
}
echo "</form></table>";
the css for the row
.info_row{
visibility:hidden;
}
the JS:
function present(item_id){
var div = document.getElementById("div_num_"+item_id);
if(div.style.visibility=="visible"){
div.style.visibility = 'hidden';
div.style.height= '0';
} else {
div.style.visibility = 'visible';
div.style.height= "200px";
}
}
as you can see all the info loads with the page but are invisible.
other good ways of tackling this problem will be appritiated especially if it does not include jquery because i am not really strong in it.
thanks in advance.
Firstly, if there isn't much info to load, preloading the data is probably more sensible anyway. Users want a responsive UI, even if it means a few extra milliseconds of initial download time for data they'll never see.
But, if you insist on loading the data separately, you could use an xmlhttprequest to load a representation of the data (such as in JSON), and use a templating solution to output the result into the info div.
The page that might generate the JSON representation of the data might look something like this:
<?php
$result = array();
// ... Code that defines type ... //
$int = 0;
foreach($types as $data){
$result[] = array(
"int" => $int,
"number" => $data["number"],
"item_name" => $data["item_name"],
"amount" => $data["amount"]
);
$int++;
}
echo json_encode($result);
?>
So, when a user clicks a link, the above page would load in an xmlhttprequest. You could then parse the result with JSON.parse(req.responseText), and apply an HTML template to the result (check out the above link, plus this one, for more info on how to do that).
Again, you're probably fine just loading all the data in one go. Extra HTTP headers actually make pages take longer to completely load.
You can use an ajax call:
with javascript
<script type="text/javascript">
function loadInfoRow()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var responseText = xmlhttp.responseText;
//Use the response text to add the extra row
}
}
xmlhttp.open("GET","info.txt",true);
xmlhttp.send();
}
</script>
with jquery
$.ajax({
url: "info.txt",
context: document.body,
success: function(text){
//where text will be the text returned by the ajax call
$(".result_table).append(text);
}
});
Related
I'm using jquery-3.3.1.min to live update and calling it to my main.php
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('smoke.php')
$('#show2').load('pids.php')
$('#show3').load('flame.php')
$('#show4').load('panic.php')
}, 2000);
});
/////
I'm echo in php using
$smoke_status = $row['smoke_status'];
$pids_status = $row['pids_status'];
$flame_status = $row['flame_status'];
$panic_status = $row['panic_status'];
$startdate = $row['startdate'];
$stopdate = $row['stopdate'];
echo "<tr>";
echo "<td id='show'></td>";
echo "<td id='show2'></td>";
echo "<td id='show3'></td>";
echo "<td id='show4'></td>";
echo "<td>$startdate</td>";
echo "<td>$stopdate</td>";
echo "</tr>";
but now...i want to make my live update data into a variable in script
how can i declare it.
i'm success calling this
var i = <?php echo $panic_status ?>;
and how can i call
echo "<td id='show'></td>";
echo "<td id='show2'></td>";
echo "<td id='show3'></td>";
echo "<td id='show4'></td>";
into new variable??plsss help and srry for the long question
Hello I do not know what you are actually doing with the code. its so scattered that one cannot easily know where to start
1.) You are displaying a result and i did not see where you are trying to escape those database with htmlentities() or htmlspecialchars() functions against xss attack.
2.) I do not know whether you are still using mysql_connect deprecated functions in your database query. if so please better move it to mysqli or PDO.
3.) i can see you calling simultaneously four php files simultaneously with 2 seconds call. What is it you are trying to achieve. This will cause alot of issues to the server including latency, poor performance and over consumption
of data. If you need a real time update why don't you switch over to nodejs and socket.io.
To answer your question, I have created an ajax example to get you started
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//$('#result').click(function(){
var post1 = 'data to post if any';
$('#loader').fadeIn(400).html('Please Wait. Data is being Loaded');
// assuming that you want query result by posting a variable
var datasend = "alert1="+ post1;
$.ajax({
type:'POST',
url:'smoke.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#loader').hide();
$('#result').fadeIn('slow').prepend(msg);
}
});
//})
});
</script>
<div id="loader"></div>
<div id="result"></div>
The above script will make a call to smoke.php and display any result contained there in
<?php
$smoke_status = 'I am not smoking';
/* if data is to be displayed in html form, you have to escape it with either htmlspecialchars() or htmlentities() functions to ensure
that XXS attack is not possible. you can read further on how to escape both single, double quotes with it as case may be
*/
echo htmlspecialchars($smoke_status);
?>
I'm working with PHP and Javascript. I return arrayList from PHP file to PHP web page; in the PHP web page I want to display array list in a table, but one of the fields "state" can be "Success or Rejected", if success, the td table shows span bootstrap icon, else, also. I using Javascript function for return span icon, but it can't read param "state" to invoke function.
My js file:
function getStateIcon(strState) {
var strHtml = '';
if (strState === "Success") {
strHtml = '<span class="label label-success">' + strState +'</span>';
} else if (strState === "Rejected") {
strHtml = '<span class="label label-warning">' + strState + '</span>';
}
return strHtml;
}
And my php web page:
<table>
//headers.....
//body
<?php
include_once '../../Model/RequestDto.php';
$list = new ArrayObject();
if (isset($_SESSION["list"]) == null) {
echo 'not found results';
} else {
$list = $_SESSION["list"];
foreach ($list as $val) {
?>
<tr>
<td><?php echo $val->getID?></td>
<td><?php echo $val->getDate()?></td>
<td><script type="text/javascript">getStateIcon(<?php echo $val->getState()?>);</script></td> //here i want pass parameter state to the js function for return span icon and draw td, but this show empty
</tr>
<?php
}
}
?>
</tbody>
</table>
You're returning the string to the caller of the function instead of writing it to the innerHTML of the td.
Actually you can easily do that with CSS by styling the td's. But if you want to use JavaScript, you need to manipulate the DOM innerHTML of the td's. For example:
<td class="Success"><td>
And, add the onload attribute to the body.
<body onload="buildIcons()">
Then the JavaScript can be written like this.
function buildIcons() {
var tds = document.getElementsByClassName('Success');
for (var i = tds.length - 1; i >= 0; --i) {
var td = tds[i];
td.innerHTML = "echo the img here";
}
}
It can be done easier with CSS.
.Success {
background: 'path to bg image';
}
You have a misconception about how JavaScript interacts with the page. Your PHP uses echo to write values into the page before it gets sent to the client.
Your JavaScript function gets called and returns a string, but this string is never written to the page.
You could fix your JavaScript to manipulate the page DOM, but this is unnecessary. At the time the php is executed, it knows the state and can easily write the span tags into the page with the echo method.
You don't need the JavaScript at all.
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.
I am actually creating a forum. So, there would be a "order by" dropdown box i.e a select tag in html. Where the user selects any order like by time or like, etc. An ajax function is called which dynamically brings content into the page from mysql database.
Select menu
<select name="orderby" onchange="showposts(this.value)">
<option value="1" selected>By Time</option>
<option value="2">By Genuine Count</option>
<option value="3">By Dubious Count</option>
</select>
showposts function
function showposts(str){
orderby=str;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("postsdiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showposts.php?q="+str,true);
xmlhttp.send();
}
Showposts.php page
$sql = "SELECT * FROM posts order by date desc ";
$result = $connection->query($sql);
$username=$_SESSION['username'];
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."    ";
echo "Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine'].";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: ".$row['subject']."</br>";
echo "Post: ".$row['post'].'<br />';
}
Problem
So, the problem here is, I want to use a continuous scroll option like the one which is used in facebook. All the javascripts and jquery libraries I saw use logic that when the user scrolls down to the page, the javascript then places some content after that. But, here I running a while loop which brings the data from database at a time. So, I couldn't implement the javascript code. So, is there any thing that I could do to achieve continuous scroll, like is there any possibility to break the while loop or retrieving entire data and display part by part or anything like that?
javascript for scrolling
function yhandler(){
var wrap=document.getElementById('postsdiv');
var contentheight=wrap.offsetHeight;
var yoffset=window.pageYOffset;
var y=yoffset+window.innerHeight;
if(y>=contentheight){
showposts();
}
}
window.onscroll=yhandler();
Use the PDO class built into php and the query from the database will return all the rows as an array of stdclass objects. Then use PDOStatement::fetchObject() to loop through the array
As you are retrieving the data from server using JavaScript, why don't you put the view with the help of JavaScript instead of PHP.
Try using Asynchronous Javascript Call (AJAX) instead of XMLHttpRequest. This will help you to load data asynchronously which means that even if the the result coming form server take time you can still execute your other javascript codes.
With AJAX implemented, let say you want to fetch 10 Posts at one time, then after fetching first 10 posts, you can print the data for those 10 using JavaScript and simultaneously make a call for another 10.
Prepare a successCallBack function, where you will parse the data received and put that as required for your HTML. You will need to append the posts, so that when the next AJAX returns the result, that gets appended after the last post.
http://www.jquery4u.com/demos/ajax/
You should look into MySQL LIMIT. The limit function takes 2 input variables, start and length. With these 2 variables you can create a paging system; that would go something among the lines of:
showposts function
//Add a global variable to save the current page:
var currentPage = 0;
var currentType = 0;
function showposts(str){
//ALL PREVIOUS CODE, UNCHANGED
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("postsdiv").innerHTML+=xmlhttp.responseText;
}
}
if(str != undefined){
currentType = str; //save the current type for later use
document.getElementById("postsdiv").innerHTML = "";
}
xmlhttp.open("GET","showposts.php?q="+currentType+"&p="+currentPage,true);
xmlhttp.send();
}
Showposts.php page
<?php
$currentPage = intval($_GET['p']);
$numPerPage = 30; //change this to the number of items you want each page
$sql = "SELECT * FROM posts order by date desc LIMIT ".($currentPage * $numPerPage).", ".$numPerPage;
$result = $connection->query($sql);
$username=$_SESSION['username'];
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."    ";
echo "Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine']."</span>";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: ".$row['subject']."</br>";
echo "Post: ".$row['post'].'<br />';
}
?>
Now you need to detect when a user has scrolled to the bottom of the page, then call the following function:
function nextPage(){
currentPage++;
showposts();
}
I am attempting to call a javascript function inside a php where loop. I've succeeded in calling the variable, however the function only works on the first line, and then breaks a subsequent query.
The javascript is a simple show/hide of a div or span tag with a specific id. I'm trying to have this appear for every instance of a variable, but only open the span associated with that entry, so I used a php variable from the query.
The javascript code is contained in the header; it works fine without the php, and the php works fine without the javascript but I can't seem to make them work together.
Here's the code:
while($row = mysqli_fetch_array($qir)) {
$ingredient_id = $row['ingredient_id'];
echo '<input type="checkbox" value="' . $ingredient_id . '" name="markdelete[]">';
echo $row['amt'] . ' ' .$row['ingredient_name']; ?> <button onclick="showHide('<?php echo $row['ingredient_id']; ?>'); return false">Edit amount</button> <br />
<span id="<?php echo $row['ingredient_id']; ?>" class="hide">
<?php include_once('amt.php');
echo '</span> ';
// }
echo '<br />';
}
echo '<input type ="submit" name="remove" value="Remove">';
First of all, the showHide is only working on the first record
It is also making this query not respond at all.
if (isset($_POST['remove'])) {
iF (!empty($_POST['markdelete'])) {
foreach ($_POST['markdelete'] as $delete_id) {
// remove specific source from source_subject
$rem_ing = "DELETE from dish_ingredient
where ingredient_id = $delete_id
and dish_id = $dish_id ";
mysqli_query($dbc, $rem_ing)
or die ('Error removing ingredient: '.mysqli_error($dbc));
}
}
}
I tried removing the return false;, to no avail. Please let me know if I need to show more of the code (e.g. the javascript itself)
Edit:
I've tried working within the php string (this is actually what I had tried first) but it seems to break everything (no javascript, no php)
echo $row['amt'] . ' ' .$row['ingredient_name'] . '<button onclick="showHide(\''. $row['ingredient_id'] .'\') return false">Edit amount</button> <br />';
echo '<span id=" '. $row['ingredient_id'] .' " class="hide">';
include_once('amt.php');
echo '</span> ';
Edit: I am open to other solutions if this is not something that is possible. I'm feeling a bit stumped. Realistically I just want to have a list of items called from a mysql database, and have a field appear onclick to edit an associated variable if desired without having to send it to another page or reload the script for usability (hence the javascript piece).
Thanks again, anyone who can assist.
Note: this is the script that I am calling:
<script language="JavaScript" type="text/JavaScript">
menu_status = new Array();
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(menu_status[theid] != 'show') {
switch_id.className = 'show';
menu_status[theid] = 'show';
}else{
switch_id.className = 'hide';
menu_status[theid] = 'hide';
}
}
}
</script>
You don't need tag there as you are already in php block.Try it without and use
showHide(\''.$row['ingredient_id'].'\')
and change
<?php include_once(....);
to
include_once(........);
Hopefully that would work
===========
try this for you javascript
<script language="JavaScript" type="text/JavaScript">
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(!switch_id) {
switch_id.className = (switch_id.className.indexOf("show") > -1) ? "hide" : "show"
}
}
}
Okay after a long time on this, I finally figured out what was going on. Part of the issue was that I was trying to call a form inside a form, which I had forgotten is not permitted in HTML, so this required some redesign.
Other issues involved calling loops within inside loops, which caused problems where the first record would work, but not for the remaining records.
The javascript above did not need to be modified, only the way that it was called.
Here is what worked. The main key was using include() instead of include_once().
while($r = $qir->fetch_assoc()) {
$ingredient_id = $r['ingredient_id'];
$amt = $r['amt'];
$ingredient_name = $r['ingredient_name'];
echo $r['amt'] . ' ' .$r['ingredient_name'];
if ($row['user_id'] == $user_id) {
echo ' <span class="openlink"><button onclick="showHide(\''.$ingredient_id. '\')">edit amount</button></span><br/>';
echo '<div id="'.$ingredient_id.'" class="hide">';
include('amt1.php');
echo '</div>';
}
}