How to initialise JQuery script for dynamically generated ids - php

EDIT:: My brain's smoking :) Perhaps I'm looking at this from the wrong angle? We need the JQuery to initialise for each dynamically generated id. Do we have to run the JQuery for each and every id (ie. place it in our PHP loop)??
How can we make this JQuery script apply to a dynamically generated list of ids where the ids increase by 1 when looped with PHP?
Here's the JQuery:
$(document).ready(function(){
$('#slider').unoslider({
scale: 'true',
responsive: 'true',
touch: 'true',
preset: 'bar_fade_left',
navigation: {autohide: true},
slideshow: {speed: 5, timer: false},
animation: {delay: 200}
});
});
And here the dynamically generated ids:
<?php echo "<ul id="slider'.$counter.'" class="unoslider">";?>
Thanks for any help!!

I created a simple plugin which lets me initialize elements based on data-* attributes:
<?php echo "<ul data-jquery-bind='unoslider' ".
"data-jquery-options='" . htmlspecialchars(json_encode($unoSliderOptions), ENT_QUOTES) . "'>;"?>
Here is the plugin:
$.fn.jqueryBind = function() {
return (this.length ? this : $('body')).each(function() {
var $root = $(this);
$root.find('[data-jquery-bind]').each(function() {
var jqueryFn = $(this).attr('data-jquery-bind');
var options = $(this).attr('data-jquery-options');
if (options) {
options = $.parseJSON(options);
}
$(this)[jqueryFn](options);
});
});
};
Then add:
$(function() {
$.jqueryBind();
});
And it will automatically search for elements with the attribute data-jquery-bind and initialize the plugin using the json serialized options in data-jquery-options.

You can use this selector -
$('ul[id^="slider"].unoslider')

Related

tinymce on textarea generated by php/jquery post

I have tinymce working well FIRST time you click the button, but after that it doesn't init anymore, no errors however.
To get editor again you need to refresh page.
Is it possible to get init editor to the text area every time you open the modal without refreshing page ?
$(document).ready(function() {
$(document).on('click', '.btn.modal', function() {
var title = $('.modal-title'),
content = $('.modal-body'),
footer = $('.modal-footer');
$.post('units.php', { addnew: 'unit' }, function(r) {
title.html(r.title);
content.html(r.content);
footer.html(r.btns);
tinymce.init({ selector: 'textarea' });
$('#modal').modal('show');
},'json');
});
});
The problem is you are using the general initialisating, which probably conflits with the textarea(s) which already have been initialised... .
The best way to solve this is by destroying all the initialised tinymce first using:
$('textarea').tinymce().re‌​move();
and then initialising them again like this:
tinymce.init({ selector: 'textarea' });
In your example this would be:
$(document).ready(function() {
$(document).on('click', '.btn.modal', function() {
var title = $('.modal-title'),
content = $('.modal-body'),
footer = $('.modal-footer');
$.post('units.php', { addnew: 'unit' }, function(r) {
title.html(r.title);
content.html(r.content);
footer.html(r.btns);
$('textarea').tinymce().re‌​move();
tinymce.init({ selector: 'textarea' });
$('#modal').modal('show');
},'json');
});
});

amCharts js doesnt work with ajax call?

I am trying create map with amCharts using jquery ajax but it doesnt work with ajax.
here my ajax code:
$('button#btn').click(function(){
$('div#ozellikli').html('<center><img src="assets/img/loading.gif" width="200" height="200"/></center>')
$.ajax({
type:'post',
url:'ozellikliAjax.php',
data:$('form#oz').serialize(),
success:function(msg){
$('div#ozellikli').html(msg);
}
});
});
Here my ajax php code:
<?php
include 'config.php';
$html="";
$yil=$_POST['yil'];
$tur=$_POST['tur'];
///HARITAYI CIZ
$sql="SELECT id,il,COUNT(kurum) AS kurum_Say FROM ozellikli GROUP BY id,il ORDER BY kurum_Say";
$result=$baglanti->query($sql);
$mapChart="";
while ($query=$result->fetch(PDO::FETCH_ASSOC)) {
$mapChart.=' { title: "'.$query['il'].':'.$query['kurum_Say'].'", id: "TR'.$query['id'].'",value:'.$query['kurum_Say'].', selectable: true },';
}
$html.='<script type="text/javascript">
AmCharts.ready(function() {
var map;
// *** CREATE MAP ***********************************************************
function createMap(){
map = new AmCharts.AmMap();
map.pathToImages = "http://www.ammap.com/lib/images/";
//map.panEventsEnabled = true; // this line enables pinch-zooming and dragging on touch devices
var dataProvider = {
mapVar: AmCharts.maps.turkeyLow
};
map.areasSettings = {
unlistedAreasColor: "#43B1A9",
rollOverOutlineColor: "#FFFFFF"
};
map.colorSteps=5;
map.valueLegend={
left: 10,
bottom:0,
minValue: "En Az",
maxValue: "En Çok"
};
dataProvider.areas = ['.$mapChart.'];
map.dataProvider = dataProvider;
map.addListener(\'clickMapObject\', function (event) {
// deselect the area by assigning all of the dataProvider as selected object
map.selectedObject = map.dataProvider;
// toggle showAsSelected
event.mapObject.showAsSelected = !event.mapObject.showAsSelected;
// bring it to an appropriate color
map.returnInitialColor(event.mapObject);
var states = [];
for (var i in map.dataProvider.areas) {
var area = map.dataProvider.areas[i];
if (area.showAsSelected) {
states.push(area.title);
}
}
});
map.write("mapdiv");
}
createMap();
});
</script>';
echo $html;
?>
when run the ajax code , script loading with ajax correctly but its not charting to map.
How can I solve this issue?
thanks
If you inject the resources the same way, you need to set manually it's ready state otherwise it won't work. AmCharts listens to the dom loaded event to set following property:
AmCharts.isReady = true;

Jquery selector not working after append

I have a php script that I call that returns html in a way that it can be directly inserted into a container or the body and just work (E.X. '<image id="trolleyLogoEdge" class="pictureFrame party" src="tipsyTrixy.png" >'). After appending this text to a div the selector $('#pictureFrame > img:first') won't work. I'm not using event handlers or anything so I don't know why I'm having an issue. My code worked fine when I just had the image tags in the div without any manipulation so I'm assuming it must be a selector issue. I have tested my php output and it is exactly matching the html that was in the div before I decided to dynamically populate the div.
var classType = '';
var classTypePrev = '';
var width = $(window).width();
var height = $(window).height();
var size = (height + width)/2;
var time = 0;
$( document ).ready(function()
{
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
startSlideshow($('#pictureFrame > img:first'));
});
});
window.onresize = function()
{
width = $(window).width();
};
function startSlideshow(myobj)
{
classType = $(myobj).attr('class').split(' ')[1];
if(classTypePrev != classType)
{
$('.picDescription').animate({'opacity': "0"},{duration: 2000,complete: function() {}});
$('.picDescription.' + classType).animate({'opacity': "1"},{duration: 3000,complete: function() {}});
}
classTypePrev = classType;
myobj.animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) - 150), opacity: '1'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function() {}}).delay(2000).animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) + 150), opacity: '0'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function()
{
$(myobj).css("left", "100%");
}
});
setTimeout(function()
{
var next = $(myobj).next();
if (!next.length)
{
next = myobj.siblings().first();
}
startSlideshow(next)},9000);
}
Your code that appends the data to the frame has a typo in the ID selector.
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
^^here
startSlideshow($('#pictureFrame > img:first'));
});
It should probably be
$('#pictureFrame').append(data);
.find() gets the descendants of each element in the current set of matched elements.
> selects all direct child elements specified by "child" of elements specified by "parent".
Try:
startSlideshow($("#pictureFrame").find("img:first"));
If img is not direct child of #pictureFrame, .find() should work.
You should know the difference between
Delegated Event
Direct Event
check this for the difference between direct and delegated events.
If we were to click our newly added item, nothing would happen. This is because of the directly bound event handler that we attached previously. Direct events are only attached to elements at the time the .on() method is called. In this case, since our new anchor did not exist when .on() was called, it does not get the event handler.
check this link to official JQuery Document for further clarification.

Too much recursion on ajax call

I am usining masonry view to display content with infinite scrolling functionality.
Masonry view part is working fine. For infinite scroll I have tried infinitescroll js
or on the basis of scroll as I have written below code.
Problem :- After first scroll I am facing too much recursion problem.
jQuery(document).ready(function($) {
var $container = jQuery('.main_container');
$container.imagesLoaded(function(){
// options
$container.masonry({
itemSelector: '.pin',
isAnimated: true,
isFitWidth: true,
isAnimatedFromBottom: true
});
});
//for infinite scrollings
jQuery(window).scroll(function() {
if(jQuery(window).scrollTop() + jQuery(window).height() == jQuery(document).height()) {
alert("bottom!");
ajaxurl = "script url here";
var data = {start:startLimit,end:endLimit};
jQuery.get(ajaxurl, data, function(response) {
var $boxes = $(response);
$('.main_container').append( $boxes ).masonry( 'appended', $boxes );
});
}
});
});
I am trying this on wordpress admin section plugin.
After step-by-step checking I found solution , Cause of the problem I am using animate effect in masonry which is conflict some how with wordpress plugin view js.
$container.imagesLoaded(function(){
// options
$container.masonry({
itemSelector: '.pin',
isAnimated: false,
isFitWidth: true,
isAnimatedFromBottom: false
});
});

Update Flot plot with 2 series in realtime

I'm working on displaying 2 time series of values using jquery and flot. I'm using them for a small period of time and for now I'm sticking to the examples. Basically I adapted several examples to extract from MySQL database the series using a PHP script that I include in the JQuery script. All works fine this far. I wish to be able to refresh this series every several seconds. This refresh doesn't seem to work and I'm not sure why. Bellow is the jquery code used to generate the graph. I put now part one of the script.
$(function(){
//add data source to flot. 2 datasets with same structure: data in UNIX_TIMESTAMP format, value in DECIMAL format
<?php include 'datasource.php'; ?>;
//declare datasets
var datasets = {
"temperature": {
label: "Temperature (C)",
data: <?php echo json_encode($dataset1); ?>
},
"humidity": {
label: "Humidity (%)",
data: <?php echo json_encode($dataset2); ?>
}
};
//set fixed colors for each series
var i = 0;
$.each(datasets, function(key, val) {
val.color = i;
++i;
});
// insert checkboxes
var choiceContainer = $("#choices");
$.each(datasets, function(key, val) {
choiceContainer.append(' <input type="checkbox" name="' + key +
'" checked="checked" id="id' + key + '">' +
'<label for="id' + key + '">'
+ val.label + '</label>');
});
choiceContainer.find("input").click(plotAccordingToChoices);
//define plot options
var options = {series: { shadowSize: 0 },
yaxis: { min: <?php echo json_encode($mintemp) ?>, max: <?php echo json_encode($maxtemp) ?> },
xaxis: { show: true, mode: "time", timeformat: "%h:%M %d.%m.%y", labelWidth: "10"}};
//draw plot
function plotAccordingToChoices() {
var data = [];
choiceContainer.find("input:checked").each(function () {
var key = $(this).attr("name");
if (key && datasets[key])
data.push(datasets[key]);
});
if (data.length > 0)
$.plot($("#placeholder"), data, options);
}
plotAccordingToChoices();
//define plot refresh timeout
setInterval(plotAccordingToChoices(), 3000);})
The first argument to setInterval should to be a string:
setInterval('plotAccordingToChoices()', 3000);
Or only the function name (not calling it):
setInterval(plotAccordingToChoices, 3000);
See: https://developer.mozilla.org/en/window.setInterval
To get updated data from the server-side (PHP), you also need to do remote calls (AJAX). You may use jQuery getScript function.
Something like this:
function updatePlot() {
$.getScript('update_plot.php');
}
setInterval(updatePlot, 3000);
Then, in your update_plot.php file, you can return JavaScript code mixed with PHP (just like you already did):
<?php // here some PHP code to get your data ?>
// and here some javascript code to use the data
plotAccordingToChoices(); // and finally update the plot

Categories