event handler for clicking a link to ajax call - php

I'm trying to add a link to delete a row from a mysql database using jquery and ajax. The data is currently displayed in a table. For some reason, the Click event isn't triggering.
Here's my AJAX call:
<script>
$(document).ready(function() {
/* load table with page load*/
$("#sort tbody").load("inc/index_table.php");
/* row deletion */
$(".deletelink").click(function(){
var id = $(this).attr("id");
$.ajax({
beforeSend: function (request) {
var answer = confirm("Are you SURE you want to delete this?/nThis action is NOT reversible.")
if (answer){ return(true); }
else { return(false); }
},
type: "POST",
url: location.href,
data: "delete="+id,
error: function() {
console.log("Theres an error with AJAX deletion");
},
success: function(){ //a.td.tr.remove just that row rather than the whole table
$this.parent().parent().remove();
console.log("Deleted.");
}
});
});
});
</script>
And the relevant HTML:
this is part of a while loop that prints a table from my database:
<td><a class="deletelink" id="'.$row["id"].'"><img src="images/delete.png" alt="Delete"></a></td>';
My code specifies <a class="deletelink"> but it's not registering with $(".deletelink").click(function(){ });
Does anyone see what could be wrong here or have an alternate method to suggest?

Looks like you are loading the elements dynamically. You can only bind to elements which currently exist in the DOM. To bind to elements which you are about to add, you must attach the event to a static element, the closer it is to the dynamic content, the better.
Try using on() with a delegate.
$("#sort tbody").load("inc/index_table.php");
/* row deletion */
$("#sort tbody").on("click", ".deletelink", function(){
//...rest of code the same
});
on() was added in jQuery 1.7. If you are using a previous version, but higher than 1.4.2 you can use delegate() instead.
$("#sort tbody").load("inc/index_table.php");
$("#sort tbody").delegate(".deletelink", "click", function(){
//...rest of code the same
});
If #sort or tbody of $("#sort tbody") is also dynamic then $("document").on("click", "#sort tbody .deletelink", function(){...}) would work as well, though anything closer than document is better off course.
Edit
I'm just looking at your code again, the delegate binding should work, however, using load()'s success callback should work with your existing code too.
The callback is executed ones load has successfully completed. I'm not 100% certain but I'm assuming that when success is called that the elements already have been loaded into the DOM and as such the normal bindings should work.
If that doesn't work the dynamic bindings mentioned above should.
$("#sort tbody").load("inc/index_table.php", function(){
/* row deletion */
$(".deletelink").click(function(){
// .. your code as before.
});
});

to make sure the table is fully loaded, try to declare the click function, in the callback of .load() like,
$("#sort tbody").load("inc/index_table.php", function() {
/* row deletion */
$(".deletelink").click(function(){ ....
});
});

Try using .on() to bind the events to the elements
$(".deletelink").on('click',function(e){
e.preventDefault();
Also make sure to add preventDefault to stop the default functioning of the link

The problem is that your delete link appears after the table loads. So when page was loaded and DOM tree was built, it wasn't there. So you can't attach a click to it.
You can try live(). This can be used as
$(".deletelink").live('click',function(){
// ajax call handling code here
});
This function attaches event after the element has been introduced in the DOM. However, this function is a bit greedy as it keeps on scanning entire DOM tree on any DOM change. So use with caution

Related

run php file on button click ajax

Entry level user here. I've seen countless AJAX\PHP examples with data being passed via POST or GET and modified one of their examples. When clicking the button (id="clickMe) I want it to execute advertise.php and nothing more (no variables need to be passed) without refreshing the page and a notification that says success. When I click the button with my current code nothing happens.
<button type="button" id="clickMe">CLICK ME TO RUN PHP</button>
<script type="text/javascript">
$(document).ready(function(){
$('#clickMe').click(function(event){ // capture the event
event.preventDefault(); // handle the event
$.ajax({
url: 'advertise.php',
data: {
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});
});
</script>
Updated, but still isn't executing.
Here is your editted version code:
$(document).ready(function(){
$('#clickMe').click(function(){
$.post("PHP_FILE.php",{ajax: true},function(data, status){
alert(data);
});
});
});
2 things - you need a document ready handler and to prevent the default click action.
$(document).ready(function() {
$('#clickMe').click(function(event){ // capture the event
event.preventDefault(); // handle the event
$.ajax({ // remainder of code...
});
When loading jQuery scripts at the top of the page you need to make sure they do not run until the DOM has loaded, that is what the document ready handler is for. The you capture the click event by including it as an argument for your click's callback function and handle the click with the preventDefault() method.
Since this request is "simple" you may want to consider using one of the shorthand methods, like $.post()

jQuery Add Dynamic Table with Clickable Rows

I'm somewhat new to jQuery, and I see examples of how to add clickable dynamic TRs to existing tables, but how can I add an entirely new table dynamically that has clickable TRs?
My HTML code:
<input type="text" id="containing"><div id="results"></div>
My jQuery code, which POSTs the input and returns the new HTML table into the Results div:
$("#containing").on("keyup", function()
{
$.post("http://URL.com/search.php", { searcher: $(this).val() },function(data, textStatus)
{
$("#results").html(data);
});
});
Search.php returns the following format:
<table id="resultantTable"><tr><td></td></tr></table>
... and additional jQuery code that's supposed to let me click the new table rows, which doesn't work:
$(document).ready(function()
{
$("#resultantTable").on('click','tr',function()
{
var href = $(this).find("a").attr("href");
if(href)
{
window.location = href;
}
});
});
This jQuery code works for tables that load up with the document, but I cannot get the TRs to be clickable in the dynamically-created table that is returned from search.php.
Any ideas?
You need to add the listener on a parent. example:
$(document).on('click', '#resultantTable tr', function(e){
//ToDo...
});
This behaviour happens because you set the event listener on all existing table, but when you dynamically create a table it does not have this listener.
One way to fix this is to set the event listener on the newly created table on creation, but the way I do it is putting the event listener on a parent element which I know exists on document load (like body)
$('body').on({
click: function(){
...
}
}, '#resultantTable tr' )
This happens because the events was registered before the ajax content exist. (resultantTable does not exists the first time the DOM is loaded)
Try to add your function after $("#results").html(data);
it is a good practice, in your ajax call, that you listen on success/error events
Add the render and click jobs inside the success events.
See jquery documentation about that

JQuery datepicker not working after ajax call

I have the following code
<html>
<head>
//included all jquery related stuff ..not shown here
</head>
<body>
<button id = 'btn' />
<div id = 'ct'>
<?php echo file_get_contents('my_ajax_stuff.php'); ?>
</div>
</body>
<script>
$('.datepicker').datepicker({dateFormat: "dd-mm-yy"});
$('#btn').click(function() {
$.ajax({
type: "GET",
url: "my_ajax_stuff.php" ,
success: function(response) {
$('#ct').html(response);
/*added following line to solve this issue ..but not worked*/
//$( ".datepicker" ).datepicker({dateFormat: "dd-mm-yy"});
} ,
error: function () {
$('#ct').html("Some problem fetching data.Please try again");
}
});
});
</script>
</html>
The page
my_ajax_stuff.php
contains a jquery ui datepicker with class = 'datepicker'.On the first load the datepicker works.But when I click on the button to reload it again , the contents are replaced with new contents.But the datepicker is not working.I have tried initialising the datepicker inside the ajax success handler ,as you see.But it also failed.What is the issue.How can it be solved???
You need to reinitialize the date picker in Ajax success
$('.datepicker').datepicker({dateFormat: "dd-mm-yy"});
$('#btn').click(function() {
$.ajax({
type: "GET",
url: "my_ajax_stuff.php" ,
success: function(response) {
$('#ct').html(response);
$( "#datepicker" ).datepicker();
/*added following line to solve this issue ..but not worked*/
//$( ".datepicker" ).datepicker({dateFormat: "dd-mm-yy"});
} ,
error: function () {
$('#ct').html("Some problem fetching data.Please try again");
}
});
});
The answer you are looking for may be similar to this question:
jQuery datepicker won't work on a AJAX added html element
You're replacing the datepicker element in the DOM with the ajax response.
The reason this works for the first time is that PHP renders the my_ajax_stuff.php on first load already in the HTML so it becomes available to jQuery in the DOM.
// do this once the DOM's available...
$(function(){
// this line will add an event handler to the selected inputs, both
// current and future, whenever they are clicked...
// this is delegation at work, and you can use any containing element
// you like - I just used the "body" tag for convenience...
$("body").on("click", ".datepicker", function(){
$(this).datepicker();
$(this).datepicker("show");
});
});
I came across this question because I was having the same problem as OP.
Mooed Farooqui's recommendation to reinitialize in Ajax success worked, but not initially.
Ended up that I was also calling the datepicker function in my equivalent of my_ajax_stuff.php. After I took that out it worked perfectly on button reload and postbacks. Hope this helps someone that stumbles upon this old question...
Call your picker inside .ajaxComplete function.
$(document).ready(function () {
// setup picker here...
});
$(document).ajaxComplete(function() {
// setup picker here...
});
Here is a link
This may be a primitive solution, but I found that If I have in my main document a function MakeDatePicker and I used it in the OnChange portion of my input, I was able to make any object, ajax, or otherwise, turn into a date picker before, and after an ajax call.
Here is the function and the call. (please note, I have ColdFusion # functions, as this is a return on a coldfusion query with a CFOutput.)
<td><input type="date" class="EstDeliveryDatePicker" chassis="#chassis#" value= "#DateFormat(EstDelivery,'mm/dd/yy')#" onclick="MakeDatePicker(this);"></input></td>
here is the function at the top of my page:
function MakeDatePicker(obj)
{
$(obj).datepicker({
changeMonth: true,
changeYear: true
});
$(obj).datepicker("show");
}
like I said, its crude, but it works.
I was having an issue with the way my tables would display their sorts. I have it so when you enter the page, you have 1 field that you can click on to select a date. If you click on one of the headers, it would sort SQL command, and re-display the table. This would break the .datepicker function. So I change it to not read off the class, but make the click, trigger the function. the problem with trying to get it to run on the .class was it would initialize after the table was redrawn and lose the scope of the DOM.

Jquery/Ajax running before dynamic php content loaded

I've got a dynamic page which I'm loading from an external PHP file when the booking link is clicked.
My issue is the jQuery code I need to run straight after it sometimes tries to execute before the PHP page is fully loaded (the follow and remove parts specifically). So when I try load the div, jQuery works sometimes, and other times not.
From what I've seen on other examples $(document).ready(function() is supposed to prevent the jQuery executing until the page is fully loaded, however since I'm loading a specific div (content) and not the entire page it seems to not work?
$(document).ready(function(){
$(document).on('click', '.booking', function (){
$('#content').load('calendar.php');
$.getJSON(url,data, function(data) {
$.each(data, function(index, data) {
$("#blocksid"+data.slot_id).css("background-color","#009cd0");
$("#follow"+data.slot_id).hide();
$("#remove"+data.slot_id).show();
});
});
return false;
});
});
Thanks in advance for any assistance!
To achieve what you are expecting in a predicable way you should run dependent javascript code
after loading content to div. Just create a call-back function for load method and have your dependent code inside it.
$('#content').load("calendar.php", function() {
//put the code here, that you need to run after loading content to above div
});
You need to set:
$.ajaxSetup({ async: false });
and then turn it back on by:
$.ajaxSetup({ async: true });
or use
$.ajax({
async:false
});

Using jQuery 'click' function that was loaded with Ajax content?

I have the contents of a php file loaded via Ajax that contains HTML and JavaScript. I have a button:
<button class="search_button">Search</button>
And I have a script underneath that will update the documents hash from a jQuery function
<script type="text/javascript">
$(".search_button").click(function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
</script>
This code works when I run the php file separately, but when loading this page from an Ajax call, the function no longer runs. In firebug the script is not present so I am assuming I cannot load a script in using this method. I tried also putting the JavaScript snippet instead a header for the whole website, but this failed also.
I was also thinking perhaps the function has to be declared when there is a search_button class already present, but it was structured in this way when I previously had them in one file (that was retrieved via Ajax) to no avail so I'm confused as to the problem.
You can include it globally with a live event:
$(".search_button").live('click', function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
jQuery will automatically evaluate script blocks, you cannot see the function in the HTML because it has been stripped out. However it should have already run. The problem is most likely timing. You could do something like
setTimeout(function(){
$(".search_button").click(function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
}, 500);
So that when the script is loaded it waits to be executed (hopefully giving jquery time to update the DOM with the new element).
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
This method provides a means to attach delegated event handlers to the document element of a page, which simplifies the use of event handlers when content is dynamically added to a page. See the discussion of direct versus delegated events in the .on() method for more information.
Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Example usage of .on() to bind click event
$(document).on("click", "#post a", function(){
alert("1");
})
Try to add the script inside a function
function name(){
$(".search_button").click(function() {
var searchTerm = $('#search_box').val();
document.location.hash="searchTerm";
return false;
});
}
and call this function just after the end of the ajax call.
$(document).ready(function() {
name();
});

Categories