This question already has an answer here:
Jquery button click event not firing
(1 answer)
Closed 8 years ago.
I have an auto refreshing HTML table with some buttons in it.
I current use the folowing Code to Refresh the Table every 5 seconds and set the ajax ClickListener. My problem is that the event ONLY fire before the first refresh fired.
<?php require_once ('UserTableHtml.php'); ?>
<script type='text/javascript'>
var table = $("#t02");
// refresh every 5 seconds
var refresher = setInterval(function()
{
table.load("UserTableHtml.php");
}, 5000);
table.ready(function()
{
$('.btnUser').click(function()
{
var clickBtnValue = $(this).val();
var ajaxurl = 'home.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response)
{
// Response goes here.
alert("action performed successfully");
});
});
});
</script>
The complete code of the output table is generated by the 'UserTableHtml.php'
Thanks for your answers an MERRY CHRISTMAS
If the problem is with the click of the button, you should use
$('.btnUser').on('click',function(){...});
Insted of
$('.btnUser').click(function(){...});
For dynamic elements, attach events using the .on() annotation.
Looks like it only loads after 5 seconds... add the line below to have it load after the table has finished rendering.
<script type='text/javascript'>
var table = $("#t02");
// refresh every 5 seconds
var refresher = setInterval(function()
{
table.load("UserTableHtml.php");
}, 5000);
table.ready(function()
{
$('.btnUser').click(function()
{
var clickBtnValue = $(this).val();
var ajaxurl = 'home.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response)
{
// Response goes here.
alert("action performed successfully");
});
});
//add this here...
table.load("UserTableHtml.php");
});
</script>
Guys i just figured it out.
Now it works as excepted.
var table = $("#t02");
table.ready(function()
{
$(document).on('click', '.btnUser',function()
{
var clickBtnValue = $(this).val();
var ajaxurl = 'home.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response)
{
// Response div goes here.
alert("action performed successfully");
});
});
});
<button type="submit" class="btnUser" name="userEdit" value="user_edit_'.$user->getId().'"><img src="images/edit-4.png" />
Related
Is there any way to stay on a scroll position when an ajax is in refresh interval every 3 seconds? Here is the code that is in another webpage called "sample.php":
<script type="text/javascript" src = "includes/jquery.js"></script>
<script>
var inProcess = false;
setInterval( function () {
if (inProcess) {
return false;
}
inProcess = true;
jQuery.ajax({
url: 'data.php',
data: '',
method: 'POST',
success: function(answer) {
jQuery('#Load').html(answer);
inProcess = false;
},
error: function() {
inProcess = false;
}
});
}, 3000 );
</script>
<div id = "Load"> </div>
Inside data.php, I just run a query to echo out table rows. The ajax in sample.php, basically sends a request to data.php every 3 seconds to "repeat" the query so when a new value enters the database, it will automatically echo out after 3 seconds. It works but I would like the scroll position to stay where it is every time the ajax reloads.
I'm using AJAX to submit the form without reloading. I'm using it for my register form. After I catch my error/success message I append it to my div and remove it after 5 seconds using timeout function.
Now if the user clicks on the button and gets error, and then again clicks the button (before 5 seconds pass) the second error message div will appear with the same error but it will be removed at the same time the first one is removed. So what I'm trying to achieve is to set my error/success messages to have individual timeouts. So first error appears, then after 2 seconds I press the button again and get second error, now the first error will be removed after 5 seconds, and the second will stay untill its 5 seconds pass.
So I have a div in my HTML code with the id "msg-response", where my error/success messages appear.
And here is how I call them:
$("#registerform").submit(function(event) {
var ajaxRequest;
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
ajaxRequest = $.ajax({
url: "include/auth/register.php",
type: "post",
data: values
});
ajaxRequest.done(function (response){
if ($.trim(response) == 'error') {
$("#msg-response").prepend("<div class='error-msg'>Email format isn't valid. Try again.</div>").hide().fadeIn("slow");
setTimeout(function() {
$('.error-msg').fadeOutAndRemove('slow');
}, 5000);
}
});
ajaxRequest.fail(function (){
alert("error");
});
});
So how can I add individual timeouts to each div appeared? And not one timeout for all divs with class .error-msg.
Thanks in advance.
You can store your .error-msg inside a var and then remove it by var reference:
var error = $("<div class='error-msg'>Email format isn't valid. Try again.</div>");
error.fadeOutAndRemove('slow');
Final code:
if ($.trim(response) == 'error') {
var error = $("<div class='error-msg'>Email format isn't valid. Try again.</div>");
$("#msg-response").prepend(error).hide().fadeIn("slow");
setTimeout(function() {
error.fadeOutAndRemove('slow');
}, 5000);
}
Intresting, I got it working by making my error-msg div to be an ID instead of CLASS, so like this:
$("#registerform").submit(function(event) {
var ajaxRequest;
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
ajaxRequest = $.ajax({
url: "include/auth/register.php",
type: "post",
data: values
});
ajaxRequest.done(function (response){
if ($.trim(response) == 'error') {
$("#msg-response").prepend("<div id='error-msg'>Email format isn't valid. Try again.</div>").hide().fadeIn("slow"); // Changed line
setTimeout(function() {
$('#error-msg').fadeOutAndRemove('slow'); // Changed line
}, 5000);
}
});
ajaxRequest.fail(function (){
alert("error");
});
});
I'm confused a little, so can atleast someone write me explanation why its good now that I'm using ID and not while using classes? And is this the right approach?
Jtable pagination is not working if I am pressing back button.
I have some 4 option in menu. First option is home and last is report. When I am clicking on report, getting a list which I am displaying by using jtable. After clicking page 1,2,3,4,10,20 new page come. But after pressing back button previous should display. For that I modified some code of jtable api.
/* Performs an AJAX call to reload data of the table.
*************************************************************************/
_reloadTable: function (completeCallback) {
var self = this;
//Disable table since it's busy
self._showBusy(self.options.messages.loadingMessage, self.options.loadingAnimationDelay);
//Generate URL (with query string parameters) to load records
var loadUrl = self._createRecordLoadUrl();
//Load data from server
self._onLoadingRecords();
self._ajax({
type:'GET',
url: loadUrl,
cache : false,
data: self._lastPostData,
success: function (data) {
var historyData = self._lastPostData;
historyData.url=loadUrl;
history.pushState(stringifyObject(self),'List',window.location.href);
location.hash = loadUrl;
self._hideBusy();
//Show the error message if server returns error
if (data.Result != 'OK') {
self._showError(data.Message);
return;
}
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(data.Records);
self._onRecordsLoaded(data);
//Call complete callback
if (completeCallback) {
completeCallback();
}
},
error: function () {
self._hideBusy();
self._showError(self.options.messages.serverCommunicationError);
}
});
},
And added one more method
window.onhashchange = function() {
//console.log(JSON.stringify(eval("(" + history.state + ")"));
if(history.state!=null){
var self = JSON.parse(history.state);
alert(self._createRecordLoadUrl());
alert(self.state._lastPostData);
self._reloadTable(completeCallback);
}
}
I am not able to call these method because self is not jtable object.
Please provide better solution.
I have got a form with two tabs, on both tabs you can edit data and submit your changes which is working already.
Now I want the tab where you made changes to get reloaded after you changed something (e.g. a picture URL and the thumbnail should get refreshed) to see the changes.
I have this code for the second tab
<script>
$(document).ready(function(){
$('.btn').click(function(){
var clickBtnValue = $(this).val();
if(clickBtnValue == 'Save') {
var ajaxurl = 'ajax.php',
data = $('form').serialize();
$.post(ajaxurl, data, function (response) {
if(response == '')
{
alert("Successfully saved");
location.href="catalog.php";
}
else alert(response);
});
}
else if(clickBtnValue == 'Save & Continue Edit')
{
var ajaxurl = 'ajax.php',
data = $('form').serialize();
$.post(ajaxurl, data, function (response) {
if(response == '') alert("Successfully saved");
else alert(response);
});
}
else if(clickBtnValue == 'Add new Item')
{
var ajaxurl = 'ajax.php',
data = $('#itemform').serialize();
$.post(ajaxurl, data, function (response) {
if(response == '')
{
alert("Successfully added new Item");
location.href="catalog.php";
}
else alert(response);
});
}
else if(clickBtnValue == 'Save Images')
{
var ajaxurl = 'saveimages.php',
data = $('#imageform').serialize();
$.post(ajaxurl, data, function (response) {
if(response == '')
{
alert("Successfully saved");
$("#tab_images").load(location.href+" #tab_images>*","");
}
else alert(response);
});
}
});
});
Everything is working until now, the data get saved and the DIV reloads, but now whenever I try to press a button nothing happens, even on the first tab.
What am I doing wrong?
EDIT:
My Tab Code: http://i.epvpimg.com/9SaKb.png
Can't post it here since it is too long so I had to make a screenshot.
It looks like the buttons you try to click are inside the div what you are reloading. When the content of that div is replaces, all the elements you fetched with ajax are considered as new - that also means that the click handlers you had previously on those buttons are also lost - hence they don't react the same way :D
try binding the event not on the button itself but an element outside the div that is being replaced
$("parent_selector_outside_ajax_div").on("click", ".btn", function() {
//your button function
});
read move about event delegation with jQuery at http://api.jquery.com/on/
As your external js library binds it's own buttons I suggest moving those buttons outside the div you are trying to update (which shouln't be a big problem as you are trying to update only for the sake of them image previews? :D).
The other alternative (which I wouln't do) would be to rebind those buttons again after the ajax has reloaded by calling whatever function the library offers to initialize itself. If your application is long lived, you also should, before replacing the old content with a new one, remove all the event handlers from the current content, to avoid possible memory leaks in some browsers (not sure what is your target audience).
I'm auto-refreshing the content on a site using ajax/json. Using jkey, I trigger some posting to the document, and during this action I want to cancel the original setTimeout that's running ("reloading" at 2 mins) - and then trigger the entire function "content" again to start over after 5 secs. However, I can't seem to stop "reloading" properly, neither call "content" after the given seconds. Can anybody spot the error?
<script>
$(function content(){
function reloading(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var timestamp = data[3];
var field1 = data[4];
_field1 = field1;
var val2 = parseInt(field1, 10) ;
_val2 = val2;
$('#output').hide().html( message ).fadeIn("slow");
$('#username').hide().html( vname +":" ).fadeIn("slow");
setTimeout(reloading,120000);
}
});
}
reloading();
});
$(document).jkey('a',function() {
$.post("update.php", { "id": _id} )
$('#output').hide().html( "<i>thx" ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
clearTimeout(reloading);
setTimeout(content,5000);
});
</script>
The clearTimeout should get the unique "key" that is returned by setTimeout. So when setting, assign the return value to global variable:
window["reload_timer"] = setTimeout(reloading,120000);
Then have this:
clearTimeout(window["reload_timer"]);
You must save the setTimeout() id in order to later clear it with clearTimeout(). Like this:
var timeoutID = setTimeout(function(){someFunction()}, 5000);//this will set time out
//do stuff here ...
clearTimeout(timeoutID);//this will clear the timeout - you must pass the timeoutID
Besides saving the timeout id as mentioned in other posts, your function reloading is created inside function content and since you create no closure to it, it's unreachable from the rest of the program.
$(function content(){
function reloading(){
console.log('RELOADING');
}
reloading();
});
// Can't reach `content` or `reloading` from here
You have to do something like this:
var reloading, content, reloadingTimeoutId, contentTimeoutId;
reloading = function () {
console.log('RELOADING');
$.ajax(
// CODE
success : function (data) {
// CODE
reloadingTimeoutId = setTimeout(reloading, 120000);
}
)
};
content = function () {
reloading();
};
$(document).jkey('a',function() {
// CODE
clearTimeout(contentTimeoutId);
contentTimeoutId = setTimeout(content,5000);
});
It's kinda difficult writing this better not knowing the bigger picture. With this, content will be called after 5 seconds and as long as reloading succeeds it will callback itself every 120 seconds. Please observe that reloading is never cleared this way.