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.
Related
So, I have a jQuery AJAX call that gets data from the server (some text, some links).
Inside AJAX success callback function I got a .on that is bind to <a> that load for me next page and get me the text of the clicked link (let's say stackoverflow.com).
The problem starts here because in the newly loaded page I got anchors...
After every click on anchor links I got new .text() value.
$.ajax({
url: url,
type: type,
dataType: dataType,
success: function(data){
$('.container').append(data);
$('.container').on('click', 'a', function(e){
e.preventDefault();
var clickLinkName = $(this).text();
console.log(clickLinkName);
$('.container').load($(this).attr('href'));
});
}
});
I would like to know how to lock clickLinkName variable. OR any other way to save only first hit.
I think this would do the trick:
$.ajax({
url: url,
type: type,
dataType: dataType,
success: function(data) {
$(".container").append(data);
var clickLinkName; // Declared here.
$(".container").on("click", "a", function(e) {
e.preventDefault();
// If not initialized, initialize.
if(!clickLinkName) {
clickLinkName = $(this).text();
}
console.log(clickLinkName);
$(".container").load($(this).attr("href"));
});
}
});
That would save only the first value in the variable clickLinkName. This answers your question, but I'm sure there are better ways of doing this.
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 need some help with a jqueryMobile app.
http://www.mandinker.com/proyects_vip_dev/app-llarjove/
In this link you'll find some boxes, click on the box named "CALENDARIO".
Okey, everything works, then press the dropfooter and go to "INICIO".
Do again the first step, go to "CALENDARIO", and tada, error!
Here's the error:
TypeError: calendario is not a function
...".ui-page-active .calendario").size()){calendario();$(
"#datepicker" ).datepicke...
And here is the relevant source code:
$(document).delegate('.ui-page-active', 'pageshow', function () {
if($(".ui-page-active .calendario").size()){
calendario();
$( "#datepicker" ).datepicker();
}
});
function makecalendar(){
$( "#datepicker" ).datepicker();
}
function calendario(){
makecalendar();
$.ajax({
type: "POST",
url: "http://llarjove.softonthecloud.net/calendar",
data: {},
error: function(){},
success: function(data) {
calendario=data;
$(".calendario ul.ui-listview").html("");
$("td").attr("class","ui-datepicker-unselectable");
noticias=data.news;
$.each(noticias,function(key,value){
tmp=value.fecha.split(" ");
tmp=tmp[0].split("-");
$("td[data-month="+(parseInt(tmp[1])-1)+"][data-year="+tmp[0]+"] > a").filter(function(){
tmp[2]=tmp[2].replace(/^0+/, "");
if($(this).text()==parseInt(tmp[2])){
return $(this).text()==parseInt(tmp[2]);
};
}).css({"background":"#00cae8","color":"white"}).attr("href","./calenItem.html?fecha='"+value.fecha+"'").on("click",function(){window.location.href = "./calenItem.html?fecha='"+encodeURIComponent(value.fecha)+"'";});
});
},
dataType: "json",
async: false
});
setInterval(function(){
$(".ui-datepicker-calendar").height($(window).height()-$(".ui-header").height()-120);
},300);
}
Any idea?
As far as I can see your POST request only executes the first time you click on "CALENDARIO".
I suggest you investigate 2 possibilities:
Your event handler is not firing, this usually happens on dynamical created content. To fix it add an event listener to the parent.
Make sure that when creating dynamic content you are replacing, not duplicating with the same ID because the event handler will only fire on the first ID it finds in the HTML tree
UPDATE:
I had a good look at your code and I'll point 2 things that I think are strange and give you trouble.
I suggest you remove from $(document).delegate()
//I think this condition is always true on return or refresh and kills your flow
$( '.ui-page' ).not( '.ui-page-active' ).remove();
and
if (recarga) {
location.reload();
recarga=false;
};
also move $(document).delegate() function after $(document).ready()
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.
$(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.