Jquery, ajax and php
I have this code to present images:
<?php foreach ($images as $row) : ?>
<div class="box col_3">
<p><a href="<?php echo base_url() ?>public/images/fullscreen/<?php echo $row['image'] ?>" rel="prettyPhoto[gallery1]" title="<?php echo $row['title'] ?>">
<img src="<?php echo base_url() ?>public/images/thumbnails/<?php echo $row['image_thumb'] ?>" title="<?php echo $row['title'] ?>" ></a></p>
<textarea name="title_image" rows="3" class="title_image"><?php echo $row['title'] ?></textarea>
<input type="hidden" class="id_image" class="id_image" value="<?php echo $row['id_image'] ?>" >
<input type="submit" name="update_image" id="update_image" value="Update" class="submit" /><br>
<a href="#" class="delete" id="<?php echo $row['id_image'] ?>">Delete image</a>
</div>
<?php endforeach; ?>
User can upload an image, and for every image div with class of box is created. This is the code which sends data for update.
$(function(){
$('.submit').click(function(){
('.box').开发者_开发技巧append('<img src="<?php echo IMG ?>loadinfo.net.gif" id="loading" />');
var id = $('.id_image').val();
var title = $('.title_image').val();
$.ajax({
url: "<?php echo site_url('gallery/update_image') ?>",
type: 'POST',
data: 'id=' + id + '&title=' + title,
success: function(){
$('#loading').fadeOut(500, function(){
$(this).remove();
});
}
});
return false;
});
});
This works just for the first box, and for the rest it doesn't. What I need to do to make it work?
you are referencing css classes within your javascript
$('.id_image').val()
this will always return the value of the first appearance of this class e.g. the first image. try to traverse through the DOM using your submit button as start e.g.
$('.submit').click(function(){
var id = $(this).prevAll('.id_image').val();
this should return the correct value for id. then you can use the same method to get the title
to update the loading image use the same method, but this time you'll have to use the parents() selector
$(this).parents('.box').append('<img src="<?php echo IMG ?>loadinfo.net.gif" id="loading" />');
as you are now assigning only a single loading image the removal function should work as expected
精彩评论