How do i pass variables into a UIkit Modal?
The Button:
<button type="button" class="uk-button" data-uk-modal="{target:'#info',center:true}" data-added="added-test" data-modified="modified-test"><i class="uk-icon-info"></i></button>
The Modal:
<div class="uk-modal" id="info">
<div class="uk-modal-dialog">
<h4 style="margin-bottom:5px;">Added:</h4>
<div id="added"></div><br>
<h4 style="margin-bottom:5px;">Modified:</h4>
<div id="modified"></div>
<div class="uk-modal-footer">
<button type="button" class="uk-button uk-modal-close">Close</button>
</div>
</div>
</div>
The Script:
$(document).ready(function () {
$('#info').on('uk.modal.show', function (event) {
var button = $(event.relatedTarget);
var added = button.data('added');
var modified = $(e.target).data('modified');
var modal = $(this);
modal.find('.uk-modal-dialog #added').text(added);
modal.find('.uk-modal-dialog #modified').text(modified);
});
});
This is not working. I do not get a error in the console. I´ve already tried a few other ways but all of them didn´t worked as they should.
Update #1
The following jquery works partially. I´ve added the id "infotrigger" to the button.
jQuery('#info').appendTo("body");
jQuery(document).on('click', '#infotrigger', infomodal_handler);
function infomodal_handler(e)
{
var added = jQuery(e.target).data('added');
var modified = jQuery(e.target).data('modified');
jQuery('#info').on({
'show.uk.modal':function(){
jQuery('#added', jQuery(this)).text(added);
jQuery('#modified', jQuery(this)).text(modified);
}
}).trigger('show.uk.modal');
}
The Problem now is that it´s only working partially. I think the reason is that the button is in a foreach loop. Mostly i have old data when opening the modal. If i open it again i have mostly the correct data.
Any ideas how to fix that?
The problem was that sometimes the icon was presssed instead of the button itself. So the data couldn´t be fetched. To fix this the variables need to be changed from:
var added = jQuery(e.target).data('added');
to:
var added = jQuery(this).data('added');
Now the correct dom element is the target.
To use the modal inside a loop i changed everything a bit. I´ve put the modal with the script into a function where i pass the element-id through and apply it to different elements:
function info_modal( $id ) {
return "
<script>
jQuery('#info" . $id . "').appendTo('body');
jQuery(document).on('click', '#infotrigger" . $id . "', infomodal_handler" . $id . ");
function infomodal_handler" . $id . "(e)
{
console.log(e);
var added" . $id . " = jQuery(this).data('added" . $id . "');
var modified" . $id . " = jQuery(this).data('modified" . $id . "');
jQuery('#info" . $id . "').on({
'show.uk.modal':function(){
jQuery('#added" . $id . "', jQuery(this)).text(added" . $id . ");
jQuery('#modified" . $id . "', jQuery(this)).text(modified" . $id . ");
}
}).trigger('show.uk.modal');
}
</script>
<!-- Info Modal -->
<div class='uk-modal' id='info" . $id . "'>
<div class='uk-modal-dialog'>
<h4 style='margin-bottom:5px;'>" . __( 'Added on', 'easy-code-placement' ) . ":</h4>
<div id='added" . $id . "'></div><br>
<h4 style='margin-bottom:5px;'>" . __( 'Last Modified on', 'easy-code-placement' ) . ":</h4>
<div id='modified" . $id . "'></div>
<div class='uk-modal-footer uk-text-right'>
<button type='button' class='uk-button uk-modal-close'>" . __( 'Close', 'easy-code-placement' ) . "</button>
</div>
</div>
</div>
";
}
Inside the loop i´ve placed the button and also apply the element-id to it and after it i call the function (the function is only for the better code readability - the script and modal can, of course, also be placed directly inside the loop):
<button type="button" id="infotrigger<?php echo $code->id; ?>" class="uk-button" data-uk-modal="{target:'#info<?php echo $code->id; ?>',center:true}" data-added<?php echo $code->id; ?>="added" data-modified<?php echo $code->id; ?>="modified"><i class="uk-icon-info"></i></button>
<?php echo info_modal( $code->id ); ?>
Related
I am currently working on a Wordpress project and I have a issue during an ajax request:
On my view, I have this button for displaying more articles on my page :
<input type="hidden" name="nbPages" value="<?php echo $nb_pages;?>">
<input type="hidden" name="pageActive" value="1">
<input type="hidden" name="termSlug" value="<?php echo $term_query->slug;?>">
.
.
.
<div class="product-bottom">
<img src="<?php echo get_template_directory_uri();?>/img/ajax-loader.gif" alt="" id="ajax-loader" style="display:none;">
<button class="btn btn-site-1" id="loadmore_bt">See more</button>
</div>
On my js file, I have this part that is called when the button is used
add_action('wp_ajax_ajax_loadmore', 'ajax_loadmore');
$(function () {
'use strict';
//AJAX LOAD MORE PRODUCTS
jQuery('body').on('click', '#loadmore_bt', function (e) {
e.preventDefault();
$('#ajax-loader').fadeIn(500);
var nbPages = jQuery('input[name="nbPages"]').val();
var activePage = jQuery('input[name="pageActive"]').val();
var termSlug = jQuery('input[name="termSlug"]').val();
jQuery.ajax({
type: 'POST',
dataType: "JSON",
data: {
'action': 'ajax_loadmore',
'nbPages': nbPages,
'activePage': activePage,
'termSlug': termSlug
},
url : ajaxurl,
success : function(response){
console.log('cool!');
console.log(response.newPageToDisplay);
}
})
In function.php , I have this function which is called :
function ajax_loadmore(){
.
.
// set query arg as $args_products
.
.
$products = new WP_Query($args_products);
$rendering = '';
if ($products->have_posts()) {
foreach ($products->posts as $key => $prod) {
$rendering .= "
<div>
<h2 class="card-title main-title-2">' . $prod->post_title . '</h2>
<p class="card-subtitle">' . get_field('reference', $prod->ID) . '</p>
</div>
<div class="card-txt">' . get_field('desriptif_court', $prod->ID) . '</div>
<button class="btn btn-site-1">More info</button>
</div>";
}
$json = array(
'reponse' => 'success',
'newPageToDisplay' => $rendering,
'pageloaded' => $pageToLoad,
'activePage' => $activePage,
);
echo json_encode($json);
}else{
echo "error";
echo json_encode(array(
'reponse' => $reponse
));
}
die();
}
My issue is: $rendering has not the same value than in the js response (as response.newPageToDisplay).
For exemple, on the first element of $rendering is $prod->post_title = 'PA80MP' , while the first element of response.newPageToDisplay is 'PA95'. Both are indeed existing values in my database.
TLDR : Ajax doesn't have the same value of variables as in the php file function that it calls.
Hope I explain well my problem ...thank you for helping!
When I am clicking on the Bengali button its showing data for few seconds and hiding it again, whereas I wrote the same code for the Assamese button, it displaying fine:
<script>
function be(){
var x= document.getElementById('ben');
if (x.style.display==='block'){
x.style.display='none';
}
else
{
x.style.display='block';
}
}
</script>
<button class= "button" onclick="be()">BENGALI</button>
<div id="ben">
<?php
$dir = '/home/test/data/Bengali/';
if (!isset($_POST['submit'])) {
if ($dp = opendir($dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
}
if ($files) {
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';
foreach ($files as $file) {
echo '<input type="checkbox" name="files[]" value="' . $file . '" /> '
.
$file . '<br />';
}
}
}
?></div>
You call the function when you click on a submit button.
So the JS runs, then the form submits, and you load a new page.
The new page doesn't set the default styles to what they were before, so it has the effect of resetting the page.
As already mentioned, a new page is opening because a button has been clicked. The best way to solve this is by modifying your button like this:
<button class= "button" onclick="be()" type="button">BENGALI</button>
This prevents the form from submitting and runs your JavaScript function
I have made a template that I would like to load in using jQuery .load() function. When testing I found out that it won't load any .
Here is my load code:
function open() {
history.pushState(null, null, "artiesten.php?u=user2");
$('.content').load('artiest_template.php .content');
}
Here is my template code:
<?php include('includes/connect.php') ?>
<span class="content">
<div class="right_col" role="main">
<div class="">
<script>alert("nothing")</script>
<?php
echo '<script>alert("' . $_GET['u'] . ' or nothing")</script>';
if($_GET['u']){
$t = mysqli_real_escape_string($connect,$_GET['u']);
$res = mysqli_query($connect, "SELECT * FROM artiesten WHERE Naam='" . $t . "'");
$i = mysqli_fetch_assoc($res);
echo '
<script src="vendors/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".a-titel").html("' . $i['Titel'] . '");
$(".a-naam").html("' . $i['Naam'] . '");
$(".a-over").html("' . $i['Over'] . '");
$(".a-kernmerk").html("' . $i['Kernmerk'] . '");
$(".a-email").html("' . $i['Email'] . '");
$(".a-foto").attr("src", "images/' . $i['Naam'] . '.jpg");
history.pushState(null, null, "?u=' . $i['Naam'] . '");
});
</script>';
}
?>
</div>
</div>
</span>
Can somebody help me with this?
Thanks in advance.
Should be
function open() {
history.pushState(null, null, "artiesten.php?u=Chato De Veirman");
$('.content').load('artiest_template.php');
}
not
function open() {
history.pushState(null, null, "artiesten.php?u=Chato De Veirman");
$('.content').load('artiest_template.php .content');
}
jQuery load() takes three parameters, URL, data and a function. These parameters have to be separated by a coma. Your load() has something behind your URL that is not part of the URL.
Change
$('.content').load('artiest_template.php .content');
to
$('.content').load('artiest_template.php');
I'm trying to change an input value using jQuery mouse over.
Scenario: I got 5 div having different colors and user names. When mouseover a div the input text change (and for color input the background color) data according to database values, when change div the text displays new data.
using PHP I echo the part of the script to handle the mouseover function
<?php
$myId = '1';
$uname = 'user1';
$ucolor = 'FFFFFF';
echo "<script>
$('$myId').mouseover( function () {
$('#uname').val('" . $uname . "'),
$('#ucolor').val('" . $ucolor ."'),
$('#ucolor').css('background-color', '" . $ucolor . "')
})
</script>";
This work if i change mouseover() to hover(), but display only the first element, if i do a mouse over the second element data doesn't change.
Try this:
Put your script after body tag:
<body>
<div class="hh" id="1"></div>
<input type="text" id="uname" />
<input type="text" id="ucolor" />
<div class="hh" id="2"></div>
</body>
<?php
$myId = '1';
$uname = 'user1';
$ucolor = 'FFFFFF';
echo "<script>
$('#$myId').mouseover( function () { // add # here
$('#uname').val('" . $uname . "'),
$('#ucolor').val('" . $ucolor ."'),
$('#ucolor').css('background-color', '" . $ucolor . "')
})
</script>";
$myId = '2';
$uname = 'user2';
$ucolor = 'FFF555';
echo "<script>
$('#$myId').mouseover( function () { console.log('fdgfdg')
$('#uname').val('" . $uname . "'),
$('#ucolor').val('" . $ucolor ."'),
$('#ucolor').css('background-color', '" . $ucolor . "')
})
</script>";
?>
In general the div or any DOM must have a unique ID value. Try using class selector(.) instead of ID selector(#).
I'm trying to make a comments system which adds to the database using PHP and AJAX without having to reload the page (if I reload the page it will pick another film suggestion at random).
At the moment it doesn't seem to work - when I click "Submit comment" it reloads the page (loading a different film) and nothing is inserted to the database.
I'd also like to be able to have the comment appear in the comments section below after submission if possible.
Thanks for your help
yourfilm.php (the process page that displays a film, specified by options selected on a form on the previous page)
<?php //recaptcha_process.php
require_once("php/checklog.php");
require_once('php/functions.php');
require_once('php/db_connect.php');
include_once("php/home_start_logged.php");
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}else{
//CODE TO QUERY DATABASE TO GO HERE
//Capture form data, if anything was submitted
if (isset($_POST['genreList']) && ($_POST['genreList'] != '')){
$genre = clean_string($db_server, $_POST['genreList']);
//create the SQL query
$query = "SELECT * FROM films WHERE genreID=$genre ";
//$endquery = " AND (";
$endquery = "";
$orFlag = false;
if (isset($_POST['streamingCheckbox1']) && ($_POST['streamingCheckbox1'] != '')){
$endquery .= " netflix IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox2']) && ($_POST['streamingCheckbox2'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " lovefilmInstant IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox3']) && ($_POST['streamingCheckbox3'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " blinkbox IS NOT NULL";
}
if($endquery != "") $query .= " AND (" . $endquery . ")";
$query .= " ORDER BY (SELECT FLOOR(MAX(filmID) * RAND()) FROM films) LIMIT 0,1;";
//query the database
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) . $query);
//if there are any rows, print out the contents
if ($row = mysqli_fetch_array($result)) {
//Whether to display links or not for purchase and streaming
if ($row['netflix'] == null){
$netflixLink = "";
}else{
$netflixLink = "<a href='" . $row['netflix'] . "'>" . "<img class='streamingLogo' src='images/netflix_logo.jpg' alt='Watch on Netflix'></a>";
}
if ($row['lovefilmInstant'] == null){
$lovefilmLink = "";
}else{
$lovefilmLink = "<a href='" . $row['lovefilmInstant'] . "'>" . "<img class='streamingLogo' src='images/Lovefilm_logo.jpg' alt='Watch on LoveFilm'></a>";
}
if ($row['blinkbox'] == null){
$blinkboxLink = "";
}else{
$blinkboxLink = "<a href='" . $row['blinkbox'] . "'>" . "<img class='streamingLogo' src='images/blinkbox_logo.jpg' alt='Watch on Blinkbox'></a>";
}
if ($row['itunes'] == null){
$iTunesLink = "";
}else{
$iTunesLink = "<a href='" . $row['itunes'] . "'>" . "<img class='streamingLogo' src='images/itunes_logo.jpg' alt='Buy now on iTunes'></a>";
}
if ($row['googlePlay'] == null){
$googleplayLink = "";
}else{
$googleplayLink = "<a href='" . $row['googlePlay'] . "'>" . "<img class='streamingLogo' src='images/googleplay_logo.jpg' alt='Buy now on Google Play'></a>";
}
if ($row['amazon'] == null){
$amazonLink = "";
}else{
$amazonLink = "<a href='" . $row['amazon'] . "'>" . "<img class='streamingLogo' src='images/amazon_logo.jpg' alt='Buy now on Amazon'></a>";
}
//Body content for film
$str_result = "<section>
<div class='sectionColumnThird'>
<img class='poster' src='images/posters/" . $row['poster'] . ".jpg'>
</div>
<div class='sectionColumnTwoThirds'>
<h2>" . $row['filmName'] . "</h2>
<p class='filmDate'>(" . $row['filmYear'] . ")</p>
<a class='formButton' href='#comments'>Jump to comments</a>
</div>
</section>
<section>
<h3>Not interested?</h3>
<a class='formButton' href='#yourfilm.php'>Find another film</a>
</section>
<section>
<h3>Rating</h3>
<p><span class='bold'>IMDB:</span> " . $row['ratingIMDB'] . "</p>
<p><span class='bold'>Rotten Tomatoes:</span> " . $row['ratingRottenTomatoes'] . "</p>
<p><span class='bold'>Metacritic:</span> " . $row['ratingMetacritic'] . "</p>
</section>
<section>
<h3>Synopsis</h3>
<p>" . $row['synopsis'] . "</p>
</section>
<section>
<h3>Trailer</h3>
<div class='videoWrapper'>
<iframe src='//www.youtube.com/embed/" . $row['trailer'] . " ' frameborder='0' allowfullscreen></iframe>
</div>
</section>
<section>
<h3>Cast & Crew</h3>
<p><span class='bold'>Director:</span> " . $row['director'] . "</p>
<p><span class='bold'>Writers:</span> " . $row['writer'] . "</p>
<p><span class='bold'>Cast:</span> " . $row['cast'] . "</p>
</section>
<section>
<h3>Details</h3>
<p><span class='bold'>Certificate:</span> " . $row['certificate'] . "</p>
<p><span class='bold'>Country:</span> " . $row['country'] . "</p>
<p><span class='bold'>Language:</span> " . $row['language'] . "</p>
</section>
<section>
<h3>Streaming Services</h3>"
. $netflixLink . $lovefilmLink . $blinkboxLink ."
</section>
<section>
<h3>Buy now</h3>"
. $iTunesLink . $googleplayLink . $amazonLink ."
</section>
<section>
<form id='frmFilmComments' action='yourfilm.php' method='post'>
<a id='comments' class='anchor'></a><h3>Comments</h3>
<p><span class='bold'>Did you like " . $row['filmName'] ."?</span></p>
<select class='selectbox' name='yesornoList'>
<option value='Yes'>Yes</option>
<option value='No'>No</option>
</select>
<p id='commentResult'></p>
<p><span class='bold'>Provide your feedback here:</span></p>
<textarea id='commentBox' class='insertComment' rows='2' cols='30' name='comment'></textarea><br>
<input class='formButton' type='submit' id='submitComment' name='submitComment' value='Submit comment' />
</form>";
$filmID=$row['filmID'];
mysqli_free_result($result);
//Print out Like it - Comments
$likeitQuery = "SELECT * FROM comments
JOIN users on users.userID = comments.userID
WHERE likeit='Yes' AND filmID=$filmID";
$likeitResult = mysqli_query($db_server, $likeitQuery);
if (!$likeitResult) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($likeitResult)){
$str_likedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
. $row['comment'] . "<br>
▲(" . $row['upvotes'] . ") ǀ ▼ (" . $row['downvotes'] . ")</p>";
}
mysqli_free_result($likeitResult);
$likedcomments = "<div class='half subSection'>
<h4>Liked it</h4>"
. $str_likedcomments .
"</div>";
//Print out disike it - Comments
$dislikeitQuery = "SELECT * FROM comments
JOIN users on users.userID = comments.userID
WHERE likeit='No' AND filmID=$filmID";
$dislikeitResult = mysqli_query($db_server, $dislikeitQuery);
if (!$dislikeitResult) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($dislikeitResult)){
$str_dislikedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
. $row['comment'] . "<br>
▲(" . $row['upvotes'] . ") ǀ ▼ (" . $row['downvotes'] . ")</p>";
}
mysqli_free_result($dislikeitResult);
$dislikedcomments = "<div class='half subSection'>
<h4>Disliked it</h4>"
. $str_dislikedcomments .
"</div>";
}else{
$str_result = "<section><h3>Sorry</h3><p>We couldn't find any films that match your terms. </br> <a href='home.php'>Please try again.</a></p></section>";
}
}else{
$str_result = "<section><h3>Sorry</h3><p>No genre was chosen.</br><a href='home.php'>Please try again.</a></p></section>";
}
$message = $str_result . $likedcomments . $dislikedcomments . "<section/>";
}
//Comments
$userID = $_SESSION['userID'];
$likeit = $_POST['yesornoList'];
$comment = clean_string($db_server, $_POST['commentBox']);
//Get any submitted comments and insert
if ($comment != '') {
$query = "INSERT INTO comments (userID, filmID, comment, likeit) VALUES ($userID, $filmID, $comment)";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$message = "Thanks for your comment!";
}
require_once('php/db_close.php');
?>
<div id="top" class="content container headerMargin">
<div class="content wrapper">
<?php echo $message; ?>
</div>
</div>
<?php
require_once('php/home_end.php');
?>
addCommentAJAX.js
$("#submitComment").click( function() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
});
$("#frmFilmComments").submit( function() {
return false;
});
function clearInput() {
$("#frmFilmComments :input").each( function() {
$(this).val('');
});
}
home_start_logged.php is simply a header template, I won't post it all but it contains:
<script src="js/addCommentAJAX.js" type="text/javascript"></script>
EDIT: Added more specific info about the error (see above).
there is not enough data to make an exact solution, but i see two problems :
1 - you are not preventing the default form submit in your submit function event.preventDefautlt() or just change the input type attribut in your form to button rather than submit
2 - if you wan't the comment that the user just sent to show up then you can use the function append() to make it show at the end of the comment section this is the fastest way to do this rather than waiting for it to show from the database
So what is probably happening here is that you haven't used event.preventDefault() This will stop your submit button from reloading the page, which will allow your ajax code and your code posting the comment to finally get run.
http://api.jquery.com/event.preventdefault/
The idea behind preventDefault is that it stops the submit button from doing its default behavior, which is submitting a form and reloading the page.
can you change this
$("#submitComment").click( function() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
});
to
function onclicksth() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
}
and change submitComment type to button? There is a better way to do this too:
//rough code including the submit and post data
$('form.frmFilmComments').on('submit', function() {
if(confirm('Do u want to input that field')){
fields-=1;
var obj = $(this),
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
$("#hdnlstcount").val(fields);
//console.log(fields);
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response2) {
//do sth with success response
}
});
return false; //disable refresh
clearInput();
}
});