I admittedly am not very proficient with Javascript (and subsequently AJAX). I have a button that you click to vote on a page. Once clicked, the page drops and expands the section so that you can see the comments below it (so that the voter will not be swayed by the comments). This works beautifully, but unfortunately, clicking the button does not actually load the PHP controller to submit the vote to the database.
View:
<div class="vote clearfix">
<ul class="list1 clearfix">
<li class="css3">
<a href="<?=base_url()?>vote/submit_vote/<?=$post?>/1/1" class="button1 css3">
<span>Button Text</span></a>
</li>
</ul>
</div>
JavaScript:
$('ul.list1 li a').click(function() {
$('a.button1').removeClass("active");
$(this).parent().find('a.button1').addClass("active");
$("div#content div.comments").fadeIn('slow');
var col1Height = $("div#left-pannel").height() -63 ;
$('div#sidebar').css("min-height", col1Height );
return false;
});
I would like this button to submit the vote to a controller. What would be the best way to fix the button so that it links normally?
Your click handler needs two things: preventDefault(), and an AJAX method such as jQuery’s $.ajax() or $.get().
preventDefault() will prevent the default action of navigating the page to the href value. Add a parameter to the click event to represent the event, and call preventDefault() on that.
$.ajax() or $.get() will perform the action of hitting the URL to cast the vote. Personally I prefer $.ajax(), it performs a GET request by default but you can set the type to POST. There are many other options available such as dataType (json, text, xml, etc.). The success and error functions are straight-forward to implement too.
JavaScript:
I also changed how you called addClass() in your code. First, we needed to cache $(this) since “this” will no longer refer to the clicked element in the success function. Second, based on the HTML you provided, the element you need to find, ‘a.button’, is the element that was clicked. If that is the case, we can drop .parent().find(‘a.button’) and just operate on $this directly.
More on jQuery.ajax(): http://api.jquery.com/jQuery.ajax/
Feel free to ask questions about the code. I hope that helps!