I have a JavaScript in the view but it's not executing again after loading different content with AJAX, so I want to place it in the <head> of the view to be isolated from AJAX without having to put it in a file because it's using PHP arrays from the controller. How do I do it? Is there a way to write JavaScript code the CakePHP way and set it as inline false the same way as JavaScript files?
It seems like even JavaScript codes places in head will not execute with AJAX so how should I do it? Should I place JavaScript related divs outside the content div or what?
This is my view:
<script>
var geocoder, lat, lng;
function initialize() {
var location = <?php echo "\"" . $location . "\""?>;
location = location.replace(/\+/g, ' ');
document.getElementById("address").innerHTML = location + " Weather";
var latlng = new google.maps.LatLng(<?php echo $loc['lat'];?>, <?php echo $loc['lng'];?>);
var mapOptions = {
zoom: 12,
center: latlng,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
draggable: false,
scrollwheel: false,
disableDoubleClickZoom: true,
zoomControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
<?php $i = 0 ?>
<?php foreach ($posts as $post): ?>
var markerLatlng = new google.maps.LatLng(<?php echo h($post['Post']['latitude']); ?>, <?php echo h($post['Post']['longitude']); ?>);
var marker = new google.maps.Marker({
position: markerLatlng,
map: map,
title: '<?php echo h($post['Post']['temperature']); ?>',
icon: 'http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.6|0|FF0000|12|_|<?php echo h($post['Post']['temperature']); ?>',
url: '<?php echo $this->Html->url(array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>'
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
<?php endforeach; ?>
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyBoEBzeiYi-bCaTIlcK7lrNKUyvUfLQqGM&sensor=false&callback=initialize®ion=LB";
document.body.appendChild(script);
}
$(document).ready(function(){
$(".post .toggle").toggle(function(){
$(".post .toggle").css('background-image','url(../../img/down.png)');
$(this).css('background-image','url(../../img/up.png)');
$(".post .description").hide();
$(this).parent().find(".description").show("slow");
$(".post").height(100);
$(this).parent().height(200);},
function() {$(".post .toggle").css('background-image','url(../../img/down.png)');$(".post").height(100);$(".post .description").hide();$(this).css('background-image','url(../../img/down.png)');
});
});
window.onload = loadScript;
</script>
<div id="weather">
<center><div id="address"> </div>
<p><div id="coords"><?php echo $loc['lat'] . ", " . $loc['lng'];?></div></p></center>
<div id="weather-menu">
<?php echo $this->Html->link('Today', 'today/' . $location);?>
<?php echo $this->Html->link('Yesterday', 'yesterday/' . $location);?>
<?php echo $this->Html->link('Custom', 'custom/' . $location);?>
<?php echo $this->Html->link('All', 'all/' . $location);?>
</div>
<div id="post-container">
<?php /*
if ($posts) {
echo "<div id=\"post\"><div id=\"temperature\">";
echo $posts[0]['Post']['temperature'] . "°C</div>";
if ($posts[0]['Humidity']['humidity'])
echo "<div id=\"humidity\">" . $posts[0]['Humidity']['humidity'] . "%</div>";
echo "<div id=\"created\">" . $this->Time->niceShort($posts[0]['Post']['created']) . " </div>";
echo "<div id=\"username\">" . $posts[0]['User']['username'] . "</div>";
echo "<div id=\"condition\">";
if (strtotime($posts[0]['Post']['created']) > date_sunrise(strtotime($posts[0] ['Post']['created']), SUNFUNCS_RET_TIMESTAMP, $posts[0]['Post']['latitude'], $posts[0] ['Post']['longitude'],90, 2) && strtotime($posts[0]['Post']['created']) < date_sunset(strtotime($posts[0]['Post']['created']), SUNFUNCS_RET_TIMESTAMP, $posts[0]['Post']['latitude'], $posts[0]['Post']['longitude'],90, 2))
echo $this->Html->image('/img/weather-icons/' . $posts[0]['Post']['condition'] . 'A.png');
else
echo $this->Html->image('/img/weather-icons/' . $posts[0]['Post']['condition'] . 'B.png');
echo "</div></div>";
}*/
?>
<?php
//$posts = $this->requestAction('/weather/fetch');
foreach (array_slice($posts, 0) as $post) {
echo "<div class=\"post\"><div class=\"temperature\">";
echo $this->Html->link($post['Post']['temperature'] . "°C", array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])) . "</div>";
if ($post['Humidity']['humidity'])
echo "<div class=\"humidity\">" . $post['Humidity']['humidity'] . "%</div>";
echo "<div class=\"created\">" . $this->Time->niceShort($post['Post']['created']) . "</div>";
echo "<div class=\"username\">" . $this->Html->link($post['User']['username'], array('controller' => 'users', 'action' => 'view', $post['Post']['user_id'])) . "</div>";
echo "<div class=\"condition\">";
if (strtotime($post['Post']['created']) > date_sunrise(strtotime($post['Post']
['created']), SUNFUNCS_RET_TIMESTAMP, $post['Post']['latitude'], $post['Post']['longitude'],90, 2) && strtotime($post['Post']['created']) < date_sunset(strtotime($post['Post']['created']), SUNFUNCS_RET_TIMESTAMP, $post['Post']['latitude'], $post['Post']['longitude'],90, 2))
echo $this->Html->image('/img/weather-icons/' . $post['Post']['condition'] . 'A.png');
else
echo $this->Html->image('/img/weather-icons/' . $post['Post']['condition'] . 'B.png');
echo "</div>";
echo "<div class=\"description\">" . $post['Description']['description'] . "</div>";
echo "<div class=\"toggle\"></div>";
echo "</div>";
}
?>
</div>
<div id="side-container">
<div id="map_canvas"></div>
<br/>
<div id ="current"><?php if (isset($w_temp)) echo "Current Temperature: " . $w_temp . "°C" . $this->Html->image('/img/wg.png');?></div>
</div>
<?php
$this->Paginator->options(array(
'update' => '#content',
'before' => $this->Js->get('#busy-indicator')->effect('fadeIn', array('buffer' => false)),
'complete' => $this->Js->get('#busy-indicator')->effect('fadeOut', array('buffer' => false))
));
echo $this->Paginator->prev('« Previous ', null, null, array('class' => 'disabled'));
echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled'));
echo $this->Js->writeBuffer();
?>
<div id="busy-indicator"></div>
</div>
and this is my controller index action:
public function index($date, $location = null) {
$this->set('location', $location);
$address = urlencode($location);
$loc = $this->getLocation($address);
$this->set('loc', $loc);
$this->loadModel('Post');
if ($date == 'all') {
$this->paginate = array('conditions' => array(
'latitude BETWEEN ? AND ?' => array(
$loc['lat'] - 0.05, $loc['lat'] + 0.05),
'longitude BETWEEN ? AND ?' => array(
$loc['lng'] - 0.05, $loc['lng'] + 0.05)
),
'order' => array('Post.created' => 'desc'),
'limit' => '5');
$this->set('posts', $this->paginate('Post'));
}
else if ($date == 'today') {
$this->set('posts', $this->Post->find('all', array(
'conditions' => array(
'latitude BETWEEN ? AND ?' => array(
$loc['lat'] - 0.05, $loc['lat'] + 0.05),
'longitude BETWEEN ? AND ?' => array(
$loc['lng'] - 0.05, $loc['lng'] + 0.05),
'Post.created >' => date('Y-m-d H:i:s', strtotime("-1 day"))
),
'order' => array('Post.created' => 'desc'))));
}
else if ($date == 'yesterday') {
$this->set('posts', $this->Post->find('all', array(
'conditions' => array(
'latitude BETWEEN ? AND ?' => array(
$loc['lat'] - 0.05, $loc['lat'] + 0.05),
'longitude BETWEEN ? AND ?' => array(
$loc['lng'] - 0.05, $loc['lng'] + 0.05),
'Post.created >' => date('Y-m-d H:i:s', strtotime("-2 day")),
'Post.created <' => date('Y-m-d H:i:s', strtotime("-1 day"))
),
'order' => array('Post.created' => 'desc'))));
}
$this->wunder($location);
}
Thank you guys. I just needed to add this to my javascript code:
var pathname = window.location.pathname;
window.onload = loadScript;
$(document).ready(function() {
$.ajax({
url: pathname,
success: function(){
loadScript();
}
})
});
You wrote:
I have a JavaScript in the view but it's not executing again after
loading different content with AJAX
I only briefly looked at what you are doing but I didn't immediately see where you are making an AJAX request. Clarifying that point would be helpful, as others have noted. However, be aware that After loading new content with AJAX if your script had event handlers on any replaced content then you will need to destroy and recreate the event handlers in Javascript (even if you replaced it with identical DOM elements).
To this point:
Is there a way to write JavaScript code the CakePHP way and set it as
inline false the same way as JavaScript files?
So you do this essentially the same way as you reference external source files in cakePHP, you can replace:
<script>
...
</script>
with the following:
$this->Html->ScriptBlock('your javascript here', array('inline'=>false));
Then in the section make sure you have (for cakePHP 2.1 or newer):
echo $this->fetch('script');
or (for cakePHP 2.0x or earlier)
$scripts_for_layout();
Since you're using "AJAX" to inject a script into a page i suppose, the way you are doing it is by using jQuery maybe or anything pulling your content into the DOM via element.innerHTML = content, am I wrong ?
BUT scripts passed in element.innerHTML will not execute, and this is what jQuery use to fragment your HTML response !
The best way to do it IMHO is to use "AJAX" only to get the data from your CakePHP app to the javascript front end (with a JSON response), then you will use this data within your javascript code to display your charts. It would be much more efficient, and you would not have the issues shoesole is talking about loosing DOM elements references.
Or you can do this the lazy way, with this hack :
<img style="display:none" src="data:image/png,script" onerror="
console.log('Hey I am javascript code running as long as javascript isnt disabled!');
"/>
<script>
// this is new invention like JSON it seem cute function but it is not
function connect_php() {
jQuery(document).ready(function($){
setTimeout(function() {
$("#final_result").css('display', 'block');
}, 4000); //here 1000 means 1 second
});
}
jQuery(document).ready(function($){
(function a(x) {
// The following condition
// is the base case.
if ( ! x) {
return;
}
a(--x);
event.preventDefault();
$( "#aform" ).submit();
connect_php();
})(10);
});
</script>
if you have php for loop doing something must wait this will fired after php finish or your loop finish send message from php to JavaScript defined in JS from start
Related
I had to redirect the visitor to another page if something went wrong. Header location couldn't work because there is already some things displayed so I only have the choice to use javascript. Here is a piece of my PHP code :
add_action('frm_field_input_html', 'getDoctypes');
function getDoctypes($field, $echo = true){
$url = 'http://ff/interface/iface.php';
$html = '';
if ($field['id'] == get_id_from_key_frm('doctype')){
$data = array('action' => 'getDoctypes');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'timeout' => 30,
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$return = file_get_contents($url, false, $context);
$doctypes = json_decode($return);
if ($return === FALSE || isset($doctypes -> code)){
$wpBaseUrl = site_url();
echo "<script>window.location = '$wpBaseUrl/error-connection-interface/' </script>";
}else{
$html = ">";
foreach ($doctypes as $code => $name){
$html .= "<option value=\"$code\">$name</option>";
}
}
}
if ($echo)
echo $html;
return $html;
}
The problem is when $return === FALSE, instead of executing the script, it just display "window.location = 'http://my_ip/error-connection-interface/'" into the HTML
Any ideas ?
Thanks in advance
Here's my code:
js
var priorities = {
banner: '300',
avatar: '301'
};
var editableDiv = $('*[data-edit]');
editableDiv.append('<div class="overlay-edit"></div>');
editableDiv.each(function(index, value) {
var actualPriorities = value.getAttribute("data-edit");
console.log(actualPriorities);
console.log(priorities[actualPriorities]);
});
html/php
<div class="hexagon-wrap" style="height:<?php echo $this->outterHeight;?>px; width:<?php echo $this->outterWidth;?>px"
<?php
if($this->htmlOptions) {
foreach ($this->htmlOptions as $key => $value) {
echo $key . "=" . $value . " ";
}
}
?>
>
$this->htmlOptions contains
array('data-edit' => 'avatar')
The output :
banner
300
avatar
undefined
I do not understand why my last result is undefined. When I'm trying
priorities['avatar']; // ouput is 301
The output is good.
The problem is the no breaking space character, and you can improve the code wrapping in quotes:
<div class="hexagon-wrap" style="height:<?php echo $this->outterHeight;?>px; width:<?php echo $this->outterWidth;?>px"
<?php
if($this->htmlOptions) {
foreach ($this->htmlOptions as $key => $value) {
echo $key . "='" . $value . "' ";
}
}
?>
Note that I change the with the ' (with a real space to separate the attributes)
I'm sure I'm not doing this in the correct manner, but I just experimenting to find out the best way to get this done.
Basically, I am using Wordpress, I have created my own theme, based on Thematic.
I have a loop, that is displaying posts from a category.
At the top of the page, I have a menu, which i am trying to use as a filter. So when a user clicks on one of the menu items, it takes the ID of that item, which is the category ID, and then I am trying to use JQuery to replace the contents of a div with the new categories posts.
When i tried using AJAX to load the content, i was getting undefined function errors. So I tried putting the loop into a PHP function inside functions.php.
Here is the function:
function get_vehicle_filter() {
$f = 0;
query_posts( array('cat' => '47', 'orderby' => 'ID', 'order' => 'ASC'));
while ( have_posts() ) : the_post();
$postid = get_the_ID();
$site_url = get_site_url();
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 200,200 ), false, '' );
echo "<a href='$site_url/vehicles-sale-info/?post_id=$postid'>";
echo "<div class='job_image_holder'>";
echo "<img src='$src[0]' class='attachment-post-thumbnail wp-post-image' />";
echo "<div class='job_image_title'>";
the_title( "<p class='white center'>", "</p>" );
echo "</div>";
echo "</div>";
echo "</a>";
$f++;
endwhile;
wp_reset_query();
}
I'm using this to display the loop on the page, which works fine:
<script>
jQuery(document).ready(function(jQuery) {
jQuery("#filtered_vehicles").html("<?php get_vehicle_filter() ?>");
});
</script>
But when i try to get the ID of the clicked menu item into the php function, I am falling down. This is the latest version:
jQuery('.vehicle_filter_item').click(function() {
// capture id from clicked button
var filterCat = jQuery(this).attr('id');
jQuery('#filtered_vehicles').fadeOut('fast', function() {
jQuery("#filtered_vehicles").html('<?php $filterCat = ' + filterCat + '; get_vehicle_filter($filterCat) ?>').fadeIn('fast');
});
});
I know thats not right, and it obviously doesnt work!!
But I've been breaking it down to see what is and isnt working, and if i try to call the function in its simplest form, as I have above when the page is loading, like below, it doesnt work?
jQuery('.vehicle_filter_item').click(function() {
// capture id from clicked button
var filterCat = jQuery(this).attr('id');
jQuery('#filtered_vehicles').fadeOut('fast', function() {
jQuery("#filtered_vehicles").html('<?php get_vehicle_filter() ?>').fadeIn('fast');
});
});
As this works when the page loads, why doesnt it work when replacing with JQuery, the exact same code?
Can anyone point me in the right direction please.
Thanking you!
PHP executes on the server. So when you serve the page, the content inside the jQuery html() is already written. Your function get_vehicle_filter() has been called and the return is what appears inside your jQuery("#filtered_vehicles").html().
What you need to do is inside the click event, make an AJAX call to a file that returns the get_vehicle_filter(). Something like that:
jQuery('.vehicle_filter_item').click(function() {
// capture id from clicked button
var filterCat = jQuery(this).attr('id');
$.ajax({
method: "POST",
url: "file_that_calls_get_vehicle_filter.php",
data: { filter: filterCat }
})
.done(function( result ) {
jQuery('#filtered_vehicles').fadeOut('fast', function() {
jQuery("#filtered_vehicles").html(result).fadeIn('fast');
});
});
});
Hope it sends you on the right path.
Right, this is how I got this working.
Ajax call:
jQuery('.vehicle_filter_item').click(function() {
// capture id from clicked button
var filterCat = jQuery(this).attr('id');
jQuery.ajax({
method: "POST",
url: "ajax-functions.php",
data: "filterCat="+ filterCat,
})
.done(function( result ) {
jQuery('#filtered_vehicles').fadeOut('fast', function() {
jQuery("#filtered_vehicles").html(result).fadeIn('fast');
});
});
});
Function: (which is called on page load)
function get_vehicle_filter() {
$f = 0;
query_posts( array('cat' => '47', 'orderby' => 'ID', 'order' => 'ASC'));
while ( have_posts() ) : the_post();
$postid = get_the_ID();
$site_url = get_site_url();
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 200,200 ), false, '' );
echo "<a href='$site_url/vehicles-sale-info/?post_id=$postid'>";
echo "<div class='job_image_holder'>";
echo "<img src='$src[0]' class='attachment-post-thumbnail wp-post-image' />";
echo "<div class='job_image_title'>";
the_title( "<p class='white center'>", "</p>" );
echo "</div>";
echo "</div>";
echo "</a>";
$f++;
endwhile;
wp_reset_query();
}
Function called through AJAX ajax-functions.php
define('WP_USE_THEMES', false);
require_once('../../../wp-blog-header.php');
if($_POST['filterCat'] == "") {
$filterCat = '47';
} else {
$filterCat = $_POST['filterCat'];
}
$f = 0;
query_posts( array('cat' => $filterCat, 'orderby' => 'ID', 'order' => 'ASC'));
while ( have_posts() ) : the_post();
$postid = get_the_ID();
$site_url = get_site_url();
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 200,200 ), false, '' );
echo "<a href='$site_url/vehicles-sale-info/?post_id=$postid'>";
echo "<div class='job_image_holder'>";
echo "<img src='$src[0]' class='attachment-post-thumbnail wp-post-image' />";
echo "<div class='job_image_title'>";
the_title( "<p class='white center'>", "</p>" );
echo "</div>";
echo "</div>";
echo "</a>";
$f++;
endwhile;
wp_reset_query();
So, basically, the reason I could not get this working was because on the AJAX call, which was a separate file, i was missing these 2 lines at the top:
define('WP_USE_THEMES', false);
require_once('../../../wp-blog-header.php');
I'm somewhat new to Javascript but know enough that I'm aware I shouldn't be writing my Javascript inline with my HTML but instead loading it from an external file. I've been trying to put it in an external file, but because of the way my code works I think it would be better to arrange it in functions that can be called at various points. What is the best practice for this?
At a guess, I'd say I should be wrapping all the JS in a singular file and then calling each code fragment with a function... but I'm not entirely sure how to do that and I'm not knowledgeable enough to know how to pose the question to look around online.
Here's a sample:
<html>
<script type="text/javascript"> <!--Create the arrays-->
var locationLat = new Array();
var locationLong = new Array();
var postURL = new Array();
var postExcerpt = new Array();
var postTitle = new Array();
var featImg = new Array();
var i = 0;
</script>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<script type="text/javascript"> <!--Load data from Wordpress into the arrays so we can use them on a map later-->
locationLat[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLat', true ) ?>";
locationLong[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLong', true ) ?>";
postURL[i] = "<?php echo get_permalink( $id );?>";
postExcerpt[i] = "<?php echo get_the_excerpt();?>";
postTitle[i] = "<?php echo get_the_title($ID);?>";
featImg[i] = "<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>"
i++;
</script>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
<script type="text/javascript">
function initialize() { <!--**I tried putting this function into an external JS file and calling it onLoad with body but it didn't do anythin**g-->
google.maps.visualRefresh = true;
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024,-95.712891),
disableDefaultUI: true,
};
var posts = locationLat.length;
var j = 0;
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var place = new Array();
while (posts != j)
{
var image = '<?php echo get_template_directory_uri(); ?>/location_marker.png';
var myLatLng = new google.maps.LatLng(locationLat[j],locationLong[j]);
place[j] = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
url: postURL[j],
excerpt: postExcerpt[j],
title: postTitle[j],
cover: featImg[j]
});
google.maps.event.addListener(place[j], 'click', function() {
map.panTo(this.getPosition());
map.setZoom(8);
$('#spantext').html(this.title);
$('#poste').html(this.excerpt);
$('.fillme').html('<img src="' + this.cover + '">');
$('.readmore').html('<p>Read more >');
$('.sidebar').show().stop().animate({
'width' : '400px',
'opacity' : '1'
}, 500);
});
j++;
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
If I'm completely off track, some guidance would be good. Everything works in this format but I really don't think it's correct. I'm aware this is a relatively dumb question, but in lieu of finding a really good answer anywhere I thought it was worth asking.
I would suggest to put the different piceces of js into different files & add them with php.
But for that, first tailor the js to be independent chunks i.e one piece of js should not be accessing variables from another.
So it would look something like :
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<script type="text/javascript" src="myScript.js">
</script>
Contents of myScript.js
<!--Load data from Wordpress into the arrays so we can use them on a map later-->
locationLat[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLat', true ) ?>";
locationLong[i] = "<?php echo get_post_meta( get_the_ID(), 'locationLong', true ) ?>";
postURL[i] = "<?php echo get_permalink( $id );?>";
postExcerpt[i] = "<?php echo get_the_excerpt();?>";
postTitle[i] = "<?php echo get_the_title($ID);?>";
featImg[i] = "<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>"
i++;
I have a form where I add Input fields ( groups ) dynamically.
It is quite a complex form, and a PART can be seen here : FIDDLE
The actual error i get on the consul is :
Error: uncaught exception: query function not defined for Select2 s2id_autogen1
When I have fields already in the form ( the first two for example ) the EDIT and REMOVE button will work just fine .
My problem is that the REMOVE button ( styled input field ) is not working for the dynamically ADDED fields ( actually "appended" by JS and populated from PHP )
NOTE on code: I know the code is a mess :-(. It was inherited and will be cleaned soon.
it was copied and pasted from the HTML output.
The ADD , REMOVE and EDIT are actually styled like buttons ( too long and irrelevant to paste )
The actual source is PHP and it is spanning over multiple files ( so is the JS ) , and thus a bit too complicated to show here .
UPDATE : The code as per popular request :-)
public function show_field_repeater( $field, $meta ) {
global $post;
// Get Plugin Path
$plugin_path = $this->SelfPath;
$this->show_field_begin( $field, $meta );
$class = '';
if ($field['sortable'])
$class = " repeater-sortable";
echo "<div class='at-repeat".$class."' id='{$field['id']}'>";
$c = 0;
$meta = get_post_meta($post->ID,$field['id'],true);
if (count($meta) > 0 && is_array($meta) ){
foreach ($meta as $me){
//for labling toggles
$mmm = isset($me[$field['fields'][0]['id']])? $me[$field['fields'][0]['id']]: "";
echo '<div class="at-repater-block at-repater-block-'.$c.$field['id'].'"><h3>'.$mmm.'
<span class="at-re-remove">
<input id="remove-'.$c.$field['id'].'" class="buttom button-primary" type="submitkb" value="Remove '.$field['name'].'" accesskey="x" name="removek">
</span>';
echo '<script>
jQuery(document).ready(function() {
jQuery("#remove-'.$c.$field['id'].'").on(\'click\', function() {
var answer = confirm("Are you sure you want to delete this field ??")
if(!answer){
event.preventDefault();
}
jQuery(".at-repater-block-'.$c.$field['id'].'").remove();
});
});
</script>';
echo '<span class="at-re-toggle">
<input id="edit-'.$field['id'].'" class="buttom button-primary" type="" value="Edit '.$field['name'].'" accesskey="p" name="editk"></h3>
</span>
<span style="display: none;">
<table class="repeate-box wp-list-table widefat fixed posts" >';
if ($field['inline']){
echo '<tr class="post-1 type-post status-publish format-standard hentry category-uncategorized alternate iedit author-self" VALIGN="top">';
}
foreach ($field['fields'] as $f){
//reset var $id for repeater
$id = '';
$id = $field['id'].'['.$c.']['.$f['id'].']';
$m = isset($me[$f['id']]) ? $me[$f['id']]: '';
$m = ( $m !== '' ) ? $m : $f['std'];
if ('image' != $f['type'] && $f['type'] != 'repeater')
$m = is_array( $m) ? array_map( 'esc_attr', $m ) : esc_attr( $m);
//set new id for field in array format
$f['id'] = $id;
if (!$field['inline']){
echo '<tr>';
}
call_user_func ( array( &$this, 'show_field_' . $f['type'] ), $f, $m);
if (!$field['inline']){
echo '</tr>';
}
}
if ($field['inline']){
echo '</tr>';
}
echo '</table></span>
<span class="at-re-toggle"><img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/edit.png';
}else{
echo 'http://i.imgur.com/ka0E2.png';
}
echo '" alt="Edit" title="Edit"/></span>
<img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/remove.png';
}else{
echo 'http://i.imgur.com/g8Duj.png';
}
echo '" alt="'.__('Remove','mmb').'" title="'.__('Remove','mmb').'"></div>';
$c = $c + 1;
}
}
echo '<img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/add.png';
}else{
echo 'http://i.imgur.com/w5Tuc.png';
}
echo '" alt="'.__('Add','mmb').'" title="'.__('Add','mmb').'" ><br/><input id="add-'.$field['id'].'" class="buttom button-primary" type="submitk" value="Add '.$field['name'].'" accesskey="q" name="addk"></div>';
//create all fields once more for js function and catch with object buffer
ob_start();
echo '<div class="at-repater-block">';
echo '<table class="wp-list-table repeater-table">';
if ($field['inline']){
echo '<tr class="post-1 type-post status-publish format-standard hentry category-uncategorized alternate iedit author-self" VALIGN="top">';
}
foreach ($field['fields'] as $f){
//reset var $id for repeater
$id = '';
$id = $field['id'].'[CurrentCounter]['.$f['id'].']';
$f['id'] = $id;
if (!$field['inline']){
echo '<tr>';
}
if ($f['type'] != 'wysiwyg')
call_user_func ( array( &$this, 'show_field_' . $f['type'] ), $f, '');
else
call_user_func ( array( &$this, 'show_field_' . $f['type'] ), $f, '',true);
if (!$field['inline']){
echo '</tr>';
}
}
$js_code2 ='<span class=\"at-re-remove\"><input id="remove-'.$c.$field['id'].'" class="buttom button-primary remove-'.$c.$field['id'].'" type="submi7" value="Removevv " accesskey="7" name="remove7"></span>';
if ($field['inline']){
echo '</tr>';
}
$js_code2 = str_replace("\n","",$js_code2);
$js_code2 = str_replace("\r","",$js_code2);
$js_code2 = str_replace("'","\"",$js_code2);
echo $js_code2;
echo '</table><img src="';
if ($this->_Local_images){
echo $plugin_path.'/images/remove.png';
}else{
echo 'http://i.imgur.com/g8Duj.png';
}
echo '" alt="'.__('Remove','mmb').'" title="'.__('Remove','mmb').'" ></div>';
$counter = 'countadd_'.$field['id'];
$js_code = ob_get_clean ();
$js_code = str_replace("\n","",$js_code);
$js_code = str_replace("\r","",$js_code);
$js_code = str_replace("'","\"",$js_code);
$js_code = str_replace("CurrentCounter","' + ".$counter." + '",$js_code);
echo '<script>
jQuery(document).ready(function() {
var '.$counter.' = '.$c.';
jQuery("#add-'.$field['id'].'").on(\'click\', function() {
'.$counter.' = '.$counter.' + 1;
jQuery(this).before(\''.$js_code.'\');
// jQuery("#'.$field['id'].'").append(\''.$js_code2.'\');
// alert(\''.$js_code2.'\');
update_repeater_fields();
});
});
</script>';
echo '<script>
jQuery(document).ready(function() {
jQuery(".remove-'.$c.$field['id'].'").on(\'click\', function() {
var answer = confirm("Are you sure you want to delete this field ??")
if(!answer){
event.preventDefault();
}
jQuery(".remove-'.$c.$field['id'].'").remove();
});
});
</script>';
echo '<br/><style>
.at-inline{line-height: 1 !important;}
.at-inline .at-field{border: 0px !important;}
.at-inline .at-label{margin: 0 0 1px !important;}
.at-inline .at-text{width: 70px;}
.at-inline .at-textarea{width: 100px; height: 75px;}
.at-repater-block{background-color: #FFFFFF;border: 1px solid;margin: 2px;}
</style>';
$this->show_field_end($field, $meta);
}
OK so as you've already been told, the live is deprecated.
Here's the fiddle of the solution: http://jsfiddle.net/y8JFb/2/
Basically give each new div that you dynamically create a unique ID based on your counter, then give data attribute to your remove counter which contains that ID.
Then you have your click handler:
$( document ).on( "click", ".at-re-remove", function( e ) {
$("#"+$(e.target).data("remove")).remove();
$(e.target).remove();
} );