I am creating a website that contains different movies, every movie has a specific id_movie, i have added a comment box where the user can add a comment about the movie, however, every movie i click on, they all show the same comments that have been entered, I want every movie to have its own comments, I will be happy if you can help me with that. thanks
comments.php
<body>
<br />
<h2 align="center"><p >Add Comment</p></h2>
<br />
<div class="container">
<form method="POST" id="comment_form">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment"></div>
</div>
</body>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
add_comment.php
<?php
$con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');
$error = '';
$comment_name = '';
$comment_content = '';
if(empty($_POST["comment_name"]))
{
$error .= '<p class="text-danger">Name is required</p>';
}
else
{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"]))
{
$error .= '<p class="text-danger">Comment is required</p>';
}
else
{
$comment_content = $_POST["comment_content"];
}
if($error == '')
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $con->prepare($query);
$statement->execute(
array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>
fetch_comment.php
<?php
//fetch_comment.php
$con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $con->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($con, $row["comment_id"]);
}
echo $output;
function get_reply_comment($con, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $con->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
$output .= '
<div class="panel panel-default" style="margin-left:'.$marginleft.'px">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($con, $row["comment_id"], $marginleft);
}
}
return $output;
}
?>
and here when I click on each movie:
<?php include('header.php');
$qry2=mysqli_query($con,"select * from tbl_movie where movie_id='".$_GET['id']."'");
$movie=mysqli_fetch_array($qry2);
?>
<div class="content">
<div class="wrap">
<div class="content-top">
<div class="section group">
<div class="about span_1_of_2">
<h3><?php echo $movie['movie_name']; ?></h3>
<div class="about-top">
<div class="grid images_3_of_2">
<img src="<?php echo $movie['image']; ?>" width="180px" height="280px" alt=""/>
<?php include('ratte.php'); ?>
</div>
<div class="desc span_3_of_2">
<p class="p-link" style="font-size:15px">Type: <?php echo $movie['type']; ?></p>
<p class="p-link" style="font-size:15px">Price: £<?php echo date($movie['price']); ?></p>
<p style="font-size:15px"><?php echo $movie['desc']; ?></p>
Watch Trailer
</div>
<div class="clear"></div>
</div>
<?php $s=mysqli_query($con,"select DISTINCT theatre_id from tbl_shows where movie_id='".$movie['movie_id']."'");
if(mysqli_num_rows($s))
{?>
<table class="table table-hover table-bordered text-center">
<?php
while($shw=mysqli_fetch_array($s))
{
$t=mysqli_query($con,"select * from tbl_theatre where id='".$shw['theatre_id']."'");
$theatre=mysqli_fetch_array($t);
?>
<tr>
<td>
<?php echo $theatre['name'].", ".$theatre['place'];?>
</td>
<td>
<?php $tr=mysqli_query($con,"select * from tbl_shows where movie_id='".$movie['movie_id']."' and theatre_id='".$shw['theatre_id']."'");
while($shh=mysqli_fetch_array($tr))
{
$ttm=mysqli_query($con,"select * from tbl_show_time where st_id='".$shh['st_id']."'");
$ttme=mysqli_fetch_array($ttm);
?>
<button class="btn btn-default"><?php echo date('h:i A',strtotime($ttme['start_time']));?></button>
<?php
}
?>
</td>
</tr>
<?php
}
?>
</table>
<div id='display_comment'></div>
<?php
}
else
{
?>
<h3>No Show Available</h3>
<div id='display_comment'></div>
<?php
}
?>
</div>
<?php include('related-movies.php');
?>
</div>
<div class="clear"></div>
</div>
<?php include('comments.php'); ?>
</div>
</div>
<?php include('footer.php'); ?>
I'll try my best, but there is a lot to cover.
comments.php
//add the target files URL as the form's action
<form method="POST" id="comment_form" action="add_comment.php" >
//add movie to the form, that way when we insert the comment we know what its for
<input type="hidden" name="movie_id" id="movie_id" value="<?php echo $movie_id; ?>" />
//.. in your JS, add the movie id to the fetch comment call
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : <?php echo $movie_id; ?>},
dataType: 'json',
success:function(data){
//...
})
}
//move this below the function definition
load_comment();
add_comment.php
//add movie id here to match what is in the form above
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (:parent_comment_id, :comment, :comment_sender_name, :movie_id)
// add ':movie_id' => $_POST['movie_id'] to the array you have there for
// $statement->execute([ ....]). The arrays below go the same way
//add those to $statement->execute() for there respective DB calls,
You had the movie in the FIELDS part of the insert, but not the VALUES, which is probably an SQL syntax error. You may not have seen an actual error because this is called with AJAX so it would just break on the client side. You could look in the browser debug window > network [XHR] requests and look at the response. There you would probably find it or you may simply get a 500 error from the server.
fetch_comment.php
//add movie id here to match what is in the AJAX fetch comment call
SELECT * FROM tbl_comment
WHERE parent_comment_id = :parent_comment_id AND movie_id = :movie_id
ORDER BY comment_id DESC
//for execute add
['parent_comment_id'=>0, 'movie_id'=>$_POST['movie_id']]
Important prepare this query properly
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
So it should be like this:
$query = "SELECT * FROM tbl_comment WHERE parent_comment_id = :parent_id";
//then add this to execute ['parent_id' => $parent_id]
mainpage.php (not sure the name on this one)
In the last unnamed code chunk you are using mysqli but above your using PDO it's better to use one or the other, personally I prefer PDO, its just better API wise. You are also not preparing these (so convert these to PDO). Using both just adds unnecessary complexity to your application (I think there were 2 of theses in there):
$qry2=mysqli_query($con,"select * from tbl_movie where movie_id='".$_GET['id']."'");
$movie=mysqli_fetch_array($qry2);
It looks like you include the comments.php into that last page <?php include('comments.php'); ?> So what I would do is where the query is above that I said to fix:
require_once `db.php`; //- create a separate file to do the DB connection for you
//then you can add that to the top of all the pages you need the DB for
include 'header.php'; //no need for the ( ) for any of the include* or require* calls.
/*
require will issue an error if the included file is not found
include will fail silently, for things that are required for your
page to work and not produce errors use require (like the DB)
for things you only ever include once, also like the DB stuff use *_once
then no matter how many *_once calls are stacked from including
the other page you don't have to worry about it.
as above those simple rules give us require_once for the DB.
the other pages I am not sure which would be best.
*/
//localize the movie ID - change any use of `$_GET['id']
$movie_id = isset($_GET['id']) ? $movie_id : false;
if(!$movie_id){
//do something if someone goes to this page with no ?id= in the URL
//you could redirect the page
//you could have a default movie id etc...
}
$statement = $con->prepare('select * from tbl_movie where movie_id=:movie_id');
$statement->execute(['movie_id' => $movie_id]);
$movie = $statement->fetch();
//dont forget to fix the other DB call and remove the MySqli stuff.
Above I suggest using a single file for the DB, in your case it can be quite simple,
db.php
<?php $con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');
That is literally all you need then, at the very top of each page you use the DB, simply add this file
require_once 'db.php';
This way if you need to change the password or something like that, you can go to one place named in way that is easy to remember and change it. How it is now, you would have to dig though all your code to change it. In that page your including a file named header.php and it looks like from your MySQLi code that it may have some connection stuff in there. I would remove any MySQLi stuff there too. You want to keep the DB file separate as you may need to include it in the AJAX backend parts and any output from header.php would mess you up.
Summery
What I showed above is a simple example of what you need to do, in that AJAX call This may not be all you need to do, these are just the things that were obvious to me.
You don't have to worry about child comment's movie ID, as they inherit it from the parent comment, which wouldn't exist (on the page) if it had the wrong ID. In your current setup, I would still save it as part of the data. It's just you dont need it to get child comments if you know the parent (which you sort of have to know). I didn't add it into one thing that looked like it was for child comment. You can add it, but as I said above, it's not really needed.
Really the question is way to broad, why isn't my code working kind of question. The only reason I took the effort was that you also took the effort to provide well organized code that is relatively minimal.
So thank you for that.
The last suggestion I would make, is clean up the extra line returns in some of the SQL, and format the TABs a bit better. But that is just a readability issue, I am very picky about formatting my code and some of that could be related to creating an question on SO as it takes a bit of getting used the markdown they use.
Hope it helps you!
Update
thanks for your answer, I really dont know what i should post here and what i shouldnt, and the thing that i dont understand is that: i have a tbl_comment which stores all comments from user and this table include movie_id, and i have another tbl_movie which has movie_id as a primary key, how can i link the movie _id with the tbl_comment so that every comment is stored for a specific movie_id
I will try to explain the flow of your application, with an example. For the sake of this example lets say the movie id is 12 and our main page is www.example.com/movies?id=12:
Inserting a comment
User goes to a url with ?id=12
everything after the ? is called the query string
PHP knows to take the query string and populate the supper global $_GET
so in the main page your movie id is now $_GET['id']
We localize this (make a local variable) at the top of the page with some basic checks. $movie_id = isset($_GET['id']) ? $movie_id : false;
if movie id is set ?id=12 then put it in $movie_id
if its not www.example.com/movies then set $movie_id to false
this avoids some errors if someone goes to the page without that set
At the bottom of the page you include this file <?php include('comments.php'); ?> think of it like pasting that code into this place
In comments.php, which runs when it's included above,
if someone inserts a new comment (submits the form) weve added that same $movie_id into the form with this line
<input type="hidden" name="movie_id" id="movie_id" value="<?php echo $movie_id; ?>" />.
-So now when the form submits to add_comment.php which you need to put in the form's action.
<form method="POST" id="comment_form" action="add_comment.php" >
It will contain the id as $_POST['movie_id'] on that page. The $_POST['movie_id'] is basically the same as $_GET['id'] but the form method tells us its post instead of get. Typically Get is used to retrieve resources, Post is used to modify them.
When PHP runs the above piece of HTML it replaces the <?php echo $movie_id; ?> with it's value of 12 so you get this
<input type="hidden" name="movie_id" id="movie_id" value="12" />
Now On add_comment.php (where the form action takes us) we can take that $_POST['movie_id'] and add that to your SQL used to Insert the comment from the form in #4. into the Database.
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (:parent_comment_id, :comment, :comment_sender_name, :movie_id)
As this is a prepared statement we have the place holder :movie_id in the SQL query. In PDO we can feed that to the PDOStatment object ($statement) you get back from $statment=$conn->prepare($sql) by calling it's execute method or $statement->execute([..other stuff here..., 'movie_id'=>$_POST['movie_id']]).
The query that runs looks like this after PHP is done with it
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (0, 'foo', 'ArtisticPhoenix', 12) <-- see what I did there.
So you see we took the value from the original URL request, added it to our form and then we wait for user action to submit that form with the movie id embedded in it. The when the form submits it calls our add comment page, where we take it out of the Posted data, and feed it into the DB with the rest of the form data for that comment.
The other ones are exactly the same except in those we are using AJAX to submit the data so instead of a form we just add it to the AJAX call. I will give you an example of how that executes.
Showing a comment
This is the same up to #4 above
In comments.php you call load_comment(); "After" defining the function as it doesn't exist tell you do that, so you cant call it before.
This runs your AJAX request $.ajax, for the purposes of this example think of it like a fancy way to do a form. The url is the form action the method is well the method. The data is the form data, the dataType is the type of encoding in this case JSON or Javascript Object Notation. Which is a fancy way of saying structured data, as in PHP its basically an array (or data with nested elements).
The url (action) points us to fetch_comment.php, so when that runs our data: {movie_id : <?php echo $movie_id; ?>}, becomes data: {movie_id : 12}, which gets sent back to server where PHP sees it as $_POST['movie_id']
Similar to the Insert, we use that ID in our SQL query that pulls the parent comments
SELECT * FROM tbl_comment
WHERE parent_comment_id = :parent_comment_id AND movie_id = :movie_id
ORDER BY comment_id DESC
This says "Select all columns From table tbl_comment WHERE parent_comment_id IS 0 and Movie Id is 12" So it will only return comments for movie 12 that are also parents.
in your code you have just $statement->execute(); But you had the parent_comment_id hard coded as 0. This was fin until we needed to add the movie_id Once we did that it makes more senses to make it part of the prepared statement so it reads better. But like the insert, now we have place holder in place of values so we need to take that data and add it to execute for this query.
So $statement->execute(); becomes $statement->execute(['parent_comment_id'=>0, 'movie_id' => $_POST['movie_id']]); Or when PHP is done with it $statement->execute(['parent_comment_id'=>0, 'movie_id' => 12]); which the Database knows to use the keys to match the placeholders and it completes our query.
SELECT * FROM tbl_comment
WHERE parent_comment_id = 0 AND movie_id = 12
ORDER BY comment_id DESC
Then we take the results and send them back to the success handler for the AJAX with echo and in this case add it to the page with this line $('#display_comment').html(data);
So In conclusion
Your code:
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
Correct code (what I said):
//.. in your JS, add the movie id to the fetch comment call
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : <?php echo $movie_id; ?>},
dataType: 'json',
success:function(data){
//...
})
}
load_comment();
What you need to do
//$movie_id = $_GET['id'] in the main page that included this file.. #2 above
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : <?php echo $movie_id; ?>},
dataType: 'json',
success:function(data)
{
$('#display_comment').html(data);
}
});
}
load_comment();
When PHP completes the above code it sends this to the client (using 12 from our example)
//$movie_id = $_GET['id'] in the main page that included this file.. #2 above
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : 12}, //PHP takes the value of $movie_id and puts it here
dataType: 'json',
success:function(data)
{
$('#display_comment').html(data);
}
});
}
load_comment();
Above is what actually runs in the browser
That is pretty much the gist of it. As I said its more beneficial to you to learn how it works. Sure I can post the complete code but I have no way to test it, no way to know if that is all the errors or not. If you learn how it works, you will be better equipped to take on those challenges yourself. I would rather spend 3 or 4 times the effort teaching you how it all works, then to post some code that you have no idea how it works.
Hope that all makes some sense.
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 was trying to get datas from the database and put them into the array in Javascript but Javascript is not working in PHP command area.
Here is the whole PHP codes;
<?php
mysql_connect("mysql.metropolia.fi","localhost","") or die("ERROR!!");
mysql_select_db("localhost") or die("COULDN'T FIND IT!!") or die("COULDN'T FIND DB");
$sql = mysql_query("SELECT * FROM METEKSAN_HABER_CUBUGU");
$haber = 'haber';
$list = array();
$i=0;
while($rows = mysql_fetch_assoc($sql)){
$list[] = $rows[$haber];
$i++;
}
echo $i;
echo '<script type="text/javascript">
var yazi=new Array();';
echo $i;
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']="'.$list[$k].'';
}
echo '</script>';
?>
But when it comes to;
echo '<script type="text/javascript">
var yazi=new Array();';
this command line, the problem begins. Though I write 'echo $i;' after that command, I get nothing on the screen but I get the result if I write before that command. So, it means that everything works well before that command. What you think about the problem ? Why can't I starting the Javascript command ? Am I writing something wrong ?
Please give me a hand.
Thanks.
UPDATE;
I opened the web source and yeah it exactly seems there is a problem. So, I think it's better to ask that how can I write
<script type="text/javascript">
/*Example message arrays for the two demo scrollers*/
var yazi=new Array()
yazi[0]='METEKSAN Savunma, Yeni Dönemin Örnek Oyuncusu Olmaya Hazır'
yazi[1]='METEKSAN Savunma Bloomberg TVde'
</script>
this Javascript code in PHP ??
You can see my output at http://users.metropolia.fi/~buraku/Meteksan/index.php
try something like this
while($rows = mysql_fetch_assoc($sql)){
$list[] = ''.$rows[$haber].'';
}
$js_array = json_encode($list);
echo "<script>var yazi = ". $js_array . ";</script>";
It seems you are executing it currently in your browser? Then you should find your second output when opening page source, because your browser tries to executes the output as JS code. If you execute it on cli, everything should work as expected.
EDIT based on your comment:
Bullshit i wrote before, obviously. Viewing line 122 of your current html shows me a problem with your quotation marks. try the following:
for ($k = 0 ; $k < $i ; $k++){
echo 'yazi['.$k.']=\''.$list[$k].'\';';
}
In the end you should try to avoid using this kind of js rendering at all. The json_encode proposal of jeremy is the correct way to go.
You may have much more compact code:
....
$list = array()
while($rows = mysql_fetch_assoc($sql)) {
$list[] = $rows[$haber];
}
echo '<script type="text/javascript">' . "\n";
echo 'var yazi=';
echo json_encode($list,JSON_HEX_APOS | JSON_HEX_QUOT);
echo ";\n";
echo '</script>' . "\n";
What is this doing:
There's no need to count the added elements in $i, count($array) will give you the cutrrent number.. But it's not needed anyway.
Put some newlines behind the echo, better readable source
json_encode will format an JSON array from your php array, which can be directly used as source code.
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>