I have a modal box that opens content from the footer of a page (a hidden div). I am trying to launch the modal and display the content of another .php file whilst passing a variable that can be used to SELECT from a DB Any ideas?
Here is the code:
The modal box link
Click Me For A Modal
The JS
(function($) {
$('a[data-reveal-id]').live('click', function(e) {
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$('#'+modalLocation).reveal($(this).data());
});
The .php file with the modalbox content
<div id="myModal" class="reveal-modal">
<div>content called from DB using passed variable</div>
<p>more content</p>
<a class="close-reveal-modal">×</a>
Does anyone have any ideas please?
-----------------------------------------------------------------------------------
UPDATED!
Here is the full js file:
(function($) {
$('a[data-reveal-id').live('click', function(e)
{
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$.ajax({
url: 'code.php',
data: '$varible',
type: 'GET',
error: function()
{
// If there's an issue, display an error...
},
success: function(output)
{
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
}
});
})
$.fn.reveal = function(options) {
var defaults = {
animation: 'fadeAndPop', //fade, fadeAndPop, none
animationspeed: 300, //how fast animtions are
closeonbackgroundclick: true, //if you click background will modal close?
dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
};
var options = $.extend({}, defaults, options);
return this.each(function() {
var modal = $(this),
topMeasure = parseInt(modal.css('top')),
topOffset = modal.height() + topMeasure,
locked = false,
modalBG = $('.reveal-modal-bg');
if(modalBG.length == 0) {
modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
}
//Entrance Animations
modal.bind('reveal:open', function () {
modalBG.unbind('click.modalEvent');
$('.' + options.dismissmodalclass).unbind('click.modalEvent');
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modal.css({'top': $(document).scrollTop()-topOffset, 'opacity' : 0, 'visibility' : 'visible'});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"top": $(document).scrollTop()+topMeasure + 'px',
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "fade") {
modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(document).scrollTop()+topMeasure});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "none") {
modal.css({'visibility' : 'visible', 'top':$(document).scrollTop()+topMeasure});
modalBG.css({"display":"block"});
unlockModal()
}
}
modal.unbind('reveal:open');
});
//Closing Animation
modal.bind('reveal:close', function () {
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"top": $(document).scrollTop()-topOffset + 'px',
"opacity" : 0
}, options.animationspeed/2, function() {
modal.css({'top':topMeasure, 'opacity' : 1, 'visibility' : 'hidden'});
unlockModal();
});
}
if(options.animation == "fade") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"opacity" : 0
}, options.animationspeed, function() {
modal.css({'opacity' : 1, 'visibility' : 'hidden', 'top' : topMeasure});
unlockModal();
});
}
if(options.animation == "none") {
modal.css({'visibility' : 'hidden', 'top' : topMeasure});
modalBG.css({'display' : 'none'});
}
}
modal.unbind('reveal:close');
});
//Open Modal Immediately
modal.trigger('reveal:open')
//Close Modal Listeners
var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
if(options.closeonbackgroundclick) {
modalBG.css({"cursor":"pointer"})
modalBG.bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
}
$('body').keyup(function(e) {
if(e.which===27){ modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key
});
function unlockModal() {
locked = false;
}
function lockModal() {
locked = true;
}
});//each call
}//orbit plugin call
})(jQuery);
Here is the html trigger:
<a class="big-link" href="#" data-reveal-id="myModal">Click Me to open modal</a>
Here is the code.php, file containing the modal:
<div id="myModal" class="reveal-modal"><div>content called from DB using passed variable</div><p>more content</p><a class="close-reveal-modal">×</a>
The issue at the minute is not passing the variable, but actually lauching the modal with the content of code.php
Thanks again for your time with this problem!
Without knowing what variables you're looking to pass, and what you're trying to grab, you can modify this. I haven't tested it so you may have to do some tweaking.
$('a[data-reveal-id').live('click', function(e)
{
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$.ajax({
url: 'URL_TO_YOUR_PHP',
data: 'YOUR_VARIABLE', // Look at how to pass data using GET, or POST
type: 'GET' or 'POST', // Choose one, and pass the data above appropriately
error: function()
{
// If there's an issue, display an error...
},
success: function(output)
{
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
}
});
})
-- EDIT --
Now the problem is that you don't have #myModal available in your HTML, yet. So, what you want to do is change the following line accordingly:
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
-- BECOMES --
$("body").append(output).reveal( $(this).data() );
In your CSS you'll want to initially hide your modal box that way it's revealed appropriately.
Related
I'm having some conflicting issues with my Laravel setup, specifically with the pagination and product filters.
Both pagination and product filters is being handled via jQuery so the page doesn't completely refresh.
This is my jQuery pagination code, working with the standard Laravel ->paginate functionality.
$(function() {
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
var page_number = $(this).attr('href').split('page=')[1];
getProducts(page_number);
window.history.pushState("", "", url);
});
function getProducts(page_number) {
$.ajax({
url : '?page=' + page_number
}).done(function (data) {
$('.devices-holder').html(data);
}).fail(function () {
alert('Data could not be loaded.');
});
}
});
This works great, the issue is when we filter the products, and then try and go to another page on the filtered results.
Right after filtering, the paginate links are correct for example /devices/filter?filter=1&page2, however on clicking this the page loads all devices without the filter, even though if I copy that url and load that page, it succesfully goes to page 2 with the filters included.
Then the paginate URL's are completely ignoring the filter afterwards, and is /devices?&page=2. I figured it must be to do with me rendering and appending the paginate links in the view, but am unsure what I am doing wrong:
{!! $devices->appends(Input::all())->render() !!}
This is my controller:
public function devicesByFilter(Request $request) {
$type = 'devices';
$types = Input::get('types');
$devices = Device::where('type', '=', $type)->where('approved', '=', 1);
if(!empty($types)) {
$url = 'filter';
$check = 0;
foreach($types as $deviceType) {
if($check == 0) {
$devices = $devices->where('device_type', 'LIKE', $deviceType);
} else {
$devices = $devices->orWhere('device_type', 'LIKE', $deviceType);
}
$url = $url.'&types%5B%5D='.$deviceType;
$check++;
}
}
$devices = $devices->orderBy('match_order', 'asc')->paginate(10);
$devices->setPath('filter');
if ($request->ajax()) {
return view('devices.ajax.loadfilter', ['devices' => $devices, 'type' => $type, 'types' => $types])->render();
}
return View::make('devices.all', compact('devices', 'type'));
}
And this is my filter jQuery code:
$(document).ready(function () {
var types = [];
// Listen for 'change' event, so this triggers when the user clicks on the checkboxes labels
$('input[name="type[]"]').on('change', function (e) {
e.preventDefault();
types = []; // reset
if ( document.location.href.indexOf('filter') > -1 ) {
var url = '../devices/filter?type=device';
} else {
var url = 'devices/filter?type=device';
}
$('input[name="type[]"]:checked').each(function()
{
types.push($(this).val());
url = url+'&types%5B%5D='+$(this).val();
});
if ( document.location.href.indexOf('filter') > -1 ) {
$.get('../devices/filter', {type: 'devices', types: types}, function(markup)
{
$('.devices-holder').html(markup);
});
} else {
$.get('devices/filter', {type: 'devices', types: types}, function(markup)
{
$('.devices-holder').html(markup);
});
}
window.history.pushState("", "", url);
});
});
So at a poor attempt to clarify:
Pagination jQuery works perfect
Filtering works perfect
Trying to go another page after filtering displays all devices not just the filtered ones, even though the URL is correct and if I load this URL again on another tab, it has the right results.
After trying to go to another page of filtered results, the pagination links are missing the append input.
It's very difficult to debug this from here, anyone who can point in the right direction or something to try/test would be great.
Fixed it by changing
$(function() {
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
var page_number = $(this).attr('href').split('page=')[1];
getProducts(page_number);
window.history.pushState("", "", url);
});
function getProducts(page_number) {
$.ajax({
url : '?page=' + page_number
}).done(function (data) {
$('.devices-holder').html(data);
}).fail(function () {
alert('Data could not be loaded.');
});
}
});
to
$(function() {
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
getProducts(url);
window.history.pushState("", "", url);
});
function getProducts(url) {
$.ajax({
url : url
}).done(function (data) {
$('.devices-holder').html(data);
}).fail(function () {
alert('Data could not be loaded.');
});
}
});
I have a site that uses ajax to load a post directly to the page when clicked.
But... I also have an ajax contact-form at the same page. But if I click a post first, then want to send a message later, it fails. But if I refresh the page and go straight to the contact-form and send a message it doesn't fail at sending. Is there any way that I can maybe "reload" ajax without refreshing the page so that you can do multiple things at my site with ajax?
$(document).ready(function() {
function yournewfunction() {
var requestCallback = new MyRequestsCompleted({
numRequest: 3,
singleCallback: function() {
alert("I'm the callback");
}
});
var width = 711;
var animationSpeed = 800;
var pause = 3000;
var currentSlide = 1;
var $slider = $("#slider");
var $slideContainer = $(".slides");
var $slides = $(".slide");
var $toggleRight = $("#right");
var $toggleLeft = $("#left");
$toggleRight.click(function() {
$slideContainer.animate({
'margin-left': '-=' + width
}, animationSpeed, function() {
currentSlide++;
if (currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
});
$toggleLeft.click(function() {
if (currentSlide === 1) {
currentSlide = $slides.length;
$slideContainer.css({
'margin-left': '-' + width * ($slides.length - 1) + 'px'
});
$slideContainer.animate({
'margin-left': '+=' + width
}, animationSpeed, function() {
currentSlide--;
});
} else {
$slideContainer.animate({
'margin-left': '+=' + width
}, animationSpeed, function() {
currentSlide--;
});
}
});
if ($(".slide img").css('width') == '400px' && $(".slide img").css('height') == '400px') {
$(".options").css("width", "400px");
$(".slide").css("width", "400px");
$("#slider").css("width", "400px");
$(".video-frame").css("width", "400px");
var width = 400;
};
if ($("#slider img").length < 2) {
$("#right, #left").css("display", "none");
};
if ($("iframe").length > 0 && $("iframe").length < 2) {
$(".options").css("width", "711px");
$(".slide").css("width", "711px");
$("#slider").css("width", "711px");
$(".video-frame").css("width", "711px");
$('.slide').hide();
var width = 711;
};
if ($(".slide img").css('width') > '400px' && $(".slide img").css('width') < '711px') {
$(".options").css("width", "600px");
$(".slide").css("width", "600px");
$("#slider").css("width", "600px");
$(".video-frame").css("width", "600px");
var width = 600;
};
}
$.ajaxSetup({
cache: false
});
$(".post-link").click(function(e) {
e.preventDefault()
var post_link = $(this).attr("href");
$("#single-post-container").html('<img id="loads" src="http://martinfjeld.com/wp-content/uploads/2015/09/Unknown.gif">');
$("#single-post-container").load(post_link, function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
} else {
$("#main-content").fadeIn(500);
$("body").addClass("opens");
yournewfunction();
}
});
requestCallback.requestComplete(true);
return false;
});
});
$(function() {
var form = $('#ajax-contact');
var formMessages = $('#form-messages');
$(form).submit(function(event) {
event.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
Though it's hard to follow exactly what is going on without being able to see the context of your HTML and without you giving us a more concrete description of exactly which line of code fails to execute, this is likely because one Ajax call is replacing a bunch of HTML which clobbers all your event handlers. So, when you then try to do the second Ajax operation, it's click handler is no longer in force so nothing happens.
Replacing a DOM element loses all event handlers that were attached to the original DOM element. Using .html() or assigning to .innerHTML replaces all the DOM elements within that element, thus losing all their event handlers.
The typical solution to this is to either reinstall the event handlers after replacing the content that you want event handlers on or use delegated event handling from a parent element that is not replaced.
Here are some references on delegated event handling:
JQuery Event Handlers - What's the "Best" method
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Does jQuery.on() work for elements that are added after the event handler is created?
Should all jquery events be bound to $(document)?
I have a form using Janko At Warpseeds Form to Wizard Plugin alongside the ImagePicker plugin and I would like to make sure all the images are selected before being able to click Next.
I am currently using Bassassistance validation plugin.
Does anyone have any idea how I could implement this?
JSFiddle showing current working code and all javascript here http://jsfiddle.net/4Hkxy/
$(function () {
jQuery(function($){
var $signupForm = $( '#multipage' );
$signupForm.formToWizard({
submitButton: 'SaveAccount',
showProgress: true, //default value for showProgress is also true
nextBtnName: 'Forward >>',
prevBtnName: '<< Previous',
showStepNo: false,
validateBeforeNext: function() {
var selectedCount = $('.thumbnails.image_picker_selector:visible .selected').length;
var totalCount = $('.thumbnails.image_picker_selector:visible').length;
if(selectedCount != totalCount) {
alert('please select an image per selection');
}
}
});
});
$("select.image-picker").imagepicker({
hide_select: true,
show_label: true,
});
$("select.image-picker.show-labels").imagepicker({
hide_select: true,
show_label: true,
});
var container = $("select.image-picker.masonry").next("ul.thumbnails");
container.imagesLoaded(function () {
container.masonry({
itemSelector: "li",
});
});
Any help would be appreciated.
Try this:
//inside "next.onclick" handler
var selectedCount = $('.thumbnails.image_picker_selector:visible .selected').length;
var totalCount = $('.thumbnails.image_picker_selector:visible').length;
if(selectedCount != totalCount) {
alert('please select an image per selection');
}
Ok this is my issue if anyone can help, please.
I have a href that div id to switch content - I would like to add another document ready function javascript without conflicting with make tab I have already.
Example of make tab already:
<script type="text/javascript">
{literal}
$(document).ready(function(){
function makeTabs(selector) {
var tabContainers = $(selector + ' > div');
tabContainers.removeClass("selected").filter(':first').addClass("selected");
galleryRendered = false;
$(selector + ' > ul a').click(function () {
tabContainers.removeClass("selected");
tabContainers.filter(this.hash).addClass("selected");
$(selector + ' > ul a').removeClass('selected');
$(this).addClass('selected');
if (this.hash == '#Pictures' && !galleryRendered)
{
var galleries = $('.pictures > .ad-gallery').adGallery({
effect : 'slide-hori',
enable_keyboard_move : true,
cycle : true,
animation_speed : 400,
slideshow: {
enable: false
},
callbacks: {
init: function() {
this.preloadImage(0);
this.preloadImage(1);
this.preloadImage(2);
}
}
});
galleryRendered = true;
}
if (this.hash == '#OnTheMap') document.getElementById("Map").map.onContainerChanged();
return false;
}).filter(':first').click();
}
makeTabs('.tabs');
});
{/literal}
</script>
Want to create a second one so I can create tabs inside of an existing div id area/content to switch from photo to video to youtube.
<div class=".tabs"><ul><li>[[Photo]]</li><li>[[Youtube]]</li><li>[[Video]]</li></ul><div id="photo">Test</div><div id="tube">Test</div><div id="vid">Test</div></div>
This will be inside a div id that already exist that uses the first tab creator shown above.
In jQuery you just have to do this:
$(function(){
// code here
});
$(function(){
// more code here
});
Every function declared like this will be executed on domready.
I'm trying to pass a variable via jquery ajax call. I'm not exactly sure how to do it properly. I get the lon lat coordinates through another html5 script.
How do i get the coordinates on the other side? I tried $_GET(lat).
I'm also not sure if i'm able to use the location.coords.latitude in a different < script >.
$.ajax({
cache: false,
url: "mobile/nearby.php",
dataType: "html",
data: "lat="+location.coords.latitude+"&lon="+loc.coords.longitude+,
success: function (data2) {
$("#nearbysgeo").html(data2);
}
});
These scripts are above the jquery code
<script type="text/javascript">
google.setOnLoadCallback(function() {
$(function() {
navigator.geolocation.getCurrentPosition(displayCoordinates);
function displayCoordinates(location) {
var map = new GMap2(document.getElementById("location"));
map.setCenter(new GLatLng(location.coords.latitude, location.coords.longitude), 12);
map.setUIToDefault();
var point = new GLatLng(location.coords.latitude, location.coords.longitude);
var marker = new GMarker(point);
map.addOverlay(marker);
}
})
});
</script>
<script type="text/javascript" charset="utf-8">
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
document.getElementById("output").innerHTML = "Your browser doesn't handle the GeoLocation API. Use Safari, Firefox 4 or Chrome";
}
}
function success(loc){
console.log(loc);
strout = "";
for(l in loc.coords){
//strout += l +" = " +loc.coords[l] + "<br>";
}
strout += '';
strout += '<center><img src="http://maps.google.com/maps/api/staticmap?center='+loc.coords.latitude+','+loc.coords.longitude+'&markers=color:blue%7Clabel:Y%7C'+loc.coords.latitude+','+ loc.coords.longitude+'&zoom=15&size=400x250&sensor=false¢er=currentPosition"></center>';
document.getElementById("output").innerHTML = strout;
document.forms['newPostForm'].lat.value = loc.coords.latitude;
document.forms['newPostForm'].lon.value = loc.coords.longitude;
document.getElementById("coords").innerHTML = '';
document.getElementById("coords").innerHTML = 'CURRENT: Lat:' + loc.coords.latitude + ' Lon:' + loc.coords.longitude;
}
function error(err){
document.getElementById("output").innerHTML = err.message;
}
function clearBlog() {
document.getElementById("listview").innerHTML = '';
}
</script>
ADDITIONAL INFO:
It works if I use this line. So i guess i can't use loc.coords.latitude this way.
data: "&lat=43&lon=-79.3",
Well i hacked it for now to get it working. I filled two hidden form elements on the page with lon and lat values. Then used 'document.forms['newPostForm'].lat.value' to create a line like this.
data: "&lat="+document.forms['newPostForm'].lat.value+"&lon="+document.forms['newPostForm'].lon.value,
Still would like an actual solution.
Here's some code from a project I'm working on. Very simple.
$.post("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
You can switch out .post with .get with no other changes, like so:
$.get("../postHandler.php", { post_action: "getRecentPosts", limit: "10" }, function(data){
$("#post-list").html(data);
Data is passed in name value pairs like so.
{ post_action: "getRecentPosts", limit: "10" }
Rewrite:
$.get("mobile/nearby.php", { lat: location.coords.latitude, lon: loc.coords.longitude }, function(data2){
$("#nearbysgeo").html(data2);
});
$lat = preg_replace('#[^0-9\.]#', '', $_GET['lat']);
You probably can use location.coords.latitude if it is defined before.
jQuery.ajax(
{
url : 'mobile/nearby.php',
data : {
'action' : 'update',
'newname' : 'enteredText',
'oldname' : 'original_html',
'userid' : '10'
},
success : function(msg){
if(msg == 1)
{
alert('success');
}
}
});
this is the proper syntax of jQuery.Ajax(); function