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);
?>
Related
this is my php code that creates a table using the results of a mysql query:
echo "<table id='table' class='selectQuery'>
while($row = mysqli_fetch_array($slctQuery)) {
// ; echo $row['id']; echo
echo "<tr class='someClass' idNumber="; echo $row['id']; echo ">
<td>";
echo $row['fname'];
echo "</td>
<td>";
echo $row['lname'];
echo "</td>;
</tr>";
}
echo "</table>";
and this part is my jquery code for changing style on click on table row:
<script>
$(document).ready(function(){
$("#table tr").click(function(){
$('.someClass').removeClass('selected');
$(this).addClass('selected');
idNum = $(this).attr('idNumber');
});
$("#table tr").click(function(){
$("#DelEdtQuestion").addClass('selected1');
});
});
</script>
and this part is for style:
<style>
tr.selected {
background-color: brown !important;
color: #FFF;
}
</style>
and this is my php code for button
if(#$_POST['Search']){
/// what should I do?
}
So, now I want have my idNum value when my search button in form was clicked.
thanks for attentions
You can use ajax. If you have a form with id="myform" and (example) input fields: firstname, lastname, username and password, the following script should send data to the php:
$(document).ready(function(){
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'ajaxfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res);
alert(res);
});
});
The ajaxfile.php can be something like that:
<?php
$firstname = mysql_real_escape_string($_POST["firstname"]);
$lastname = mysql_real_escape_string($_POST["lastname"]);
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
//here you have the variables ready to do anything you want with them...
//for example insert them in mysql database:
$ins = "INSERT INTO users (firstname, lastname, username, password ) VALUES ( '$firstname', '$lastname', '$username', '$password' )";
if(mysql_query($ins)){echo "SUCCESS";}else{echo "FAILURE";}
?>
Another example, similar to yours, is to take the row id from your table, pass it to ajax, have ajax (for example) make a query to the database and return the results:
// your script, modified for ajax:
$(document).ready(function(){
$("#table tr").click(function(){
$('.someClass').removeClass('selected');
$(this).addClass('selected');
var idNum = $(this).attr('idNumber'); //use "var" to -initially- set the variable
$.ajax({
type: 'POST',
url: 'ajaxfile.php',
data: 'id='+idNum
}).done(function(res){
var res = $.trim(res);
alert(res);
});
});
$("#table tr").click(function(){
$("#DelEdtQuestion").addClass('selected1');
});
});
Modified ajaxfile.php to suit the above example:
<?php
$id = mysql_real_escape_string($_POST["id"]);
//query database to get results:
$result = "SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1";
$row = mysql_fetch_assoc($result);
echo "Username: ".$row["username"]."Password: ".$row["password"]."Firstname: ".$row["firstname"]."Lastname: ".$row["lastname"].
?>
Since your question was rather ambigious, I put more effort to give you an idea about the basics of ajax so that you work out your own solution, rather than to suggest a potential solution -that at the end could not be what you were looking for...
And since we are talking about ajax basics, it is a good practice to secure your ajax files since they are accessible from any browser:
in the very beginning of any ajax file, right below the "?php" tag, you can add these lines below, to protect the file from being accessed by browser -but remain accessible to ajax calls:
//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}
Hope that helps you and others. T.
UPDATE:
It is ALWAYS a good practice to keep your php and javascript files separately... In the above examples there are ideally 3 files involved: the main php file, the scripts file and the ajax-php file.
So -preferably after the "body" tag of your "main" php file- you should include the scripts-file (after the jquery ofcourse!). Like that:
<!-- jQuery v.1.11.3-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- include scripts file -->
<?php include("scripts.php"); ?>
(notice that for jquery I use the regular "script" tags but for the scripts file I just do a "php include").
As you see above, the javascript file has also ".php" extension (not ".js"). This is a "trick" I like to do because it gives me the ability to execute php code within the js file. Of course, all javascript code in that file is included between "script" tags.
example of a hypothetical "scripts.php":
<script>
// I create a js variable that takes value from php
var phpDate = '<?php date("Y-m-d"); ?>';
alert(phpDate);
//or pass the contents of another php variable in your app to javascript:
var myPhpVar = '<?php echo $my_php_var; ?>';
//or put a php SESSION to a js variable:
var mySess = '<?php echo $_SESSION["my_session"]; ?>';
</script>
The above comes quite handy sometimes when you want to pass to javascript php variables that already exist in your application.
It is a very long answer (more like a tutorial!)... But now should be quite clear to you how to pass values not only from js to php but also vice versa!!!
HTML:
<section class="clientbox">
<div class="container">
<div class="col-lg-10 col-lg-offset-1">
<h2>WHAT CLIENT SAYS</h2>
<h4>POSITIVE REVIEWS FOR LOVING PROBLAM.COM </h4>
<p id="testimonial"><?php echo $alldata[0]['text'] ?></p>
</div>
</div>
</section>
javascript:
<script type="text/javascript">
<?php $i = 1; ?>
setInterval(function()
{
document.getElementById('testimonial').innerHTML = "<?php echo $alldata[$i]['text'] ?>";
<?php $i++; ?>
}, 3000);
What actually I am trying to do is change the text of 'testimonial' from values stored in $alldata array every 3 secs.
The problem is that the php variable $i is not getting updated. It stays 1 only.
You mixed the server side logic (PHP) with the client side logic (JavaScript).
When the client request your web page, PHP render the contents which contains HTML, CSS, JavaScript and some other contents and the web server send these contents to the client side.
The web browser receives these contents and then execute the JavaScript and render the HTML according to the styles.
You need to generate all the contents needed by the JavaScript setInterval on the server side, and adjust your JavaScript logic to iterate on these data.
The logic may looks like the following. I'm not familiar with PHP, not sure if this is valid. The JavaScript doesn't check if all data has been consumed.
<script type="text/javascript">
<?php
function get_data($e) {
return($e['text']);
}
$data = array_map("get_data", $alldata);
?>
var js_alldata = <?php echo json_encode($data) ?>;
var i = 1;
setInterval(function()
{
document.getElementById('testimonial').innerHTML = js_alldata[i % js_alldata.length];
i++;
}, 3000);
You can't mix PHP and Javascript like that. PHP runs first, producing some data for Javascript to interpret. From Javascript's perspective, it can only see this:
<script type="text/javascript">
setInterval(function()
{
document.getElementById('testimonial').innerHTML = "some data";
}, 3000);
</script>
You would need to pass all of the data to Javascript so it can iterate over it.
See this answer for how to mix PHP and Javascript.
I've made this code and it is working. As people above told you, server side cannot work with the client-side iterations or setIntervals, therefore you should send the whole data beforehand.
Example:
$array = array();
$array[0]['text'] = 'hi';
$array[1]['text'] = 'hey';
$array[2]['text'] = 'hou';
$js_array = json_encode($array);
?>
<p id="testimonial"><?php echo $array[0]['text'] ?></p>
<script>
var json;
var i=1;
json = <?php echo $js_array; ?>
setInterval(function()
{
document.getElementById('testimonial').innerHTML = json[i]['text'];
i++;
}, 3000);
console.log(json);
</script>
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>';
}
}
I am working on a project where I have divisions stored in mysql database with the "division id" and the "division name";
what I want to have is so that i use php to do a "while" loop and go through all the divisions;
then for each division it creates a button which will trigger a javascript function…
I have done a lot of testing on this so I know certain parts are working…; here is my code:
<p id="id57512">How are you?</p>
<script>
var g_myobj = {};
</script>
<?php
$result_g1 = mysql_query("SELECT * FROM divisions");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$div_id=$row[div_id];
$div_name=$row[div_name];
$button_id="b";
$button_id.=$div_id;
$function_id="f";
$function_id.=$div_id;
?>
<button id=<?php echo $button_id; ?>><?php echo $div_name; ?></button>
<script>
var f_id='<?php echo $function_id; ?>';
var b_id='<?php echo $button_id; ?>';
var div_id='<?php echo $div_id; ?>';
var newFieldName = f_id;
var newFieldValue = function() {document.getElementById("id57512").firstChild.nodeValue=gman_code1(div_id);};
g_myobj[newFieldName] = newFieldValue;
var gman_code1 = function(number) {
var result1 = number*2;
console.log(result1);
return result1;//add return statement
}
//define the behavior
document.getElementById(b_id).addEventListener("click", g_myobj[f_id] , false);
</script>
<?php
}
the function names need to be a variable; but I figured out how to do that by making it an object; and so can access the different functions that way…
I basically tested this all when it was not in a loop; where I manually had it do everything twice (even creating the functions in the object) and it all worked fine…
basically when you click on a button it is supposed to send a number to that "p" container and multiply it by 2
when I did it manually and not in loop i just had it create the object g_myobj first and then just started adding items to the object…
but now that i am doing this in a loop - I felt I could not have the statement that creates the empty object in the loop or it would just keep recreating it; so I went above the loop and had the object created there in its own "script" tags all by itself…
that part may be a problem with this, not sure at all…
another potential problem is that I am not sure if I can do all this in a loop like this
it is a "php loop" and so maybe this just all cannot be done in a loop like that…
What is going on is the first button works but none of the others do…
So, I am hoping someone can advise me on what I am doing wrong on this…
Thanks so much...
If all you are trying to do is send a number to <p> and multiply it by 2, see this one liner function. I assume you are trying to accomplish more than just the multiplying thing otherwise you probably would have just done a simple function like below...
Also, I'm sure you will get lots of comments on it, but you should not be using the mysql_ functions anymore. They are both deprecated and potentially unsafe. You should use mysqli or PDO prepared statements.
On your button, you should probably put quotes around the id="yadayada" instead of id=yadayada. jQuery may be a good option for your js to handle functions or what-have-you.
<p id="id57512">How are you?</p>
<?php
$result_g1 = mysql_query("SELECT * FROM divisions");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH)) {
$div_id = $row[div_id];
$div_name = $row[div_name];
$button_id = "b$div_id";
$function_id = "f$div_id"; ?>
<button id="<?php echo $button_id; ?>" onClick="MyRadFunction('<?php echo $div_id; ?>')">
<?php echo $div_name; ?></button>
<?php } ?>
<script>
function MyRadFunction(DivId) {
$("#id57512").html(DivId*2);
// var NewNum = $("#id57512").text();
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
When rendering your button, you should wrap the id in quotes, e.g.
<button id='<?php echo $button_id; ?>'><?php echo $div_name; ?></button>
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);
}
});