my bootstrap modal turns out blank after adding ajax - php

I've got a problem adding ajax to my code. I'm trying to make my photogallery so I can put in images filtered by categories trough a form. After I put in ajax, my modal turns out blank like this:
But somehow it does display the thumbnail picture. It seems to not take the target id's of the modal.
Here's my ajax code:
function fotoalbumfilter() {
$.ajax({
url: '../ajax/fotoalbumfilter.php',
data: {
categorie: $('#fotoalbumfilter').val()
},
type: "POST",
dataType: 'json'
}).done(function(result) {
var jsonResult = result;
var outputgallery = jsonResult.outputgallery;
$('#output-gallery').html(outputgallery);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
});
};
$(document).ready(function() {
fotoalbumfilter();
});
my php code:
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) { die();}
require_once('../app_config.php');
if($_POST['categorie']){ $categorie = $_POST['categorie']; }else{ $categorie = ''; }
$result = array();
if($categorie == ''){ $fotos = ''; }else{ $fotos = "WHERE (categorie_id = '".$categorie."')"; }
$r = 0;
$querycategorie = mysqli_query($con, "SELECT * FROM fotos ".$fotos." ORDER BY timestamp ASC");
while($uitkomst = mysqli_fetch_array($querycategorie)){
$weergave = 1;
$titel = $uitkomst['titel'];
$foto = $uitkomst['naam'];
$r++;
if($r == 1){ $outputgallery = '<div class="row">'; }
$outputgallery .= '<div class="col-lg-3 col-sm-4 col-md-4 col-xs-6 fotocontaineralbum">
<a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="'.$titel.'" data-image="/images/fotoalbum/'.$foto.'" data-target="#image-gallery">
<img class="img-fluid" src="/images/fotoalbum/'.$foto.'">
</a></div>';
if($r == 4){ $outputgallery .= '</div>'; $r = 0; }
}
if($r !== 0){ $outputgallery .= '</div>'; }
$outputgallery = utf8_encode($outputgallery);
$result['outputgallery'] = $outputgallery;
echo json_encode($result);
and my html (with php dropdown):
<div class="container">
<div class="col-md-12 pagecontainer container">
<div class="row">
<div class="col-md-12">
<center><h2><span class="impactfont mcorange" style="margin:20px;">Het Fotoalbum</span></h2></center>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="categoriecontainer impactfont">
<select class="categoriedropdown" onchange="fotoalbumfilter()" id='fotoalbumfilter'>
<option>Kies een categorie</option>
<?php
mysqli_query($con, "SET CHARACTER SET utf8_general_ci");
$query = mysqli_query($con, "SELECT * FROM foto_categorie ORDER BY 'id' ASC") or die (mysqli_error($con));
while($uitkomst = mysqli_fetch_array($query)){
$categorie = $uitkomst["categorie"];
$id = $uitkomst["id"];
?>
<option value="<?php echo $id; ?>"><?php echo $categorie;?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="col-md-12 padding20 pagecontent">
<div id="output-gallery">
</div>
</div>
</div>
</div>
<div class="modal fade" id="image-gallery" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="image-gallery-title"></h4>
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
</div>
<div class="modal-body">
<img id="image-gallery-image" class="img-fluid" src="">
</div>
<div class="modal-footer">
<div class="col-md-2 floatl">
<button type="button" class="btn btn-primary floatl" id="show-previous-image">Previous</button>
</div>
<div class="col-md-8 text-justify" id="image-gallery-caption">
</div>
<div class="col-md-2 floatr">
<button type="button" id="show-next-image" class="btn btn-default floatr">Next</button>
</div>
</div>
</div>
</div>
</div>

The issue is that you do not instruct the modal to update its contents. You can do so by adding the following javascript next to your existing one. Basically this updates the contents of the modal depending on which button was clicked. The functionality is explained in detail in the Bootstrap docs under the Varying modal content section.
$('#image-gallery').on('show.bs.modal', function (event) {
var thumbnail = $(event.relatedTarget),
imageSrc = thumbnail.data('image');
$('#image-gallery-image').attr('src', imageSrc);
});

Related

Get a value inside a modal PHP HTML

This is my code, i was supposed to get the "$pw" outside the modal.. But it seems that i can't get the value of it and Also i can't seem to fetch the "$errMSG" value.. If it's if($pin != $pww) cant get the err MESSAGE.. Really need some help.. Thank you!
This is my "$pw" code, its on the same page as my modal..
<?php
include('connectdb.php');
$sql = "SELECT * FROM accounts WHERE usernamee='$userid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($data = $result->fetch_assoc()) {
$pww = $data['passwordd'];
}
}
?>
This is my modal code:
<div class="container">
<form method="post">
<h2>Enter your Pin Number</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Enter your Pin Number</h4>
</div>
<div class="modal-body text-center">
<input type="password" id="first-name" required="required" class="form-control" name="pin">
<?php
if(isset($errMSG)){
?>
<div class="alert alert-danger">
<span class="glyphicon glyphicon-infos-sign"></span> <strong><?php echo $errMSG; ?></strong>
</div>
<?php
}
else if(isset($successMSG)){
?>
<div class="alert alert-success">
<strong><span class="glyphicon glyphicon-info-sign"></span> <?php echo $successMSG; ?></strong>
</div>
<?php
}
?>
</div>
<div class="modal-footer">
<button type="submit" name="submit3" class="btn btn-default"><i class="fa fa-key"></i> Confirm Pin</button>
</div>
</div>
</div>
</div>
<!-- START OF PHP -->
<?php include ('connectdb.php');
if(isset($_POST['submit3']))
{
$pin = $_POST["pin"];
if ($pin != $pww) {
$errMSG= "WRONG PIN.. TRY AGAIN..";
}
else{
header('Location: myorders.php');
}
} // SUBMIT
?>
</form>
</div>
include('connectdb.php');
$pww = '';
$sql = "SELECT * FROM accounts WHERE usernamee='$userid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($data = $result->fetch_assoc()) {
$pww = $data['passwordd'];
}
}
Try this code, You should declare pww before your if or while brackets, to get acces to this variable.

Create a session variable when user clicks a button inside a loop

I have a button inside a loop.
When the user clicks on the button I want to create a $_SESSION variable with the value of a variable inside the loop.
For example, the variable $id_puja is 767 at this loop item, when the user clicks on the button I want to create the session variable $_SESSION['clicked_puja'] = $row['id_puja'].
This is the button:
while{...
$id_puja = $row['id_puja'];
...
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
...
}
I
EDITED, full loop code:
<?php
$resultadopujas=0;
global $mysqli;
$loop = mysqli_query($mysqli, "SELECT * FROM tb_pujas
WHERE subasta_puja = '".$subasta."'")
or die (mysqli_error($mysqli));
$orden = 0;
$resultado = $loop ->num_rows;
if ($resultado == 0){
?> <div class="container">
<div class="jumbotron">
<div class="row">
<div class="col-md-6">
<p><?php echo $resultado."NO HAY PUJAS"?></p>
</div>
</div>
</div>
</div>
<?php
}
$numpuja=0;
while ($row = mysqli_fetch_array($loop))
{$numpuja = $numpuja+1;
$originalDate = $row['datetime_puja'];
$newDate = date("d-m-Y H:i:s",strtotime($originalDate))
?>
<div class="container">
<div class="jumbotron" style="background-color: white">
<div class="row">
<div class="col-md-2">
<img style="width: 80px;height: auto;align-self: " src="garantia.png">
</div>
<div class="col-md-2">
<img style="width: 80px;height: auto;align-self: " src="ok.png">
</div>
<div class="col-md-2">
<img style="width: 80px;height: auto;align-self: " src="extra.png">
</div>
<div class="col-md-2">
<p><strong>Dia/Hora puja: </strong><?php echo $newDate?></p>
</div>
<div class="col-md-2">
<p><strong>Precio puja: </strong><?php echo $row['precio_puja']." €"?></p>
</div>
<div class="col-md-2">
<p><?php echo "<strong>Puja núm:</strong> ".$numpuja?></p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p><?php echo "<strong>Comentarios:</strong> ".$row['comentarios_puja']?></p>
</div>
</div>
<div class="row">
<div class="col-md-4">
<img style="width: 100%;height: auto;align-self: " src="https://cribbeo.com/pujas/<?php echo $row['foto1']?>">
</div>
<div class="col-md-4">
<img style="width: 100%;height: auto;align-self: " src="https://cribbeo.com/pujas/<?php echo $row['foto2']?>">
</div>
<div class="col-md-4">
<img style="width: 100%;height: auto;align-self: " src="https://cribbeo.com/pujas/<?php echo $row['foto3']?>">
</div>
</div>
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-4">
</div>
<div class="col-md-4">
<script>
function myclick(){
alert (<?php echo $row['precio_puja']?>);
}
</script>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" id="boton" onclick="myclick()" data-target="#myModal">Open Modal</button>
</div>
</div>
</div>
</div>
</div>
<?php
}
?>
EDITED modal part
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Mensajes de la subasta <?php echo $referencia."VAR=".$_COOKIE['puja']?></h4>
</div>
<div class="modal-body" style="background-color:#486A86; color: white">
<div class="container">
<header class="header">
<h1>Chat</h1>
</header>
<main>
<img src="images/logohorizontal.png" alt="Cribbeo" width="200px">
<div class="userSettings">
<label for="userName">Usuario: <?php echo $_SESSION['usuario']?></label>
<input id="userName" type="hidden" placeholder="Username" maxlength="32" value=" <?php echo $_SESSION['usuario']?>">
</div>
<div class="chat">
<div id="chatOutput"></div>
<input id="chatInput" type="text" style="background-color:white; color: #486A86" placeholder="Escribe aquí el texto de tu mensaje" maxlength="128">
<button id="chatSend" style="background-color:#486A86; color: white">Enviar</button>
</div>
</main>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
And this is chat.js
$(document).ready(function() {
var chatInterval = 250; //refresh interval in ms
var $userName = $("#userName");
var $chatOutput = $("#chatOutput");
var $chatInput = $("#chatInput");
var $chatSend = $("#chatSend");
function sendMessage() {
var userNameString = $userName.val();
var chatInputString = $chatInput.val();
$.get("./write.php", {
username: userNameString,
text: chatInputString
});
$userName.val("");
retrieveMessages();
}
function retrieveMessages() {
$.get("./read.php", function(data) {
$chatOutput.html(data); //Paste content into chat output
});
}
$chatSend.click(function() {
sendMessage();
});
setInterval(function() {
retrieveMessages();
}, chatInterval);
});
Try this-
//START OF LOOP...
//Add data-var attribute to your button to store the value of the session variable to be picked up by jQuery.
<button type="button" class="btn btn-info btn-lg session-btn" data-toggle="modal" data-target="#myModal" data-var="<?php echo $id_puja;?>">Open Modal</button>
//END OF LOOP..
// jQuery CDN link
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script>
$('.session-btn').on('click', function(){
var session_var = $(this).data('var');
console.log(session_var); // prints the session variable value to the console.
$(document).ready(checkModal);
function checkModal() {
if($('#myModal').is(':visible')){
//if the modal is visible on the page
$.ajax({
url: 'read.php',
type: 'POST',
data: {session_var: session_var},
success: function(){
alert('success');
}
});
}
}
});
</script>
In read.php file
<?php
require("connect.php");
session_start():
//connect to db
$db = new mysqli($db_host,$db_user, $db_password, $db_name);
if ($db->connect_errno) {
//if the connection to the db failed
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
if(isset($_POST['session_var'])){
$_SESSION['session_var'] = $_POST['session_var'];
echo $_SESSION['session_var'];
$query="SELECT * FROM chat WHERE id_puja ='".$_SESSION['session_var']."' ORDER BY id ASC";
//execute query
if ($db->real_query($query)) {
//If the query was successful
$res = $db->use_result();
while ($row = $res->fetch_assoc()) {
$username=$row["username"];
$text=$row["text"];
$time=date('G:i', strtotime($row["time"])); //outputs date as # #Hour#:#Minute#
echo "<p>$time | $username: $text</p>\n";
}
}else{
//If the query was NOT successful
echo "An error occured";
echo $db->errno;
}
} else {
echo 'variable is not posted!';
}
$db->close();
?>

ajax return response with jquery

i want to display a full div modal in bootstrap 4 with ajax/PHP response. I have a php code that contains the #ofTheLinkCallAction
<p class="post-content white-text btn-2">' . $contents_brand[ 'detail_projet' ] . '</p>
This is my action.js
function urlId() {
//id of url
$('.post .modal-action').click(function (e) {
e.preventDefault();
var id_projet = $(this).data('id_projet');
var $hidennDiv = $('#' + id_projet);
//inject id url ajax
$.ajax({
url: 'core/libs/contents-services.php?action=getModal&id=' + id_projet,
type: "get",
dataType: "html",
success: function (reponse) {
$('#demoModal').html(reponse);
id_projet = reponse.id_projet;
}
});
function ss_takeover_modal() {
if ($('.modal.takeover').length) {
$('.modal.takeover').each(function () {
takeoverModal(this);
});
}
}
function takeoverModal(el) {
$(el).on('show.bs.modal', function (e) {
var animateaction = $(el).find('.modal-dialog').data('animateaction');
$(el).find('.modal-dialog').attr('class', 'modal-dialog ' + animateaction + ' animated');
});
$(el).on('hide.bs.modal', function (e) {
var animateaction = $(el).find('.modal-dialog').data('animateaction');
$(el).find('.modal-dialog').attr('class', 'modal-dialog ' + animateReverse(animateaction) + ' animated');
});
}
function animateReverse(action) {
//Add Animate options w/reverse (close) setting here
if (action === 'slideInDown') {
return 'slideOutUp';
}
if (action === 'slideInRight') {
return 'slideOutRight';
}
}
$(document).ready(function () {
ss_takeover_modal();
// End takeover modal
});
});
}
urlId();
And my PHP that contains the return action :
function modal() {
require( "./connexion.php" );
$sql_print = 'SELECT * FROM projets AS P LEFT JOIN images AS I ON P.id_projet=I.fk_projet_id WHERE P.id_projet=' . $_GET[ 'id' ];
$req = mysqli_query( $connexion, $sql_print )or die( mysqli_error( $connexion ) );
//4
$return = "";
global $data_projet, $data_nom_projet, $data_detail_projet, $data_type_projet, $data_youtube;
while ( $data = mysqli_fetch_array( $req ) ) {
$data_projet = $data[ 'nom_projet' ];
$data_detail_projet = $data[ 'detail_projet' ];
$data_type_projet = $data[ 'type_projet' ];
$data_youtube = $data[ 'youtube' ];
}
$dir = '../../00_sources/images/mockups/'.$data_projet.'/';
if ($data_type_projet == 6){
echo'
<a class="btn-floating btn-medium waves-effect waves-light red modal-action modal-close right"><i class="material-icons">close</i></a>
<div class="container-fluid center">
<div class="row col s8">
<div class="caption color-secondary-2-4 center-align">
<h3>'.$data_projet.'</h3>
<h5 class="primary-text-color">'.$data_detail_projet.'</h5>
<div class="video-container">
<iframe width="560" height="315" src="'.$data_youtube.'" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe>
</div>
</div>
</div>'
;
}else{
$images = glob($dir."*");
echo'
<div class="modal fade takeover demo" id="demoModal" tabindex="-1" role="dialog" aria-labelledby="demoModalLabel" aria-hidden="true">
<div class="modal-dialog container" role="document" data-animateaction="slideInDown">
<div class="container">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
<div class="row mx-auto">
<div class="col-xl-8 col-lg-10 col-md-12 mx-auto">
<div class="modal-content pt-4">
<div class="modal-header border-0 pb-3 px-0">
<h5 class="modal-title mx-auto bb b-light text-center text-white" id="demoModalLabel">
Title
</h5>
</div>
<div class="modal-body p-0 bg-light">
Content
</div>
</div>
</div>
</div>
</div>
</div>
</div>
';
foreach($images as $image) {
echo'
<div class="row col d-flex align-items-center">
<img class="img-fluid" src="'.$image.'"></div>
</div>
';
}
}
The modal is showing nothing, the action at seems to not works. May be i miss something but i really don't see where. I think in my action.js i have something wrong.
Can anyone help me pleas ?
I find the solution. In my php's return, i was writing twice the id's of the modal's div. So the browser doesn't understand which one to show.

PHP News Via Modal

i'm currently working on a project to improve my PHP/SQL skills.
So basically i want to make it so you click on the news title opens a modal that shows the news content, this is what i currently have and it isn't working.
Also sorry for my english, I'm dutch.
$newssql = $odb -> query("SELECT * FROM `news` ORDER BY `date` DESC LIMIT 4");
while($row = $newssql ->fetch())
{
$id = $row['ID'];
$title = $row['title'];
$content = $row['content'];
$autor = $row['author'];
echo '
<a data-toggle="modal" data-id="'.$id.'" data-target="#modal-3">
<div class="inbox-item">
<p class="inbox-item-author">'.htmlspecialchars($title).'</p>
<p class="inbox-item-text">'.htmlspecialchars($content).'</p>
<p class="inbox-item-date">'.date("m/d/y" ,$row['date']).'</p>
</div>
</a>
';
}
//Modal
<div aria-hidden="true" aria-labelledby="modal-label-3" class="modal fade"
id="modal-3" role="modal" style="display: none;" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button aria-hidden="true" class="close" data-dismiss=
"modal" type="button">×</button>
<h4 class="modal-title" id="modal-label-3">NEWS</h4>
</div>
<div class="modal-body">
<?php echo htmlspecialchars($content); ?>
</div>
</div>
</div>
</div>
//jQuery
<script>
$('button[data-target="#modal-3"]').click(function(event) {
event.preventDefault();
var j = $(this).attr('data-id');
});
</script>
as far as I can see,
<script>
$('button[data-target="#modal-3"]').click(function(event) {
event.preventDefault();
var j = $(this).attr('data-id');
});
</script>
jquery will detect a click event from a button where as you stated
echo '
<a data-toggle="modal" data-id="'.$id.'" data-target="#modal-3">
<div class="inbox-item">
<p class="inbox-item-author">'.htmlspecialchars($title).'</p>
<p class="inbox-item-text">'.htmlspecialchars($content).'</p>
<p class="inbox-item-date">'.date("m/d/y" ,$row['date']).'</p>
</div>
</a>
';
it's on an <a> tag which is not a button.

how to pass a json data into jquery data() or data-caption, data-image, data-any?

this is where my json, ajax goes.
<div id="pic"></div>
this is my modal and when i clicked the image through the appended html on #pic.. the modal will show the clicked image...
<div class="modal fade" id="image-gallery" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="image-gallery-title"></h4>
</div>
<div class="modal-body">
<img id="image-gallery-image" class="img-responsive" src="">
</div>
<div class="modal-footer">
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="show-previous-image">Previous</button>
</div>
<div class="col-md-8 text-justify" id="image-gallery-caption">
This text will be overwritten by jQuery
</div>
<div class="col-md-2">
<button type="button" id="show-next-image" class="btn btn-default">Next</button>
</div>
</div>
</div>
</div>
This is my script wherein i want to pass the json data unto jquery data and it seems like the jquery data do not store the passed json data.. i also checked if my json is wrong but it displays the img which i also pass a json data.
<script>
$.ajax({
type: "POST",
url: "response2.php",
dataType: "json",
success: function(JSONObject) {
var peopleHTML = "";
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {
peopleHTML += "<div class='col-lg-3 col-md-4 col-xs-6 thumb'>";
peopleHTML += "<a class='thumbnail' href='#' data-image-id=''
data-toggle='modal' data-title='" + JSONObject[key]["title"] + "'
data-caption='" + JSONObject[key]["name"] + "'
data-image='./images/gallery/img/" + JSONObject[key]["img"] + "'
data-target='#image-gallery'>";
peopleHTML += " <img class='img-responsive'
src='./images/gallery/img/" + JSONObject[key]["img"] + "'
alt='Short alt text'>";
peopleHTML += "</a>";
peopleHTML += "</div>";
}
}
$("#pic").html(peopleHTML).hide();
$("#pic").fadeIn("slow");
}
});
</script>
this is my php where i pass the json from database to jquery
<?php
$connection = mysqli_connect("localhost", "root", "", "ecommerceagri");
$query = mysqli_query($connection,
"SELECT a.`Gallery.Photo.SRC` AS img, a.`Gallery.Photo.Title` AS title,
a.`Gallery.Photo.Caption` AS caption FROM galleryphoto AS a;");
$someArray = [];
while ($row = mysqli_fetch_assoc($query)) {
array_push($someArray, [
'title' => $row['title'],
'caption' => $row['caption'],
'img' => $row['img']
]);
}
$someJSON = json_encode($someArray);
echo $someJSON;
?>

Categories