Ruby rails - jQuery JS being executed but not making ajax call - ruby

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() because click() is asynchronous: the code inside the function() passed to click does not get executed until you click, but the rest of add_remove() will get called.
Here's what is actually happening in your code, which explains why the AJAX call doesn't get made:
Using :onclick => ... attaches add_remove() to your button.
You click the button, add_remove() gets called and attaches another click callback to your button. Then add_remove() calls alert(). There is no AJAX call happening here, just adding a new click handler, and sending an alert.
You click the button a second time, and you will attach a third click callback to the button. However since you also attached a click handler the first time you clicked the button, you should see an AJAX request here.
Click it a third time and you'll see two AJAX requests this time, for a total of 3 AJAX requests.
Here's what you actually want to do. Remove the :onclick => ... from the button:
<%= button_tag "Add / Remove", :id => "add_remove_button" %>
Attach a click event to the button when the page first loads:
$(function(){
$('#add_remove_button').click(function() {
$.ajax({
type: 'GET',
url: "/item/add_remove",
success: function(data) { $('#view_item').html(data); },
data: $('#test').serialize(),
error: function(){ },
success: function(data){ },
complete: function (){ }
});
return false;
});
});

You are mixing up the jquery-registering-callbacks style and the old event-handler attributes. So you triggered the registering when calling the add_remove function.
Simply remove the :onclick stuff and function add_remove(){ ... }

Related

why browser request for image after ajax?

I'm using backbone and nodejs for a single page webapp.
I got a view, which has a model(a blog post) in it. when user click on 'like' button, the view will start ajax send the user'id to server to let the like number +1.
it looks like this:
this.model.save({
likedBy: userModel.get('_id')
}, {
url: '/posts/' + this.model.get('_id') + '/like',
success: function() {
// do something
},
patch: true
});
my problem is, when this code got run. browser start http request to retrieve all the images on the screen, and re-render them. so the screen got a "shake" after user clicked the like button.
this is not happening everywhere, but what caused this? how to stop the "shake"?
thanks for any advance.
When you call this.model.save() the model will update his data in the server and will call your view's render function. The render method will create a new DOM element and replace the old DOM element, that's what causing the flickering (it requests the images again).
I assume you have an API call for Like action (if not it's better to have one) so you can make a sperate AJAX call for like action on your model by adding a function like so:
addLike : function(data) {
Backbone.ajax({
url: '/api/like/'+ this.get('id'),
method: 'POST',
data: data,
success: options.success,
error: options.error
});
}

Jquery Mobile submit button not working after page refresh

I have a single page mark-up with popup divs that contain forms that the user can use to update his/her account information. After form submission the popup closes and the page refreshes showing the updated information that is located within a li (this seems to be working). The problem is, if the user goes back and tries to update again the button within the popup is not submitting.
Thanks in advance for any suggestions!!!
Javascript
$('#updateadmin').click(function() {
var admin = $('#adminform').serializeArray();
/*alert(admin);*/
$.ajax({
type: "POST",
url: 'adminupdate.php',
data: admin,
success: function(data) {
if(data=="success") {
$('#admindiv').popup('close');
$.mobile.changePage('companyinfo.php', {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true,
changeHash: false
});
} else {
$('#adminupdatestatus').html(data).css({color: "red"}).fadeIn(1000);
}
}
});
return false;
});
It sounds like the #updateadmin link/button is located on the page that gets reloaded, if this is the case then you should delegate your event handler so it affects matching elements in the DOM for all time, not just when the code runs.
You would change this:
$('#updateadmin').click(function() {
to this:
$(document).on("click", "#updateadmin", function() {
This works because you're now attaching the event handler to the document element which always exists. When events reach the document element they are checked to see if the element on which they originally fired matches the selector we put as the second argument for .on().
Documentation for .on(): http://api.jquery.com/on

reload page when clicking on current page link, using jQuery Address plugin

I am using jQuery Address plugin, and all my ajax navigation is based on it, and more precisely on internalChange or externalChange events like that
$(document).ready(function() {
initDeepLinking();
});
function linkClicked(e){
var request = $.ajax({
url: e.path,
data: e.queryString,
type: "GET",
dataType: "json",
});
request.done(handleResponse);
return false;
}
function handleResponse(response, textStatus, jqXHR){
$('#main').html(response.responseText);
};
function initDeepLinking(){
$.address.internalChange(function(event){
linkClicked(event);
});
$.address.externalChange(function(event){
linkClicked(event);
});
}
so when i click on a link leading to the current page, nothing happens.
I would like the page to reload when I do that. Any simple options ?
Thanks !
I am having troubles understanding what your question really is:
you don't know how to attach a handler to the link
you don't know what statement can be used to refresh the current page
In order to set a handler you can use some selector. For example, getting the element by class. More about jquery selectors here.
After you have the element, you can attach an event handler for the 'on click' event and do something like this:
window.location.reload(true);

Jquery load in Dialog is repeated exponentially

I have a really annoying issue with jQuery and/or the jQuery UI Dialog Box.
After clicking on a special link a modal dialog will pop up with some loaded content (ajax) and inside this loaded content are new links/buttons that load their url inside the same div Box, so the dialog still is loaded, but with new content then. The Problem is, that if you link on that link (inside a fresh loaded dialog box and on a recently reloaded website) it works as it should, but with the second click it loads the url twice, with the third it loads 4 times ... It growing exponentially with every new link loaded inside the dialog. I testet this with a counter stored inside $_SESSION.
This is the Javascript Code:
var somedialog = $('<div></div>').dialog({
autoOpen: false,
resizable: false,
modal: true,
/*show: 'fade',
hide: 'puff',*/
closeOnEscape: true,
close: function(){
}
});
function openInDialog(url, title, width, height)
{
somedialog.empty();
somedialog.dialog("option", "width", width);
somedialog.dialog("option", "height", height);
somedialog.dialog("option", "title", title);
somedialog.load(url,{},function (responseText, textStatus, XMLHttpRequest)
{
somedialog.dialog('open');
}
);
//somedialog.load(url,{},function (responseText, textStatus, XMLHttpRequest){
// dialogdiv.somedialog('open');
//});
}
$('a.ajaxBuyItemDialog').on('click',function(){
openInDialog(this.href, this.title, 400, 300);
//prevent the browser to follow the link
return false;
});
There seemed to bee other people with this issue, but that was not a very effective discussion: https://stackoverflow.com/questions/6471360/jquery-load-after-load-repeated-results-problem
Thanks for your help!
EDIT:
This is part of the code which is located in the loaded script:
$("#_BUYITEM_FORM").live('submit', function(){
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response){ // on success..
$("#_BUYITEM_CONTENT").html('<p class="AjaxLoaderImg"><span>Einen Moment bitte...</span></p>');
$("#_BUYITEM_CONTENT").html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
Without it I can't get it to refresh the dialog box with new content.
It seems that your javascript code is replicated in every $('a.ajaxBuyItemDialog') destination page clicked. Adding that script to the dialog again at every click causes event to be triggered more than once.
If you reload the script numerous times it will add a new submit handler to form each time since you are using live().
live() will delegate the handler to the document and thus should either only be called once or you need to call die() before script loads each time.
if you were to get rid of using live() you could move the submit handler to the success callback of load() and use submit() rather than live(). If the original form is replaced...the original submit() event handler will also be gone
"Dirty" solution
function watchBuyItemForm(){
$("#_BUYITEM_FORM").submit(function(){
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response){ // on success..
somedialog.html(ajaxLoader);
somedialog.html(response); // update the DIV
watchBuyItemForm();
}
});
return false; // cancel original event to prevent form submitting
});
}

jQuery Submit Function Does Not Work (Inner Function)

I have a problem with this jQuery code. It doesn't work as expected:
$('#select_dropdown').change ( function(){
$('#form_to_submit').submit( function(event){
$.post("list.php", { name: "John", time: "2pm" },
function(data) {
alert("Data Loaded: " + data);
});
});
});
However, this works:
$('#select_dropdown').change ( function(){
$('#form_to_submit').submit();
});
I wonder why the internal function on submit doesn't work. When a user selects a value from a dropdown, the form must be submitted. The second set of codes work but if I add an inner function to submit, it doesn't.
Basically, I want to do some ajax call after the user select on the dropdown.
According to documentation ( http://api.jquery.com/submit/ ), submit() without parameters will submit your form, but if you include arguments it will bind the submit event to the form, but it wont submit it.
So, the code posted by #Chris Fulstow would be the right way of submitting the form, but as ajax is not synchronous, function will continue without waiting for the answer and then, the alert will not be shown.
You can make it synchronous, but you must use $.ajax instead of $.post, because $.post doesn't include an async option. Anyway, I'm providing a solution for your specific problem, but I'm guess there should be a better way for doing it.
$(function() {
$('#select_dropdown').change(function() {
$('#form_to_submit').submit();
});
$('#form_to_submit').submit(function(event) {
$.ajax(
url: "list.php",
data: { name: "John", time: "2pm" },
success: function(){
alert("Data Loaded: " + data);
},
async:false,
);
});
});
When you call with a callback argument submit( handler(eventObject) ) it will only attach an event handler. To trigger a form submit, call submit() with no arguments:
$(function() {
$('#select_dropdown').change(function() {
$('#form_to_submit').submit();
});
$('#form_to_submit').submit(function(event) {
$.post(
"list.php",
{ name: "John", time: "2pm" },
function(data) {
alert("Data Loaded: " + data);
}
);
});
});
The .submit call in your first example is binding a function to the submit event on the form. From the fine manual:
.submit( handler(eventObject) )
handler(eventObject) A function to execute each time the event is triggered.
You need to bind your submit handler:
$('#form_to_submit').submit(function(event){ /*...*/ })
somewhere else and call submit as in your second example.
So the problem here is that in the first case, you are binding an event handler to the element, and in the second you are triggering it. Let's look at the first case:
$('#form_to_submit').submit(function(evt){ ... });
You're essentially doing something like
document.getElementById('form_to_submit').addEventListener(
'submit',
function(evt){...},
false
);
The second case is you instructing the form to submit, which is why it works. If you wanted the handler to work with your custom code you would need both of them. First bind your event handler, then, onchange instruct the form to submit.
$('#form_to_submit').submit(function(evt){ ... });
$('#select_dropdown').change(function(){
$('#form_to_submit').submit();
});
Keep in mind though, that as other people have already said, if your action is set to go to another location, you may not see the results of the binded event handler so instead of explicitly stating a url for your action, you will have to use something to prevent the form from going anywhere like action="javascript:void(0)" or the like.
To make your code a bit cleaner, you could pull the ajax out of an unnamed function and put it in a named one and call it on change so it looks like this.
var fetchList = function(){
$.ajax(...);
};
$('#form_to_submit').submit(fetchList);
$('#select_dropdown').change(fetchList);
I haven't run this code, please excuse any silly syntax mistakes I've made. But this should get you some of the way there. Good luck! :)

Resources