Quick JQuery help

Associate
Joined
11 Mar 2007
Posts
1,741
Hey all,

Was hoping someone could give me a little hand with this ajax jQuery script. Basically, the php foreach loop will output a list of items, each with a unique it, and when the submit button next to the item is pressed it should grab the item ID, show a laoding gif and ajxify the php script. Half the time the ajax doesn't work though and when it does it shows the loading gif next to all the items. I think it is just to do with how I'm selecting the correct div, the ajax part works fine when it does. Basically I don't think I'm pulling the unique ID correctly but not really sure where I've gone wrong!

All help appreciated!!


Code:
<?php if(isset($records)) : foreach($records as $row) : ?>
	<div class="book id_<?php echo $row->booksId; ?>">
		<div class=""><a href="books/<?php echo $row->booksSlug; ?>"><?php echo $row->booksTitle; ?></a>
	
	<div class="finished">
			<?php echo form_open('members/index/remove_reading');?>
				<input type="submit" id="update_reading" value="Finished!" /><span class="ajax_loader"></span>
				<input type="hidden" id="id" name="id" value="<?php echo $row->booksId; ?>">
			<?php echo form_close(); ?>
		</div>
</div><!-- div.book -->
	<?php endforeach; ?>
	<?php endif ;?>
	
	<!-- Ajax UPDATE READING -->
	<script type="text/javascript">
	$('#update_reading').click(function(){
		var book_id = $('#id').val();
		$('.id_' + test + ' span.ajax_loader').empty().html('<img src="site_images/ajax-loader.gif" class="ajax_loader" alt="Loading Icon" />');
		var form_data = {
			id: book_id,
			ajax: '1'
		};
		$.ajax({
			url: "<?php echo site_url('members/index/remove_reading'); ?>",
			type: 'POST',
			data: form_data,
			success: function(msg) {
				$('.id_' + test).html(msg);
			}
		});
		return false;
	});
	</script>
 
Your IDs need to be unique you will have multiple DOM elements with the ID update_reading and id, jQuery won't like that. Also returning false to prevent default action should be done by passing in the event with the click function and then called like e.preventDefault();

Also if you submitting form information via ajax there is a plugin out there that can help http://jquery.malsup.com/form/

Daz
 
Last edited:
Back
Top Bottom