ajax return response with jquery - php

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.

Related

Chat with laravel, socket io and redis not transferring messages through private channel

I am building a website with laravel, with chat option available inside it. I am able to store the messages in database as well as display in the sender's screen. But I can't manage to display the messages in receiver side. I am providing my codes as below. I used socket io and redis for the chat option.
server.js :
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http,{
cors: { origin: "*"}
});
const port = process.env.PORT || 6001;
var Redis = require('ioredis');
var redis = new Redis();
var users =[];
http.listen(port, function () {
console.log(`Listening to port ${port}`);
});
redis.subscribe('private-channel', function() {
console.log('subscribed to private channel');
});
redis.on('message', function(channel, message) {
message = JSON.parse(message);
console.log(message);
if (channel == 'private-channel') {
let data = message.data.data;
let receiver_id = data.receiver_id;
let event = message.event;
io.to(`${users[receiver_id]}`).emit(channel + ':' + message.event, data);
}
});
io.on('connection', function (socket) {
console.log('connection');
socket.on("user_connected", function (user_id) {
users[user_id] = socket.id;
io.emit('updateUserStatus', users);
console.log("user connected "+ user_id);
});
socket.on('disconnect', function() {
console.log('disconnected');
var i = users.indexOf(socket.id);
users.splice(i, 1, 0);
io.emit('updateUserStatus', users);
console.log(users);
});
});
controller :
public function companyconversation($userId) {
$users = \DB::table('users')->where([
'usertype'=>'individual',
])->get();
$friendInfo = User::findOrFail($userId);
$myInfo = User::find(Session::get('loginId'));
$company = $myInfo;
//$groups = MessageGroup::get();
$this->data['company'] = $company;
$this->data['users'] = $users;
$this->data['friendInfo'] = $friendInfo;
$this->data['myInfo'] = $myInfo;
$this->data['users'] = $users;
$this->data['userId'] = $userId;
//$this->data['groups'] = $groups;
//dd($users);
return view('company.convo', compact('users','friendInfo','myInfo','company'));
}
view :
<div id="main-content">
<div class="container-fluid">
<div class="block-header">
<div class="row clearfix">
<div class="col-md-6 col-sm-12">
<h1> Messages(Chat) </h1>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">Demo </li>
<li class="breadcrumb-item active" aria-current="page">Messages(Chat) </li>
</ol>
</nav>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-lg-12 ">
<div class="card ">
<div class="body" style="height:100%; min-height:700px;">
<div class="chatapp_list">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Search...">
<div class="input-group-append">
<span class="input-group-text"><i class="icon-magnifier"></i></span>
</div>
</div>
<div class="col-md-12">
<div class="users">
<h5>Users</h5>
<ul class="list-group list-chat-item">
#if($users->count())
#foreach($users as $users)
<li class="chat-user-list
#if($users->id == $friendInfo->id) active #endif">
<a href="{{ route('company_conversation', $users->id) }}">
<div class="chat-image media">
{!! makeImageFromName($users->fname,$users->lname) !!}
</div>
<div class="media-body">
<span class="name chat-name">{{$users->fname}}</span>
<!-- <span class="message">offline</span> -->
<span class="badge badge-outline status user-status-icon user-icon-{{$users->id}}"></span>
</div>
</a>
</li>
#endforeach
#endif
</ul>
</div>
</div>
</div>
<div class="chatapp_body">
<div class="col-md-9 chat-section">
<div class="chat-header">
<div class="chat-name font-weight-bold">
{{ $users->fname }}
</div>
</div>
<div class="chat-body" id="chatBody">
<div class="message-listing" id="messageWrapper" style="
border: 1px #ccc solid;
height: 100%;
overflow: hidden;
min-height: 450px;
position: relative;
z-index: 9;
color:#333;
background: #fff;
">
</div>
</div>
<div class="chat-box">
<div class="chat-input border text-secondary bg-white p-3 " id="chatInput" contenteditable="">
</div>
<div class="chat-input-toolbar">
<button title="Add File" class="btn btn-light btn-sm btn-file-upload">
<i class="fa fa-paperclip"></i>
</button> |
<button title="Bold" class="btn btn-light btn-sm tool-items"
onclick="document.execCommand('bold', false, '');">
<i class="fa fa-bold tool-icon"></i>
</button>
<button title="Italic" class="btn btn-light btn-sm tool-items"
onclick="document.execCommand('italic', false, '');">
<i class="fa fa-italic tool-icon"></i>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal Success -->
<div class="modal fade" id="adsuccessModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle"> Successfully Saved </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="text-align: center;">
<span> <i class="fa fa-check-circle-o" style="font-size: 6em; color: #060;"></i> </span>
<h2 style="color: #060;"> Ad Saved Successfully</h2>
<button type="button" class="btn btn-round btn-success">
<i class="fa fa-bars"> Back to Ads Lists </i> </button>
</div>
<span style="font-size: 10px; color: #f00; text-align: center; margin-bottom: 1em;">Note: Your Ad will be automatically expired after 30 days of posted</span>
<div class="modal-footer">
<button type="button" class="btn btn-round btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal END -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js" integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous"></script>
<script>
function getCurrentTime() {
return moment().format('h:mm A');
}
function getCurrentDateTime() {
return moment().format('MM/DD/YY h:mm A');
}
function dateFormat(datetime) {
return moment(datetime, 'YYYY-MM-DD HH:mm:ss').format('MM/DD/YY h:mm A');
}
function timeFormat(datetime) {
return moment(datetime, 'YYYY-MM-DD HH:mm:ss').format('h:mm A');
}
$(function (){
let $chatInput = $(".chat-input");
let $chatInputToolbar = $(".chat-input-toolbar");
let $chatBody = $(".chat-body");
let $messageWrapper = $("#messageWrapper");
let user_id = "{{ Session::get('loginId') }}";
//console.log(user_id);
let ip_address = '127.0.0.1';
let socket_port = '6001';
let socket = io(ip_address + ':' + socket_port);
let friendId = "{{ $friendInfo->id }}";
socket.on('connection',function() {
socket.emit('user_connected', user_id);
});
socket.on('updateUserStatus', (data) => {
let $userStatusIcon = $('.user-status-icon');
$userStatusIcon.removeClass('text-success');
$userStatusIcon.attr('title', 'Away');
console.log(data);
$.each(data, function (key, val) {
if (val !== null && val !== 0) {
let $userIcon = $(".user-icon-"+key);
$userIcon.addClass('text-success');
$userIcon.attr('title','Online');
}
});
});
$chatInput.keypress(function (e) {
let message = $(this).html();
if (e.which === 13) {
$chatInput.html("");
sendMessage(message);
return false;
}
});
function sendMessage(message) {
let url = "{{ route('send-message') }}";
let form = $(this);
let formData = new FormData();
let token = "{{ csrf_token() }}";
formData.append('message', message);
formData.append('_token', token);
formData.append('receiver_id', friendId);
appendMessageToSender(message);
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'JSON',
success: function (response) {
if (response.success) {
console.log(response.data);
}
}
});
}
function appendMessageToSender(message) {
let name = '{{ $myInfo->fname }}';
let image = '{!! makeImageFromName($myInfo->fname,$myInfo->lname) !!}';
let userInfo = '<div class="col-md-12 user-info">\n' +
'<div class="chat-image">\n' + image +
'</div>\n' +
'\n' +
'<div class="chat-name font-weight-bold">\n' +
name +
'<span class="small time text-gray-500" title="'+getCurrentDateTime()+'">\n' +
getCurrentTime()+'</span>\n' +
'</div>\n' +
'</div>\n';
let messageContent = '<div class="col-md-12 message-content">\n' +
'<div class="message-text">\n' + message +
'</div>\n' +
'</div>';
let newMessage = '<div class="row message align-items-center mb-2">'
+ userInfo + messageContent +
'</div>';
$messageWrapper.append(newMessage);
}
function appendMessageToReceiver(message) {
let name = '{{ $friendInfo->fname,$friendInfo->lname }}';
let image = '{!! makeImageFromName($friendInfo->fname,$friendInfo->lname) !!}';
let userInfo = '<div class="col-md-12 user-info">\n' +
'<div class="chat-image">\n' + image +
'</div>\n' +
'\n' +
'<div class="chat-name font-weight-bold">\n' +
name +
'<span class="small time text-gray-500" title="'+dateFormat(message.created_at)+'">\n' +
timeFormat(message.created_at)+'</span>\n' +
'</div>\n' +
'</div>\n';
let messageContent = '<div class="col-md-12 message-content">\n' +
' <div class="message-text">\n' + message.content +
' </div>\n' +
' </div>';
let newMessage = '<div class="row message align-items-center mb-2">'
+userInfo + messageContent +
'</div>';
$messageWrapper.append(newMessage);
}
socket.on("private-channel:App\\Events\\PrivateMessageEvent", function (message)
{
appendMessageToReceiver(message);
});
});
</script>
Event :
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PrivateMessageEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $data;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('private-channel');
}
public function handle() {
}
}
I am expecting the message to appear on the receiver side, but it is not happening.

How to reuse the jquery ajax post request, that is already working, to the autocomplete functionality?

I have a link "Show cities" when is clicked it appears a modal with some cities:
<a class="city" id="showCities"
data-toggle="modal" data-target="#modal2" href=""> Show cities</a>
When the user clicks in a city inside the modal the modal closes and in the "#conferences" div it appears the conferences that have the column "city" in the conferences table equal to the clicked city. This is working fine with an ajax request.
Doubt:
My doubt is because I would like to reuse this part of the code, the ajax request, for a autocomplete search
input with id "#search". When the user writes for example "Ne" in this autocomplete input it appears Newcastle.
This is working fine.
But when the user clicks in Newcastle it should appaer in the div "#conferences" the conferences
that have the city column as "Newcastle". For this part Im in doubt in how to reuse the code of the ajax post request when
the city inside the modal is clicked. Do you know how to achieve that?
As it is when the user clicks in "Newcastle"
he is redirected to "http://proj.test/conferences/where/city/Newcastle" and it appears the conferences where the city is Newcastle (in this case there is only 1):
[{"id":2,"name":"conf test","city":"Newcastle",...}]
But what should happen is the conferences where city column
is Newcastle appear in the #conferences div.
AutoCompleteController:
class AutocompleteController extends Controller
{
public function index(){
return view('autocomplete.index');
}
public function search(Request $request){
$search = $request->term;
$conferences = Conference::where('name', 'LIKE', '%'.$search.'%')->get();
$cities = Conference::where('city', 'LIKE', '%'.$search.'%')->get();
$data= [];
foreach ($conferences as $key => $value){
$data[] = ['category'=> 'Conferences', 'value' => $value->name, 'url' => 'conference/'.$value->id.'/'.$value->slug];
}
foreach ($cities as $key => $value){
$data[] = ['category'=> 'Cities', 'value' => $value->city, 'url' => 'conferences/where/city/'.$value->city];
}
return response($data);
}
}
Autocomplete Jquery:
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
},
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
var li;
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category bg bg-light-gray2 h6 font-weight-bold text-heading-blue'>"
+ item.category + "</li>" );
currentCategory = item.category;
}
li = that._renderItemData( ul, item );
if ( item.category ) {
li.attr( "aria-label", item.category + " : " + item.label );
}
});
}
});
$("#search").catcomplete({
source: "{{ URL::to('autocomplete-search') }}",
select: function(event, ui) {
window.location.href = ui.item.url;
}
Modal that appears when Show citis is clicked:
<div class="modal fade bd-example-modal-lg" id="modal2" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
<ul class="modal-list row">
#foreach($cities as $city)
<li class="col-lg-4 col-md-6 col-sm-12">
<a class="" name="city" id="{{$city}}">{{$city}}</a>
</li>
#endforeach
</ul>
</div>
</div>
</div>
</div>
The div #conferences" that show the conferences, the results:
<div class="row" id="conferences">
#foreach(conferences as $conference)
<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">
<img class="card-img-top" src="{{$conference->image}}" alt="Card image cap">
<div class="card-body">
<h5 class="card-title h6 font-weight-bold text-heading-blue">{{$conference->name}}</h5>
<p class="card-text font-size-sm"><i class="fa fa-map-marker" aria-hidden="true"></i> {{$conference->place}},
{{$conference->city}}</p>
</div>
</div>
#endforeach
</div>
jQuery ajax request:
$("a[name='city']").on('click', function(){
$('#showCities').html($(this).text()+' <i class="fa fa-caret-down" aria-hidden="true"></i>');
var city = $(this).attr("id");
$.ajax({
url: '{{ route('city.conferences',null) }}/' + city,
type: 'GET',
success:function(result){
console.log(result)
$('#conferences').empty();
var newConferences='';
var placeholder = "{{route('conferences.show', ['id' => '1', 'slug' => 'demo-slug'])}}";
$.each(result, function(index, conference) {
$('#modal2').modal('hide');
var url = placeholder.replace(1, conference.id).replace('demo-slug', conference.slug);
newConferences += '<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">\n' +
' <div class="card-body">\n' +
' <h5 class="card-title h6 font-weight-bold text-heading-blue">'+conference.name+'</h5>\n' +
' <p class="card-text font-size-sm"><i class="fa fa-map-marker" aria-hidden="true"></i> '+conference.city+'</p>\n' +
' </div>\n' +
' </div>\n';
});
$('#conferences').html(newConferences);
},
error: function(error) {
console.log(error.status)
}
});
});
One option would be to use data attributes. As an additional critique, depending on how your AJAX request works, you may not want to use city name as an ID; especially if there can be multiple cities of the same name returned in a request (ID's will collide and produce unexpected results).
<div class="modal fade bd-example-modal-lg" id="modal2" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
<ul class="modal-list row" id="cities-list>
#foreach($cities as $city)
<li class="col-lg-4 col-md-6 col-sm-12">
<a class="" data-city-name="{{city}}" name="city" id="{{$city}}">{{$city}}</a>
</li>
#endforeach
</ul>
</div>
</div>
</div>
</div>
For example, I've added some IDs to your code above. Then you would simply access these values on the click event of your link like so:
$('#cities-list li a').on('click', function() {
// push city name to #conferences div
$('#conferences').append($('<p />').text($(this).attr('data-city-name')));
});

my bootstrap modal turns out blank after adding ajax

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);
});

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;
?>

How to open a url as a bootstrap modal window?

I have this line of PHP:
$STRING .= $b_f.''.$CORE->_e(array('head','5','flag_link')).''.$b_a;
This url opens now as a new webpage. How can i open it as a dialog/modal window instead? In my code i have bootstrap installed.
Try this "trick":
Open modal
<div id="popupModal2" class="modal hide fade" tabindex="-1" role="dialog">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Title</h3>
</div>
<div class="modal-body">
<iframe src="" style="zoom:0.60" frameborder="0" height="250" width="99.6%"></iframe>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">OK</button>
</div>
</div>
and the js:
$('.bootpopup').click(function(){
var frametarget = $(this).attr('href');
var targetmodal = $(this).attr('target');
if (targetmodal == undefined) {
targetmodal = '#popupModal';
} else {
targetmodal = '#'+targetmodal;
}
if ($(this).attr('title') != undefined) {
$(targetmodal+ ' .modal-header h3').html($(this).attr('title'));
$(targetmodal+' .modal-header').show();
} else {
$(targetmodal+' .modal-header h3').html('');
$(targetmodal+' .modal-header').hide();
}
$(targetmodal).on('show', function () {
$('iframe').attr("src", frametarget );
});
$(targetmodal).modal({show:true});
return false;
});
Just pass your link to the button's href.
DEMO

Categories