I'm working currently on an backend script for an projects My PHP skills are ok, I get working what I want. But everything about JS/AJAX/jQuery I did not understand.
Ok, my problem:
I have thumbnails for videos and photo sets and want to set cover photos for each. I use at the moment an popup script, that works.
But I use an admin theme (based on Bootstrap), that I purchased and it will be look much better, when I use modals and not popups.
I try many things to get my script from the popup get working into the modal - but I fail all the time.
I open the modal with
<a class="btn red btn-outline sbold" href="<?php echo $website; ?>/modals/photo_cover.php?photoid=<?php echo $row['id']; ?>" data-target="#ajax" data-toggle="modal"> Generiere Thumbnails </a>
This opens an preloader modal, that I add to my page also. I want this, because I want to add an automatic generation of thumbs in the future. So, it should be show the loader while the thumbs will be generate.
<div class="modal fade bs-modal-lg" id="ajax" role="basic" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<img src="<?php echo $website; ?>/assets/global/img/loading-spinner-grey.gif" alt="" class="loading" />
<span> Generiere Thumbnails ...</span>
</div>
</div>
</div>
</div>
Then the (external) modal will be open with my script:
<?php
include_once ('../classes/LS.php');
include_once ('../inc/config.php');
?>
<style>
label > input { visibility: hidden; position: absolute; }
label > input + img { cursor:pointer; border:2px solid transparent; }
label > input:checked + img { border:2px solid #f00; }
</style>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Galerievorschau</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "UPDATE content_pic_db SET pic_poster_file = :pic_poster_file WHERE id = :id";
$stmt = $dbh1->prepare($sql);
$stmt->bindParam(':id', $_GET['photoid']);
$stmt->bindParam(':pic_poster_file', $_POST['poster']);
$stmt->execute();
?>
<div class="portlet-body">
<div class="note note-danger"><p>Klicke auf ein Bild um es als Vorschaubild für die Galerie festzulegen.</p></div>
<div class="row">
<div class="col-sm-12 col-md-12">Das Vorschaubild wurde erfolgreich Deiner Galerie zugewiesen. Du kannst jetzt dieses Fenster schliessen.</div>
</div>
</div>
<?php } else { ?>
<div class="portlet-body">
<div class="note note-danger"><p>Klicke auf ein Bild um es als Galerievorschau festzulegen.</p></div>
<div class="row">
<form id="preview" method="POST">
<?php
if (!empty($_GET['photoid'])) {
$stmt = $dbh1->prepare('SELECT pic_count, pic_path FROM content_pic_db WHERE id = :id');
$stmt->execute(array(':id' => $_GET['photoid']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$pfad = $row['pic_path'] . '/thumbs/';
$scan = glob($pfad . "*.{jpg}",GLOB_BRACE);
for ($i = 0; $i<count($scan); $i++) {
if (strlen($scan[$i]) >= 3) {
?>
<div class="col-sm-6 col-md-6">
<label class="thumbnail">
<input type="radio" name="poster" value="<?php echo substr($scan[$i], 50); ?>" />
<img title="Klicke auf ein Bild um es als Vorschau auszuwählen" src="<?php echo $website; ?>/stream_g.php?id=<?php echo $_GET['photoid']; ?>&file=<?php echo substr($scan[$i],50); ?>" />
</label>
</div>
<?php
}
}
}
}
?>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer"><button type="button" class="btn red" data-dismiss="modal">Fenster schliessen</button></div>
<script>$('input[name=poster]').change(function () { $("#preview").submit(); });</script>
And here are starting my problem.
The modal will be open, but when I choose an image (I "replace" the radio buttons with the images) as cover, the modal will just be closed and nothing will be written to the database.
As popup everything is working, but not as modal.
I think, I have to use JS/AJAX/jQuery to write to the database. But I don't know how ... I read already a lot of tut's but I don't understand how it works.
Would be nice if someone could explain me step by step how I can get this working ...
And I need to know how to execute a script and get informed, if it is finished. As I say before, I want to add an option to generate thumbs. So I want to open the preloader modal, generate the thumbs and when it's finished it should be show the 2nd modal for choosing the cover.
you can't write in database using JS (jQuery or Ajax). It is only possible using frameworks like node.js (server-oriented js) but I think you don't have to act like this.
Native Javascript isn't a back-end language
Look, you have to use PHP to interact with databases. Javascript is a front-end language, at this level (considering we will not use node.js, this is another thing :p). So, you can considere web development like this :
FRONT END (Client side) | BACK END (Server side)
[HTML + CSS] [JS] <-->[AJAX]<--> [PHP][SQL]
If you want your page to make things dynamically, you have to build everthing in a different way.
I suggest you to considere this way of working
[HTML -> import jQuery and write ajax request] - index.html (only scripts)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="application/javascript">
$.ajax({
type: 'post',
dataType: 'json',
url: 'request.php',
success: function(data){ //Building an array using database datas directly in the body
var content = "<table><tr><th>Lastname</th><th>Firstname</th><th>Email</th></tr>";
for(i = 0; i < data.length; i++) {
content += "<tr><td>" + data[i].lastname + "</td><td>" + data[i].firstname + "</td><td>" + data[i].email + "</td></tr>";
}
content += "</table>";
document.body.innerHTML += content;
}
});
</script>
[PHP -> Requests database and return datas] - request.php
<?php
$dbname = "YOUR DATABASE NAME HERE";
$host = "DATABASE HOST ADDRESS HERE";
$user = "LOGIN USERNAME HERE";
$pass = "LOGIN PASSWORD HERE";
try {
$bdd = new PDO('mysql:host='.$host.';dbname='.$dbname.';charset=utf8', $user, $pass);
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
$table = "TABLE NAME HERE";
$colonnes = "*"; //COLUMNS TO SELECT HERE, * FOR ALL
$request = $bdd->query('SELECT ' . $colonnes . ' FROM ' . $table); //SQL QUERY
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BUILDING THE TABLE TO RETURN %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
TABLE STRUCTURE EXAMPLE :
------------------------------------
| id | lastname | firstname | email |
------------------------------------
*Line 1*
*Line 2*
*Etc...*
*/
$i = 0;
foreach($request as $req) {
$table[$i]['lastname'] = $req['lastname'];
$table[$i]['firstname'] = $req['firstname'];
$table[$i]['email'] = $req['email'];
$i++;
}
echo json_encode($table); //echo will show datas when executing this script, the ajax request will take every showed data in its success method
exit();
?>
Obviously, using this work methodology makes that each page of your website is an html file. Only the PHP scripts are using the .php extension. This is, for me, a sexier way of working ^^
Related
So basically to give a brief before exploring in to the code I give below.
Basically what I'm trying to do is, I have a modal in one of my php page as below. I'm trying to show the model from a php function "fetch_assignment_history" given below. There is a button in which we can add users to the assignment, and the button onclick event(onClick="assign(this.dataset.id)") call function passing the id from the php function to JS function.
So when the user click the button the JS function shows the modal as well as get the assignment id in the function. This assignment id is set (through JS) to data attribute of multiple select dropdown in the modal.
Now the point where I'm stuck is, a setinterval constantly fetch the assigned users. This basically collect from mysql database of users who were added to the assignment (comma delimitted id's).
When the modal is opened I want the previously assigned users to be selected in the multiple select (as per data in mysql) as default. For this I want to get the id passed from the onclick event
My HTML part (modal)
<div id="assignee" class="modal custom-modal fade" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title text-center">Assignment</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="col-md-12 col-sm-12 col-xs-12 form-group has-feedback">
<label style="color:#333D79FF; font-size:15px;">Add Users <span class="text-danger">*</span></label>
<div>
<select class="select2_multiple form-control" multiple="multiple" id="userslist" name="userslist[]" style="width: 100%;left: 10px;">
<option id="none" value="">Select Users</option>
<?php
My PHP CODE TO PULL OUT DATA FROM MYSQL DB
?>
<option value="<?php echo $id; ?>" data-useravatar="<?php echo $avatar; ?>" data-usertitle="<?php echo $firstname;echo " ";echo $lastname; ?>" data-role="<?php echo $role; ?>" data-assignment=""><?php echo $firstname;echo " ";echo $lastname; ?></option>
<?php } ?>
</select>
</div>
<div id="usersfetch"></div>
</div>
</div>
</div>
</div>
</div>
My PHP
1. function to fetch assignment history.
Below button onclick goes to JS and shows modal. and also pass id
function fetch_assignment_history($connect)
{
$query = "
SELECT * FROM assignment
WHERE id = '".$_SESSION['id']."'
ORDER BY id ASC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '<ul class="list-unstyled">';
foreach($result as $row)
{
$user_name = '';
$dynamic_background = '';
$message = '';
$assignmentname = $row["assignmentname"];
$name = $row["name"];
$id = $row['id'];
$output .= '
<div class="x_panel" style=" font-size:14px;">
<span class="controlbuttons">
<button class="btn btn-round" data-id="'.$id.'" onClick="assign(this.dataset.id)"><i class="material-icons" title="Assign">person_add</i></button>
</span>
</div>
';
}
$output .= '</ul>';
return $output;
}
function to assigned user history
function fetch_assigned_user_history($connect)
{
some php queries
}
My JS
I want the assignid from function assign(assignid) to be called from function fetch_assigned_user_history(). How do I accomplish this??????
setInterval(function(){
fetch_assigned_user_history();
}, 1000);
function assign(assignid)
{
var assignid = assignid;
$("#assignee").modal("show");
$('#userslist').data("assignment",assignid);
}
function fetch_assigned_user_history()
{
var action = "fetch_assigned_user_data";
var getid = ;// I need to get the ID from the previous function from onclick event function assign(assignid)
$.ajax({
url:"assignment.php",
method:"POST",
data:{action:action, assignmentid:getid},
success:function(data)
{
$('#usersfetch').html(data);
}
})
}
Hope I'm clear with my question. Appreciate for an advise to fix.
To summarise, the basic question is how to call variable of one JS function in to another (in this example id's) so that i can get the list of users in that assignment? Also how to get it selected by default the Multiple select with database values.
You already stored 'assignid' in data-* attribute, you can just retrieve it when you need it
function assign(assignid) {
var assignid = assignid;
$("#assignee").modal("show");
// You already store your assignid at here
$('#userslist').data("assignment",assignid);
}
function fetch_assigned_user_history()
{
var action = "fetch_assigned_user_data";
// Now you just need to retrieve it
var getid = $('#userslist').data("assignment");
$.ajax({
url:"assignment.php",
method:"POST",
data:{action:action, assignmentid:getid},
success:function(data)
{
$('#usersfetch').html(data);
}
})
}
I am making a comment system for my blog that I am creating and currently I have two problems with it. The form appears under every post. But only works on the top post. The rest of the forms simply don't work.
The another problem I have is that I'm using ajax and the form does add the record to SQL but I still have to refresh my page for it to show. I want it to show automatically straight away after it is added.
tl:dr
Two problems:
The only form that works is the first one under the first post, the rest simply don't work
Ajax doesn't automatically show the comments, need to refresh to seem them
Code:
JQuery
function post()
{
var comment = document.getElementById("comment").value;
var name = document.getElementById("name").value;
var mail = document.getElementById("mail").value;
var post_id = document.getElementById("post_id").value;
if(comment && name && mail)
{
$.ajax
({
type: 'post',
url: 'php/comment.php',
data:
{
user_comm:comment,
user_name:name,
user_mail:mail,
post_id:post_id,
},
success: function (response)
{
document.getElementById("comments").innerHTML=response+document.getElementById("comments").innerHTML;
document.getElementById("comment").value="";
document.getElementById("name").value="";
document.getElementById("mail").value="";
}
});
}
return false;
}
Index.php
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysql_query('SELECT * FROM `posts` ORDER BY id DESC') or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$id_post = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
echo " <!-- Blog Post Content Column -->
<h1> " . $row['post_title'] . " </h1><p class='lead'>
by <a href='#'>Matt</a></p> <hr>
<p><span class='glyphicon glyphicon-time'>" . $row['date_created'] . "</span></p>
<img class='img-responsive' style='width: 900px;height: 300px;' src=" . $row['post_img'] . "> <hr>
<p class='lead'>" . $row['post_first'] . "</p>
<p>" . $row['post_second'] . "</p> <hr>";
?>
<!-- Comments Form -->
<div class='well'>
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method='post' onsubmit="return post();">
<input type='hidden' id='post_id'name='post_id' value='<?php echo $id_post; ?>'>
<div class='form-group'>
<input type="text" id="name" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type='text' id='comment' name='comment' class="form-control" rows='3'></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<?php
$resultcomments = mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post' ORDER BY `date` DESC") or die(mysql_error());
while($affcom = mysql_fetch_assoc($resultcomments)){
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<!-- Posted Comments -->
<div id='comments'class='media'>
<a class='pull-left' href='#'>
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'><?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
}
?>
</div>
comment.php
include_once('../../acp/db/db.php');
$link = mysql_connect($dbhost, $dbuser, $dbpassword, $dbname);
mysql_select_db($dbname);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if(isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail']))
{
$comment=$_POST['user_comm'];
$name=$_POST['user_name'];
$mail=$_POST['user_mail'];
$post_id=$_POST['post_id'];
$insert=mysql_query("INSERT INTO comment (name,mail,comment,post_id) VALUES ('$name', '$mail', '$comment', '$post_id')");
$select=mysql_query("SELECT * FROM `comment` WHERE post_id = '$id_post' ORDER BY `date` DESC");
if($row=mysql_fetch_array($select))
{
$name=$row['name'];
$comment=$row['comment'];
$date=$row['date'];
?>
<div class='media'>
<a class='pull-left' href='#'>
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'><?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
exit;
}
?>
This is the first time I am playing around with AJAX :) so be easy on me Any help will be appreciated.
I tested all your code. It's working now. I commented it overall, so search after "NB" (lat. for "Nota bene") in codes, in order to see were I made relevant changes. I'll describe here some problems with it and I'll also give you some recommendations - if I may. At last I'll insert the three corrected pages.
Problems:
One big problem was, that you were using the $id_post variable in
the SELECT sql statement (in comment.php), which does not exist
in comment.php code.
Other problem: DOM elements had same ids. The DOM elements inside
loop-forms must have unique id attributes. You must always have
unique id attributes in html elements. Give them the form
id="<early-id><post_id>" for example.
There were also other problems in more places. I commented overall,
so you'll have to read my codes.
Recommendations:
Use mysqli_ instead of mysql_ functions, because mysql
extension were completely removed from PHP >= 7.0.
Use exception handling, especially when dealing with db access.
Don't write HTML code from inside php. Alternate php with html if you
wish, but don't do echo "<div class=...></div>" for example. This
is actually very important if you use an IDE which can format your
html code. If this code is inside php, you have no chance for this
beautifying process. therefore you can miss important html-tags
without knowing it, because your IDE didn't showed you where tags are
really missing in page.
In html tags: use same name as id. Example: id=mail<?php echo
$post_id; ?>, name=mail<?php echo $post_id; ?>. Exception: radio
buttons, checkboxes and all tags which can form a group. Then, each
tag would have a unique id, but all of them would receive the same
name.
Use '' overall and "" inside them. Maintain this "standard", you'll see it's a lot better than the inverse.
Corrected pages:
Index.php:
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
<!-- NB: Added my scripts for testing -->
<link href="Vendor/Bootstrap-sass-3.3.7/Bootstrap.css" rel="stylesheet" type="text/css" />
<script src="Vendor/jquery-3.1.0/jquery.min.js" type="text/javascript"></script>
<script src="Vendor/Bootstrap-sass-3.3.7/assets/javascripts/bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-8">
<?php
$result = mysqli_query($con, 'SELECT * FROM `posts` ORDER BY id DESC');
if (!$result) {
throw new Exception('The query could not be executed!');
}
while ($row = mysqli_fetch_array($result)) {
// NB: Unified $post_id name overall (instead of $id_post).
$post_id = $row['id'];
$post_title = $row['post_title'];
$post_date = $row['date_created'];
$post_img = $row['post_img'];
$post_first = $row['post_first'];
$post_second = $row['post_second'];
?>
<!-- Blog Post Content Column -->
<!--
NB: Extracted html code from php and added here, where it should be.
-->
<h1>
<?php echo $post_title; ?>
</h1>
<p class="lead">
by Matt
</p>
<hr/>
<p>
<span class="glyphicon glyphicon-time">
<?php echo $post_date; ?>
</span>
</p>
<img class="img-responsive" style="width: 1200px; height: 100px;" src="<?php echo $post_img; ?>">
<hr/>
<p class="lead">
<?php echo $post_first; ?>
</p>
<p>
<?php echo $post_second; ?>
</p>
<hr/>
<!-- Comments Form -->
<div class="well">
<h4>Leave a Comment:</h4>
<div class="new-com-cnt">
<form method="post" onsubmit="return post('<?php echo $post_id; ?>');">
<!--
NB: Deleted hidden input (not needed!) and was missing post_id in "id" attribute!
So: transfered post_id value to post() function as argument. See js too.
-->
<!--
NB: Added post_id to the "id" attributes. See js too.
-->
<div class="form-group">
<input type="text" id="name<?php echo $post_id; ?>" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail<?php echo $post_id; ?>" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea type="text" id="comment<?php echo $post_id; ?>" name="comment" class="form-control" rows="3"></textarea>
</div>
<input type="submit" value="Post Comment">
</form>
</div>
</div>
<hr>
<!--
NB: Added new "comments" outer-container in order to append
new comment to it and added post_id value into its "id" attribute.
See the js too.
-->
<div id="comments<?php echo $post_id; ?>" class="comments-container">
<?php
$resultComments = mysqli_query($con, 'SELECT * FROM `comment` WHERE post_id = ' . $post_id . ' ORDER BY `date` DESC');
if (!$resultComments) {
throw new Exception('The query could not be executed!');
}
while ($affcom = mysqli_fetch_assoc($resultComments)) {
$name = $affcom['name'];
$email = $affcom['mail'];
$comment = $affcom['comment'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<!-- Posted Comments -->
<!--
NB: deleted id attribute "comments", because I added an outer
container to hold the insert results, e.g. the div
with the class "comments-container".
-->
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="<?php echo $grav_url; ?>" >
</a>
<div class="media-body">
<?php echo $name; ?>
<h4 class="media-heading">
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
?>
</div>
<?php
}
?>
</div>
</div>
</div>
</body>
</html>
<?php
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
comment.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NB: TITLE</title>
</head>
<body>
<?php
try {
$con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
if (!$con) {
throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
}
if (isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail'])) {
$comment = $_POST['user_comm'];
$name = $_POST['user_name'];
$mail = $_POST['user_mail'];
$post_id = $_POST['post_id'];
// NB: NEW. CHANGE THIS TO YOUR wished DATE FORMAT.
// Use UNIX timestamps for dates, so that you make good date calculations.
$date = date("Y-m-d");
// NB: INSERT DATE IN DB TOO, so that you can select by date desc down under.
$insert = mysqli_query($con, "INSERT INTO comment (name,mail,comment,post_id, date) VALUES ('$name', '$mail', '$comment', '$post_id', '$date')");
if (!$insert) {
throw new Exception('The query could not be executed!');
}
// NB: Replaced $id_post with $post_id.
$select = mysqli_query($con, "SELECT * FROM `comment` WHERE post_id = '$post_id' ORDER BY `date` DESC");
if (!$select) {
throw new Exception('The query could not be executed!');
}
if ($row = mysqli_fetch_array($select)) {
$name = $row['name'];
// NB: Added email, because it wasn't provided.
$email = $row['mail'];
$comment = $row['comment'];
$date = $row['date'];
// NB: It wasn't provided, so I added the same value as in index.php.
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
?>
<div class="media">
<a class='pull-left' href='#'>
<!--
NB: Where is your $grav_url value?! I added one of mine for testing.
-->
<img class='media-object' src=' <?php echo $grav_url; ?>' >
</a>
<div class='media-body'>
<?php echo $name; ?>
<h4 class='media-heading'>
<small><?php echo $date; ?></small>
</h4>
<?php echo $comment; ?>
</div>
</div>
<?php
}
// NB: Don't use exit(). Let the code flow further, because
// you maybe want to close the db connection!
// exit();
}
$closed = mysqli_close($con);
if (!$closed) {
throw new Exception('The database connection can not be closed!');
}
} catch (Exception $exception) {
// NB: Here you should just DISPLAY the error message.
echo $exception->getMessage();
// NB: And here you should LOG your whole $exception object.
// NB: Never show the whole object to the user!
// echo '<pre>' . print_r($exception, true) . '</pre>';
exit();
}
?>
</body>
</html>
Javascript file:
// NB: Added post_id as parameter. See form too.
function post(post_id) {
// NB: Added post_id value to the "id" attributes. See form too.
var comment = document.getElementById("comment" + post_id).value;
var name = document.getElementById("name" + post_id).value;
var mail = document.getElementById("mail" + post_id).value;
if (comment && name && mail) {
$.ajax({
type: 'post',
url: 'php/comment.php',
data: {
user_comm: comment,
user_name: name,
user_mail: mail,
post_id: post_id
},
success: function (response) {
// NB: Comments-post_id is now an outer container. See form.
// NB: Added post_id value to the "id" attributes. See form too.
document.getElementById("comments" + post_id).innerHTML = response + document.getElementById("comments" + post_id).innerHTML;
document.getElementById("comment" + post_id).value = "";
document.getElementById("name" + post_id).value = "";
document.getElementById("mail" + post_id).value = "";
}
});
}
return false;
}
// ******************************************************************************
// NB: Recommendation:
// ******************************************************************************
// Use jquery and ajax instead of vanilla javascript. It's no problem anymore ;-)
// Use done, fail, always instead of success, error, ....
// ******************************************************************************
//function post(post_id) {
// var comment = $('#comment' + post_id);
// var name = $('#name' + post_id);
// var mail = $('#mail' + post_id);
//
// if (comment && name && mail) {
// var ajax = $.ajax({
// method: 'POST',
// dataType: 'html',
// url: 'php/comment.php',
// data: {
// user_comm: comment.val(),
// user_name: name.val(),
// user_mail: mail.val(),
// post_id: post_id
// }
// });
// ajax.done(function (data, textStatus, jqXHR) {
// var comments = $("#comments" + post_id);
//
// // NB: I'm not sure, not tested, too tired :-) Please recherche.
// comments.html(data + comments.html());
//
// comment.val('');
// name.val('');
// mail.val('');
// });
// ajax.fail(function (jqXHR, textStatus, errorThrown) {
// // Show error in a customized messages div, for example.
// $('#flashMessage').val(textStatus + '<br />' + errorThrown);
// });
// ajax.always(function (data, textStatus, jqXHR) {
// //...
// });
// }
//
// return false;
//}
// ******************************************************************************
Good luck.
Your parent loop is generating several comments form and they all have the same id. Ids are supposed to be unique for the whole document. refer this. Perhaps this is causing other comment forms not to work except the first one.
Your second problem is not an issue. It is general behavior of how server works. When you are using ajax, it is sending data to the server which stores it in the database. Server's job is done. It cannot send the data back to the page and update the page content without refreshing the page. You can initiate another ajax call after posting to server in order to refresh the content of the page.
And though it is not related to the question. Try to be consistent with your use of single quotes and double quotes. You shouldn't randomly choose them. Decide on one and use them consistently. And yes do try to learn PDO or mysqli. I will suggest PDO.
I currently have a page where I'm connecting to db via PDO, db, prepare.
Selecting SQL_CALC_FOUND_ROWS in order to have pagination with the results.
All of that is good. However, each return is to have a text popup when clicked. Thats where I want to target a particular field of defined row.
Code I have is as follows :
$db = new PDO('mysql:dbname=###;host=###','###','###');
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ?(int)$_GET['per-page'] : 8;
//Positioning
$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
//Query
$articles = $db->prepare("
SELECT SQL_CALC_FOUND_ROWS id, comment_caption, comment_sub_caption,comment_title, comment_main, comment_name,
comment_date, comment_url
FROM TABLE_NAME
LIMIT {$start}, {$perPage}
");
$articles->execute();
$articles = $articles->fetchAll(PDO::FETCH_ASSOC);
// Pages
$total = $db->query("SELECT FOUND_ROWS() as total")->fetch()['total'];
$pages = ceil($total / $perPage);
//Pagination div
<div class="pagination">
<?php for($x = 1; $x <= $pages; $x++): ?>
<a href="?page=<?php echo $x; ?>&per-page=<?php echo $perPage; ?> "<?php if($page === $x){ echo 'class="selected"'; }?>><?php echo $x ?></a>
<?php endfor; ?>
</div>
// Here is the container for the foreach
<div id="container">
<?php
foreach($articles as $article): ?>
<div class="item small">
<div class="module">
<div class="article">
<div class="item-inner">
<a href="<?php echo $article['comment_url']; ?>">
<div class="project-title">
<div class="mid">
<h2><?php echo $article['comment_caption']; ?></h2>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
// This is the popup that I want to associate with each return
<div id="test-popup" class="white-popup mfp-hide">
<blockquote><?php echo $article['comment_main'];
?></blockquote>
<p><i><?php echo $article['comment_name']; ?> - <?php echo $article['comment_date']; ?></i></p>
</div>
In the popup, I want to echo the 'comments_main, comments_name & comments_date' field of the particular instance that is clicked. Here currently, it just echos the first row.
I'm not sure what the best way to go about it is... ?
Any help would be greatly appreciated.
This is not really a php-mysql related question, but rather a javascript-html-css related one.
You have 2 options:
You output the comments_main, comments_name & comments_date fields to all listed items in a way they are not visible to the users first in the browser. Typically, you could use the anchor element's title property, or html5's data- properties, or even a list of invisible divs. Whenever the user clicks a link, you use javascript to fetch these data for the given comment from your list on the client side (if they are not stored in a list of divs already) and make it appear.
You do not output these data to the client, but upon clicking you use an ajax call to retrieve these data from the server via another php page.
For both approach there are lots of tutorials out there with designed boxes (tooltips) and copy-paste javascript, html, and css code.
so I'm making a pagination which uses 3 different files. The page itself (index.php), the header which contains a JS Ajax scripts for changing page which is included in the index.php (header.php) and a pagination script contained in a separate PHP file which is called via the AJAX script (pagination.php).
In the index.php I have a variable which defines the category the user is currently in named $category, I would like this variable to be used in the pagination.php to select what results are shown (Only results where subcategory2 = $category).
Because pagination.php is called through an ajax script on document ready it can't see that variable. Is there any way for the two to communicate without the use of Session (which would mess up when changing to other categories) or include (which would end up calling the script twice).
Header.php:
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("/includes/pagination.php");
$(".pagination").bootpag({
total: <?php echo $pages; ?>,
page: 1,
maxVisible: 5
}).on("page", function(e, num){
e.preventDefault();
$("#results").prepend('<div class="loading-indication"><img src="/images/ajax-loader.gif" style="width: 2em; margin: 0 auto;" /><br />Loading...</div>');
$("#results").load("/includes/pagination.php", {'page':num});
});
});
</script>
Pagination.php
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
//sanitize post value
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
$page_number = 1;
}
echo $category;
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($mysqli, "SELECT ProductID, SupplierID, ProductName, ProductDesc, ProductURL, Image1URL, Image2URL, Image3URL, Image4URL, Image5URL, ProductCondition, Stock, AvailabilityDate, ProductGTIN, ProductMPN, ProductBrand, ProductGroupID, ProductColour, ProductGender, ProductAgeGroup, ProductMaterials, ProductSize, ProductPSize, Feature1, Feature2, Feature3, Feature4, Feature5, Feature6, Feature7, Feature8, Feature9, Feature10, CostPrice, Markup, Offer, Shipping, ShippingWeight, ShippingLabel FROM products ORDER BY productid ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '
<table id="productbox">
<tr>
<th class="producthead" colspan="3">'.$row["ProductName"].'</th>
</tr>
<tr>
<td class="productimgcell"><img src="'.$row["Image1URL"].'" class="productimg" /></td>
<td class="productinfo">'.$row["Feature1"].'<br />'.$row["Feature2"].'<br />'.$row["Feature3"].'</td>
<td class="productprice"><div class="pricebg">'; echo price_calc($mysqli, $row["ProductID"], $row["CostPrice"], $row["Markup"], $row["Offer"]); echo '<span class="priceinfo">inc. VAT</a></div><div style="clear:both;"></div><div class="addtocartbg">Add To Cart</div></td>
</tr>
<tr>
<td class="productfoot" colspan="3">5/5 Stars - Write A Review</td>
</tr>
</table><br />
';
}
echo '</ul>';
?>
Index.php
<?php
$category = 'AMD';
global $category;
$page_title = 'AMD Motherboards - Motherboards - PC Components';
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
$results = mysqli_query($mysqli,"SELECT COUNT(*) FROM products WHERE SubCategory2 = '$category'");
$get_total_rows = mysqli_fetch_array($results);
$pages = ceil($get_total_rows[0]/$item_per_page);
include_once($_SERVER['DOCUMENT_ROOT'].'/template/header.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/template/sidemenu.php');
?>
<div class="contentboxcontainer">
<div class="centercontentbox">
<div class="halfcontentboxcontainer">
<div class="halfcontentbox">
<div class="contenthead">Deals</div>
<div class="content">
<div class="contentcontainer">
Test
</div>
</div>
</div>
</div>
<div class="halfimgcontentboxl">
<img src="https://assets.vg247.com/current//2015/07/battlefront_leaked_alpha_tatooine_4.jpg" style="border-radius: 5px; width: 100%;" />
</div>
</div>
</div>
<div class="contentboxcontainer">
<div id="contentbox">
<div class="contenthead">Products</div>
<div class="content">
<div id="results"></div>
<div class="pageswrap"><div class="pagination"></div> <div style="clear:both;"></div></div>
</div>
</div>
</div>
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/template/footer.php');
?>
Send the category id as a post variable in the load command.
var cat = <?php echo $category; ?>
$("#results").load("/includes/pagination.php", {'page':num , 'category':cat});
For anyone else interested in an answer for this, I'm going to post my work around just in case anyone might find it useful.
In my pagination.php I added a check for the current page the user is on and compared that to a url I define. If the user is on said page then I define the category there.
pagination.php
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
if ($_SERVER['HTTP_REFERER'] == $domainurl.'/store/pc-components/motherboards/amd/') {
$category = 'AMD';
}
I had to use $_SERVER['HTTP_REFERER'] due to it being called from JS and $domainurl is defined in my config file (which is included in db_connect.php).
I can now call my variable in a mysql query on pagination.php
FROM products WHERE SubCategory2 = '".$category."'
Not the cleanest of work arounds but it saved me worrying about having to rethink the way I was doing it all.
Here is something that seems to be having repetition problem with. I want to open a content into a modal from a remote page, which is populated from a MySql database. I also want that modal to be opened with my custom styling etc. I have gone so far with it, but after that I have got stuck. Here is the code so far
the output on the page:
$output .='<h4><a class="md-trigger" data-OfferID="' . $offer_id . '" href="#" data-modal="offer_modal">' . $title . '</a></h4><hr>';
the modal where data is loaded, on click of output (located in footer.php):
<div id="offer_modal" class="md-modal md-effect-flip" aria-hidden="true">
<div class="md-content">
</div>
</div>
the script located in the page where $output is echoed:
$('.md-trigger').click(function(){
var OfferID=$(this).attr('data-OfferID');
$.ajax({url:"Open-Offer.php?OfferID="+OfferID,cache:false,success:function(result){
$(".md-content").html(result);
}});
});
and just as a reference, the remote page which loads the data based on id, and then populates modal:
<?php
extract($_GET);
?>
<?php
require('inc/connect/config.php');
$offer = (int) $_GET['OfferID']; ?>
<?php
try {
$code_sql = 'SELECT * FROM codes WHERE id LIKE :code_id';
$query = $db->prepare($code_sql);
$code_params = array(':code_id' => $offer);
$query->execute($code_params);
$code_r = $query->fetch(PDO::FETCH_ASSOC);
$c_title = $code_r['title'];
$c_desc = $code_r['description'];
$c_redeem = $code_r['redemption'];
$c_textcode = $code_r['textcode'];
$c_exp = $code_r['expiry'];
$c_terms = $code_r['terms'];
$c_url = $code_r['url'];
} catch (PDOException $e) {
echo "failed to load offer";
exit;
}
?>
<button type="button" class="close close-md" data-dismiss="modal" aria-label="Close"><h3><span aria-hidden="true">×</span></h3></button>
<h5><?php echo $c_title; ?></h5>
<p><?php echo $c_desc; ?></p>
<h3><?php echo $c_textcode; ?></h3>
<p><?php echo $c_redeem; ?></p>
<p class="small-text"><?php echo $c_terms; ?></p>
At the moment, the problem I am getting is the modal only loads once, when the top item in the list is clicked, it won't load when clicking any other item in the list... what am i doing wrong!! I am pretty new to all of this, so go easy on me please :)
thanks in advance
Kaylee
Test with this example.
$('.md-trigger').on('click',function(){
var OfferID=$(this).attr('data-OfferID');
$.ajax({url:"Open-Offer.php?OfferID="+OfferID,cache:false,success:function(result){
$(".md-content").empty().append(result);
}});
});