$(document).ready(function() {
$(".delete_user_button").click(function(){
var username_to_delete = $(this).attr('rel');
$.ajax({
type:"POST",
url:"/delete/",
data:{'username_to_delete':username_to_delete},
beforeSend:function() {
$(this).val("Removing...");
},
success:function(html){
$("div.delete_div[rel=" + username_to_delete + "]").remove();
}
});
return false;
});
});
Why doesn't $(this).val() work?
I'm trying to change the text of the button when the user clicks remove.
In your event handler (beforeSend), this refers to the XMLHttpRequest object used for the ajax call, not your original this of the click event handler. You should "capture" it in a variable first:
$(document).ready(function() {
$(".delete_user_button").click(function(){
var element = $(this);
var username_to_delete = element.attr('rel');
$.ajax({
type:"POST",
url:"/delete/",
data:{'username_to_delete':username_to_delete},
beforeSend:function() {
element.val("Removing...");
},
success:function(html){
$("div.delete_div[rel=" + username_to_delete + "]").remove();
}
});
return false;
});
});
This mechanism is called "closures". For an interesting explanation of this, check this link:
http://www.bennadel.com/blog/1482-A-Graphical-Explanation-Of-Javascript-Closures-In-A-jQuery-Context.htm
Without more knowledge about the context or analysing the script itself: Keep in mind that, in certain environments, it might be possible that $ itself does not work and needs to be replaced with jQuery - I've seen this in Liferay.
I guess this is not your problem here, but it might come in handy for others looking for this problem from another context.
Related
My problem current is that I am trying to call a function with jquery at a specific event but it is running at the wrong event. The function I want to call is:
function resolvedAjax(tid){
$.ajax({type: 'post',url: 'resolveTicket.php',data: 'tid=' +tid, success: function(s){
$('#resolvedTicket').html("Resolved");
mainTable();
}});
}
I am trying to call it VIA this block of jquery:
$(document).on('click', '.viewTD', function(){
var tid = $(this).closest('tr').find('.tidTD input').val();
$.ajax({
type: 'post',
url: 'modalInfo.php',
data: 'tid=' +tid,
success: function(d){
$('.modal-body').html(d);
$('.modal-title').html("Ticket ID: " + tid);
$('#myModal').modal('show');
var time = $('#time').val();
var desc = $('#description').val();
$("#addComment").click(function(){
$.ajax({type: 'post', data: { myData: $('#commentAdd').serialize() }, url: "addComment.php", success: function(info){
$.ajax({
type: 'post',
url: 'modalInfo.php',
data: 'tid=' +tid,
success: function(d){
$('.modal-body').html(d);
$('.modal-title').html("Ticket ID: " + tid);
$('#myModal').modal('show');
}});
}});
});
}
});
$('#Resolved').click(resolvedAjax(tid));
});
The problem is that when I open the modal by clicking the viewTD class it runs the function which is not quite what I want. I am trying to get it so that if you click the resolved button inside the modal, which has an ID of Resolved, it will run that function. Currently it is running it as soon as it opens and doesn't wait till the resolved button is closed. Is .click() not the right trigger? I am trying to optimize this bit of code which is redundant and probably as poorly constructed as can be which is why I am working on function implementations to simplify code and make it more correct but currently this function is having problems and I don't know why.
(Additional information just in case it is needed)
The modal's body is constructed by the first ajax call in the second bit of jquery code. Inside the modal is a table with the ticket information and a form to add comments and the resolve button. I have all this redundant nested code because it was the only way I could get comments to get added and it resolved a few problems (though it has created a few). I think I can get it all working if I can get some of these functions to work but right now I am having the problem of opening the modal and resolving the tickets right away instead of allowing me to view it and add comments correctly.
I know it's probably something simple but I am still trying to learn to use jquery as I have not used it much in the past, sorry if there is any confusion I can try and clarify anything if needed.
Thanks
Edit I have this code now but it is still not working:
$(document).on('click', '.viewTD', function(){
window.tid = $(this).closest('tr').find('.tidTD input').val();
$.ajax({
type: 'post',
url: 'modalInfo.php',
data: 'tid=' +tid,
success: function(d){
$('.modal-body').html(d);
$('.modal-title').html("Ticket ID: " + tid);
$('#myModal').modal('show');
var time = $('#time').val();
var desc = $('#description').val();
}
});
});
$( document ).on( "click", "#addComment", function() {
$.ajax({type: 'post', data: { myData: $('#commentAdd').serialize() }, url: "addComment.php", success: function(info){
}});
});
$( document ).on( "click", "#Resolved", resolvedAjax(window.tid));
I can't seem to get tid accessible outside of the scope of that viewTD click event. I have tried windows, global variables and objects but can't get it working.
Your handler
$("#addComment").click(function()
is inside another handler.
$(document).on('click', '.viewTD', function(){
The second handler does not exist as far as the compiler is concerned because it is in the wrong scope. You need to move that #addComment handler into the root scope. Of course this will require you to rewrite the function - but that is why it is not responding to the clicks.
Also, .click is fine, but a better syntax is using .on because it allows you to scope your handler a little better.
$( document ).on( "click", "#addComment", function() {
console.log( "foo!");
});
Solution I found finally:
$(document).on('click', '.viewTD', function(){
var tid = $(this).closest('tr').find('.tidTD input').val();
modalConent(tid);
tabID.tableID = tid;
});
$( document ).on( "click", "#addComment", function() {
$.ajax({type: 'post', data: { myData: $('#commentAdd').serialize() }, url: "addComment.php", success: function(info){
modalConent(tabID.tableID);
}});
});
$( document ).on( "click", "#Resolved", function(){
resolvedAjax(tabID.tableID);
});
The change I made to fix it was:
$( document ).on( "click", "#Resolved", function(){
resolvedAjax(tabID.tableID);
});
instead of
$( document ).on( "click", '#Resolved', resolvedAjax(tabID.tableID));
Not sure why you can't do it the second way but whatever the reason is you have to do it the top way, if someone could comment why I'd sure love that!
#Korgrue's suggestion of getters and setters helped to make the tid variable accessible everywhere and helped make this work fully.
I have the following script I've written.
<script>
$(document).ready(function(){
$('a').data('loop',true);
$('body').on('click', 'a', function(event){
console.log($(this).data('loop'));
if ($(this).data('loop') == 'true') {
console.log('hit');
event.preventDefault();
caller = $(this);
$(this).data('loop',false);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({linkref: linkref, linkpos: linkpos, screenwidth: screenwidth});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
data: "json=" + json_data,
complete: function (jqXHR, status) {
console.log(status);
console.log(caller);
$(caller).click();
}
});
} else {
console.log(event.isDefaultPrevented());
console.log('miss');
$(this).data('loop',true);
}
});
});
</script>
It works, sends me the details I want etc etc. BUT!!!
When I click a link, It fires off the details to me via Ajax, then it's meant to "click" the event again, which it does! but the event does not fire it's normal action. So When clicking a link to another page, I would go to that other page... that's not happening.
If I comment out the line event.preventDefault(); Then the event fires as I would expect...
So to me it looks like the event.preventDefault is executing even though it's not meant to be during the second call...
Sorry if this is a bit complicated to understand. I don't quite understand what's happening myself.
Is it possibly a bug, or is there something that I've done that has caused this?
I didn't think I could, but I have successfully made a jsfiddle for this.
https://jsfiddle.net/atg5m6ym/2001/
You can try this and not worry about the "loop" anymore:
$(document).ready(function () {
$('body').on('click', 'a', function (event) {
event.preventDefault();
var caller = $(this);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({linkref: linkref, linkpos: linkpos, screenwidth: screenwidth});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
data: "json=" + json_data,
complete: function (jqXHR, status) {
console.log(status);
console.log(caller);
window.location.href = linkref; // Redirect happens here
}
});
});
});
UPDATE
There's a few issues to note here:
1) Some links don't require a redirect (as noted, bootstrap model links that control showing/hiding or within document anchors
To correct this it really depends on the case. Usually bootstrap adds specific classes or data attributes to the links so you can do something like.
$('body').on('click', 'a:not(list of things to exclude)'..
Personally I'd instead define the links I wanted to track as :
<a href=<link> data-tracked='true'...
<script>
$('body').on("click","a[data-tracked='true']"...
Or if you want to track most links with a few exceptions you can:
<a href=<link> data-tracked='false'...
<script>
$('body').on("click","a:not([data-tracked='false'])"...
Or more generally:
<script>
$('body').on("click","a", function () {
if ($(this).attr("data-tracked") == "false" || <you can check more things here>){
return true; //Click passes through
}
//Rest of the tracking code here
});
The following if statement will return true whenever the data-loop attribute exists against an element, regardless of it's value:
if ($(this).data('loop')) {
It needs to be changed to check for the value:
if ($(this).data('loop') == 'true') {
When you assign anything to be the value of an element attribute it becomes a string and, as such, requires a string comparison.
Event.preventDefault() is not being executed second time.
Link redirection happens when the method is completed.
So in your case redirection will happen when complete method of ajax call is completed.
lets say, we have event1 and event2 object in the code. event1 is the object in the ajax call method and event2 is the event object in recursive call (second call) method.
so when link is clicked second time , we still have complete method to be executed. as soon as it returns to the complete method of ajax call, it finds the event1 is having preventDefault property true and it does not redirect.
Try this ;)
$(document).ready(function(){
$('body').on('click', 'a', function(event){
event.preventDefault();
var caller = $(this);
var linkref = $(this).attr('href');
var linkpos = $(this).offset();
var screenwidth = $(window).width();
var json_data = JSON.stringify({
linkref: linkref,
linkpos: linkpos,
screenwidth: screenwidth
});
$.ajax({
url: "content/submitcontenthandler?handler=core/_dashboard&method=tracking_ping",
method: "POST",
/* To temprary block browser; */
async: false,
data: "json=" + json_data,
complete: function(jqXHR, status){
/* add class **ignore** to a element you don't want to redirect anywhere(tabs, modals, dropdowns, etc); */
if(!caller.hasClass('ignore')){
/* Redirect happens here */
window.location.href = linkref;
}
}
});
});
});
I'm using below code. This is bootstrap 3 delete conformation message.
$(document).ready(function(){
$('a.btnDelete').on('click', function (e) {
e.preventDefault();
var id = $(this).closest('div').data('id');
$('#myModal').data('id', id).modal('show');
});
$('#btnDelteYes').click(function () {
var id = $('#myModal').data('id');
var dataString = 'id='+ id ;
$('[data-id=' + id + ']').parent().remove();
$('#myModal').modal('hide');
//ajax
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(html)
{
//$(".fav-count").html(html);
$("#output").html(html);
}
});
//ajax ends
});
});
This is the trigger element that I'm using
<div data-id="MYID"><a class="btnDelete" href="#">Delete</a></div>
And I'm using the same HTML element dynamically to trigger delete and it doesn't work.
Can someone point me the correct way to do it?
You have to use event delegation
$(document).on("click" , '#btnDelteYes' ,function () {
Pretty much: bind the click higher up to something that exists when the script is run, and when that something is clicked, tell it to pass the click event to the #btnDelteYes element instead
I cant understand what exactly you are doing on your code due to missing information, but the answer is: you should use event delegation on the dynamically inserted content
you can try
$('[data-id=MYID]').on('click','.btnDelteYes',function({
e.preventDefault();
var id = $(this).closest('div').data('id');
$('#myModal').data('id', id).modal('show');
});
here <div data-id="MYID"> should be a hard coded html content and The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.
I got an problem with dynamically added DOM objects in jQuery. First of all I use this:
var $input = $('#search-input');
var $usersList = $('#ulist');
$input.on('input', function () {
$.ajax({
type: 'get',
url: '/userlist',
data: {query: $input.val()},
success: function (response) {
var json = JSON.parse(response);
$usersList.empty();
$.each(json, function (index, val) {
$usersList.append("<div id=\"listelem\">" + val + "</div>");
});
}
});
});
<div id="ulist"></div>
<input id="search-input" type="text">
to insert divs into usersList. This works well, but now I want to get val from this div when I click on it to process it further. I wrote this piece of code:
$usersList.on('click','#listelem', function(){
alert("clicked");
});
When I click on div I got proper alert, but now I have no idea how could I took data from inside of this element.
I don't know the proper engineering but I have dealt with similar issue while I was developing some requirements. basically as I understood you want to find out the target of the event and drag a value from there? if so you can do something like this:
jQuery(document).on('click', '#listelem', function(event){
var x = event.target.val();// event.target.value; depending on your situation and availability of the method.
});
Hope this helps.
try this
$(document).on('click','#listelem', function(event) {
alert($(event.target).text());
});
jsfiddle
Thanks you for help. for me proper option was to call
var mem =event.target.innerText;
you can do that with the regular javascript, you don't need Jquery.
document.addEventListener("click", function(e) {
if(e.target) {
console.log("item clicked ", e.target.textContent);
}
});
This should do the job to get the value of current target.
I have some jquery that looks like this,
$('.career_select .selectitems').click(function(){
var selectedCareer = $(this).attr('title');
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
}
});
});
My problem is that if the user keeps clicking then the .hfeed keeps getting data appended to it. How can I limit it so that it can only be clicked once?
Use the one function:
Attach a handler to an event for the elements. The handler is executed at most once per element
If you wanted the element to only be clicked once and then be re-enabled once the request finishes, you could:
A) Keep a state variable that updates if a request is currently in progress and exits at the top of the event if it is.
B) Use one, put your code inside a function, and rebind upon completion of request.
The second option would look like this:
function myClickEvent() {
var selectedCareer = $(this).attr('title');
var that = this;
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
},
complete: function() {
$(that).one('click', myClickEvent);
}
});
}
$('.career_select .selectitems').one('click', myClickEvent);
You can either use a global variable like
var added = false;
$('.career_select .selectitems').click(function(){
if(!added) {
// previous code here
added = true;
}
});
or use .one("click", function () { ... }) instead of the previous click function to execute the handler at most once per element. See http://api.jquery.com/one/ for more details.