This is my first post so I hope I am not violating any rules. I have searched quite extensively, but possibly may have not looked for the correct terms that I am looking to resolve.
At any rate, my problem is this:
I have a table generated with a list of items, the left-most column has a button when clicked calls an ajax Post and or load function to query the history of the item and list it below the table. This works in its true sense of the expected result, however, reviewing the console through FireBug, subsequent clicks on buttons in the list result in the doubling of posts. ie. 1st click shows 1 console event, 2nd click shows 2 console events, 3rd click shows 4 console events, and so on. this continues until I select a different location and the count resets.
The below is what I see in the console. This presents a problem with timing as each subsequent post takes longer.
clicking the hist-tag button 5365
>GET http://localhost/digipens/query.php?rec_id=5365
clicking the hist-tag button 5365
>GET http://localhost/digipens/query.php?rec_id=5365
clicking the hist-tag button 5365
>GET http://localhost/digipens/query.php?rec_id=5365
clicking the hist-tag button 5365
>GET http://localhost/digipens/query.php?rec_id=5365
code:
$('.hist-tag').click(function(){
var ID=$(this).closest('tr').attr('id')
itemid = $("#itemid_input_"+ID).val();
dataString = '?rec_id='+ID;
$('#item_hist').load('query.php' + dataString);
});
Any ideas or different ways to accomplish the same goal would be excellent.
Thanks!
It sounds as if you are adding a click handler as a result of your click. Do you call $('.hist-tag').click() after the table updates? If so, you are adding new click handlers each time, which means the click is handled twice, and then 4 times, and then 8 times, etc.
I can only guess, because I don't see the relevant code here.
If so, the correct solution is to only add your click handler once, and do it via an .on() call. This way, the clicks are handled for current and future elements:
$('#mytable').on('click', '.hist-tag', function(){
var ID=$(this).closest('tr').attr('id');
itemid=$("#itemid_input_"+ID).val();
dataString = '?rec_id='+ID;
$('#item_hist').load('query.php' + dataString);
});
This attaches a handler to an element that you know will always exist #mytable, or whatever the ID of your table is, and then watches for clicks on children that propagate to the table and filters them on the selector you provide, i.e. .hist-tag.
Again, I am guessing, but that's what it seems like is happening from the evidence I have.
I suspect your click event is somehow being re-bound on each return.
Perhaps the same script is included in the response from your load call?
Try this:
$('.hist-tag').off('click');
$('.hist-tag').on('click', function(){
var ID=$(this).closest('tr').attr('id');
itemid=$("#itemid_input_"+ID).val();
dataString = '?rec_id='+ID;
$('#item_hist').load('query.php' + dataString);
return false; // prevents bubbling the click to the container
});
Related
I have a div that loads up with data and buttons depending on what some variables are in a SQL database. When we click those buttons, it changes those SQL variables because of paypal api calls or whatever (such as a "de-activate this account" button.
Right now, when I click the buttons, everything works but the page stays the same, so the "deactivate button" still says "deactivate button" instead of saying "account is deactivated" and other examples like that. When the page is refreshed they change because the SQL database has changed
Right now, I'm using the following code:
location.reload();
which effectively refreshes the page, but then you have to click a couple times to get back to the div you were working in. not a huge deal but annoying none the less.
What I'm wanting to know is if there is a way that when someone clicks the button that, for example, deactivates the account, it displays the message "Account successfully deactivated" then it freshes that DIV only, and loads up the new information based on the SQL database changes.
So far I tried this:
var url = 'index.php';
$('#div1-wrapper').load(url + ' #div1');
Which actually did what I wanted but after the reload, none of my "clicky" divs (such as a + in the top left corner) would work anymore and therefore the div wouldn't expand like its supposed to. It's like when it reloaded it didn't contain the right names on the divs but when I viewed source it was the original information so the reload either didn't happen or it doesn't update in the source.
I just need to know if there is a way to reload a div as if the page has been refreshed (so that the PHP code is re-run and the variables re-evaluated) but without refreshing the page.
Also I'd like to do it with JQuery since when you click my buttons, its running jquery $.post and in that post after it alert(data) it does the refresh.
My button calls look like this:
$("[id^=cancelbtn_]").click(function(){
var formid = this.id;
var myRegexp = /^cancelbtn_(\d+)$/;
var match = myRegexp.exec(formid);
var which_row = match[1];
var username = $("#cancelbtn_"+which_row).attr("attr1");
$.post('post.php', {'administrator':7,'username':username}, function(data) {
alert(data);
location.reload();
});
});
I have a problem with jQuery events.
First let me explain the setup of the page:
The main-page.php is consisted of:
a) a header (where the logo is)
b) a navbar (where the various selections are)
c) a dynamic content area (Where the content of the clicked element on the navbar will be loaded)
d) Footer
Lets say that the navbar is consisted of | HOME | MESSAGES | ABOUT US | ...
The content of HOME is a separate PHP file, with a separate CSS and JS file. The same goes for all selections.
As soon as I select HOME (for example), i remove any content from the DYNAMIC CONTENT area and I place the content of HOME using AJAX. At the same time I remove any CSS/JS files associated with the previous content and I link the CSS/JS files associated with the one loaded. This part is working perfectly.
Now, if I switch from one selection to other selections (lets say from HOME --> MESSAGES --> ABOUT US and then back to HOME), if I click on a button inside HOME it will fire the event multiple times. This is even worse if that event is causing an AJAX call to the server (imagine calling the server 5 times instead of 1).
**The reason I use the on() event on the element with radio-element class is because is a future DOM element. Initially this element is not on the page.
A sample of JS code:
$(document).on('click', '.radio-element', function(){
$.ajax({
url: "js/ajax/ajaxcall.php",
success: function(output){
$('#ajaxcall-container').html(output);
}
});
});
What I do is, as soon as I click an element with the class of radio-element, I go in the server and i fetch the output of ajaxcall.php script.
Watching the NETWORK tab inside INSPECT ELEMENT, I see that the click event is executing the AJAX call multiple times. Sometimes 2, other 3 or even 5.
What I did to solve the problem (non of them is working 100%):
A) unbind the event before binding it using "off"
$(document).off('click','.radio-element').on('click', '.radio-element', function(){ .... });
B) Use event.stopImmediatePropagation()
$(document).on('click', '.radio-element', function(event){
event.stopImmediatePropagation();
//rest of code
});
Below is a solution that I haven't tried yet since I read in an article that it will not stop event binding process, it will just prevent multiple event execution (don't know if this will cause other problems).
$(document).on('click', '.radio-element', function(event){
if(event.handled !== true)
{
//Code goes here
event.handled = true;
}
});
The problem with multiple event firing is that there are AJAX calls that perform actions that are not supposed to be executed more than once (eg. send email to clients).
Also, this behavior (multiple event firing) is not something i can predict. Sometimes it works fine, some others it fires the event 5 times in a row.
I have been searching the web for a week now, but everything i tried did not solve the problem. Any solution will be much appreciated :)
Thanks!
Based upon what I am reading here - I would guess you are bringing on the js file with the click bind event more than once. If you are using custom routing or single page app and not refreshing the page, it is very likely based on what you are saying.
You could test this theory by adding a console.log inside the click event (above the ajax) and fool around with it and check the logs. If you are clicking it and it is logging whatever you logged more than once, then you know that this is the issue. I don't think it is the ajax.
I have also encountered the same problem quite a while. I solved this by unbinding all the events associated with the element before executing new event handlers.
Use like this:
$('#element').unbind().click()
{
//write something here
}
This will unbind previous event handlers before creating a new one. I think this will works well for you.
If you are using jquery version 1.7+
you can use off() like this
$('#element').Off().click()
{
//write something here
}
My guess based on your description is that you are not removing the event listeners. So every time you switch tab/page the same event will be added over and over again. Even though you have tried to do it, something is not going right. I doubt it has anything to do with Ajax.
I am new to Jquery. I have a doubt:
For example, in a web page as voting, if you click a button, a counter is incremented by +1. Now, how to draw the url of the button on a website? Therefore, if we provide the url to others, and just click on the URL, the counter should increase by 1 on the website.
Best example of this is FaceBook LIKE.
I prefer to use jQuery, PHP and MySQL
It's a little bit difficult to understand what you're trying to ask but here's my take on it.
Scenario
You have a page at http://mywebsite.com/rating which contains 5 items you can rate on.
Solution
There are two events here that point to the same server side code.
What you need to do is assign an identifier to your button/product/whatever you're trying to rate. So you might have something like this <button ratingname="button1">Rate me!</button>
Now you will have a jQuery function that will use AJAX to communicate with your server and store the increment in the database. This jQuery function will be invoked via an event handler for the button and by going to this url: http://mywebsite.com/rating#button1.
Once your page loads you should check the hash for a value and if one is found then invoke the original jQuery function. You may want to additionally check if the value for the hash is a valid rating button value. (Note you could also use a query string).
I would do it using ajax, and a server side program to record votes.
You could design the page with any look-and-feel. Then add the ajax code to talk to your server-side program and maybe show the user the current votes.
?id=642&point=1
It’s a POST, not a GET, so it could only be done from a form or AJAX, not a simple URL.
//Vote update
$.post(
"http://example.com/folder/vote.php", // url
{ id: 642, point : 1 }, // post-data
function(data){ // response
$("#resultBox").addClass("done"); // show msg
}
);
More reading at http://api.jquery.com/jQuery.ajax/
I've encountered another problem with jQuery $.load(). I have two buttons, their visibility is mutually exclusive. A PHP conditional statement determines which is shown. All of that is contained in a div element #subDiv. Once either button is pressed, a PHP post file (two slightly different files for the two different buttons) is ran, and it writes a value to a database. Then, upon post success, I use $.load() to refresh #subDiv, which would (in theory) run the conditional again, and determine that the button that was not there last will now be shown.
My problem is the following:
When I click on the button when it is in State A, it will post correctly, and refresh the div to show the button in State B.
When I click on the button when it is in State B, it will post correctly, and refresh the div (according to Chrome Dev Tools), but the button remains in State B. Upon actual browser refresh, the button will appear in the correct State.
The two States and their respective post files are almost identical except for the minor necessary differences (one adds to a database table, one deletes from a database table). Seeing as the button correctly changes from State A to State B, but not the reverse, I'm not sure where the problem lies. To complicate things, a browser refresh will reveal the button in the correct state. $.load() is being used by myself to simulate a browser refresh of only one div element, for usability purposes and to cut down on loads. Therefore, I can only assume it is an error of the $.load() method.
Here's the jQuery code that controls the button click handling of both State A and State B:
//State A
$('#subButton').live('click',function() {
$.post("php/retailerNameNotif.php", $("#retailerNameNotif").serialize(), function(){
$('#retailerNameSubDiv').load('coupon.php #retailerNameSubDiv', function(){$( "button, input:submit, input:button, a#jql, input:radio" ).button();});
});
});
//State B
$('#unsubButton').live('click',function() {
$.post("php/retailerNameNotifUnsub.php", $("#retailerNameNotifUnsub").serialize(), function(){
$('#retailerNameSubDiv').load('coupon.php #retailerNameSubDiv', function(){$( "button, input:submit, input:button, a#jql, input:radio" ).button();});
});
});
Any help?
Edit:
As a further complication, I've noticed that occasionally, it will work correctly, switching states exactly as I want. However, on the 6th (and consistently the 6th) time, it goes back to the behavior I described here, getting stuck on one of the States.
My guess would be that the browser is caching the results of the load() call.
You could try inserting a random string to the filename to be sure that the request is made every time.
For example (not tested) :
var rnd = Math.random()
$('#retailerNameSubDiv').load('coupon.php?rnd=' + rnd + ' #retailerNameSubDiv', function(){$( "button, input:submit, input:button, a#jql, input:radio" ).button();});
I'm build jquery to build a custom email system (left pane list of messages - right pane the selected or current message) ....
After an Ajax call is made (for example - the message is deleted and the left pane is reloaded using .load to update the list), calls from there fails from there (its as if the reloaded content doesnt see the ajax on the page anymore... and nothing happens)
Below is an example of the jquery that deletes the mail. The deleteMail script also echos the updated list..
$('#leftmail').html(loading).load('/pages/mail/async/deleteMail.php',{'id' : id });
Does anyone have any ideas why this would happen? It is a .load things specifically?
Please help! Thanks!
F
Binding events to elements only happens once. When you load the pane via AJAX, those events are lost and not recreated on the newly fetched elements.
The jQuery live() function is designed for this. Instead of $('element').click(function() {}), you'd do $('element').live('click', function() {}) to have those click events work on content loaded after the initial domready event.