Trying to find out why this jQuery JS isn’t making ajax call though it is being called for execution.
I have this button to make an ajax GET request to a method in the controller, the method will partial render. When I click on the button I don’t see any request coming on the console but I see the alert “test” on the browser.
I have the same exact JS with other parameters working for other tupes of ajax calls, so I just copied one of them and changed all required parameters, expecting it shall work right away. Neither I get any errors on the console. My routes and id names are good and verified. What is it that I am missing here?
view – Note: this button is rendered via a different ajax, that part works.
<%= button_tag "Add / Remove", :id => "add_remove_button", :onclick => "javascript:add_remove();" %> #note: this is buried under div tags in a html table
JS-
function add_remove(){
$('#add_remove_button').click(function() {
$.ajax({
type: 'GET',
url: "/item/add_remove",
success:$('#view_item').html(data)
/*function(){ },
data:$('#test').serialize(),
error: function(){ },
success: function(data){ },
complete: function (){ }*/
}); #No ajax call made
/*return false;*/
});
alert('test'); #I get this alert
}
You’ll always see that
alert()becauseclick()is asynchronous: the code inside thefunction()passed to click does not get executed until you click, but the rest ofadd_remove()will get called.Here’s what is actually happening in your code, which explains why the AJAX call doesn’t get made:
:onclick => ...attachesadd_remove()to your button.add_remove()gets called and attaches another click callback to your button. Thenadd_remove()callsalert(). There is no AJAX call happening here, just adding a new click handler, and sending an alert.Here’s what you actually want to do. Remove the :onclick => … from the button:
Attach a click event to the button when the page first loads: