Selecting an element within a JQuery function [duplicate] - javascript

This question already has answers here:
$(this) inside of AJAX success not working
(2 answers)
Closed 9 years ago.
I am using JQuery and AJAX to submit and process a form. Once the user submits the form, the html from the processing form (Using a success function) should get appended to the the current input. But what keeps happening, is that the html gets appended to all inputs on the page, not just the one being selected.
My Code:
$(".comment-form").submit(function() {
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "comment.php",
data: dataString,
success: function(html) {
$(".comment-input-wrap").append(html); <-- The code in question
}
});
$(this).find('.comment-input').val("");
return false;
});
I Tried to use:
$(this).parent().append(html);
But I think the problem is that I can't use $(this) because it is outside the scope of the function. What can I do?
Thanks!

Simplest approach would be to cache the element before ajax call and access it inside the callback.
You can do this way:
$(".comment-form").submit(function() {
var dataString = $(this).serialize();
var $this = $(this); //Cache it here
$.ajax({
type: "POST",
url: "comment.php",
data: dataString,
success: function(html) {
$this.parent().append(html); //access the variable
}
});
$(this).find('.comment-input').val("");
return false;
});
Or use context property of ajax.
$.ajax({
type: "POST",
url: "comment.php",
data: dataString,
context: this, //Set the context for callback
success: function(html) {
$(this).parent().append(html); //access it using the context itself.
}
});
or you can also use $.proxy
$.ajax({
type: "POST",
url: "comment.php",
data: dataString,
success: $.proxy(function(html) {
$(this).parent().append(html); //access it using the context itself.
}, this); // Set the context
});
or using ecmascript5 function.prototype.bind
$.ajax({
type: "POST",
url: "comment.php",
data: dataString,
success: (function(html) {
$(this).parent().append(html); //access it using the context itself.
}).bind(this); // Set the context
});

You could simply store $(this) in a variable:
{
var $this = $(this);
{
$this.append(html);
}
}

Related

Set tooltip text with jQuery [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have the following code:
var text = "";
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: DataReview.BASE + "/Encryption/FetchLatestEditBy",
data: JSON.stringify({
"ExtendedReport_id": dataRow["ExtendedReport_id"],
"Report_id": dataRow["Report_id"]
}),
success: function (data) {
text = data.ResultData;
},
error: function (data) {
console.log(data);
}
});
setTimeout(function () {
console.log(text); //This displays the value
$(this).attr('data-toggle', 'tooltip');
$(this).attr('title', text);
}, 1000);
As you can see, I'm trying to set the tooltip-text in the setTimeout-function. But It will not show up. When I replace text-variable with some dummy-text, it works. But the variable value does not work.
When you use timeout, the this will be in window scope and not with the element. So you are actually adding attributes to the window.
Secondly there is no guarantee that ajax call will be done or you might be waiting too long after the Ajax call by using a timeout. You should be setting the attributes in the success callback of the Ajax call.
Thirdly you probably need to get trigger the tooltip manually so it gets the updated data.
var elem = $(this);
$.ajax({
/* your code here, removed to simplify answer*/
success: function (data) {
elem.attr('data-toggle', 'tooltip');
elem.attr('title', text);
elem.tooltip().tooltip("show"); // might need to change this line based on actual library
}
});
I am assuming your ajax success is taking more time and thus the setTimeout function is called first before the "text" variable value is set in the success function. Try calling a function in onsuccess ajax function.
var text = "";
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
url: DataReview.BASE + "/Encryption/FetchLatestEditBy",
data: JSON.stringify({
"ExtendedReport_id": dataRow["ExtendedReport_id"],
"Report_id": dataRow["Report_id"]
}),
success: function (data) {
text = data.ResultData;
settooltiptext();
},
error: function (data) {
console.log(data);
}
});
function settooltiptext()
{
console.log(text); //This displays the value
$(this).attr('data-toggle', 'tooltip');
$(this).attr('title', text);
}

Javascript image timout

Good day, i'm having a problem with my code, can't get to show the loading image for few seconds, while POST code is getting in database and gives backinformation to show.
$("#poll_vote").click(function(){
var answer = $("input.panswer:checked").val();
var p_id = $("#p_id").val();
$("#poll_load").html("<tr><td align='center'><img src='/images/ajax/ajax4.gif'/></td></tr>");
$.ajax({
type: "POST",
data: "action=poll_vote&p_id="+p_id+"&answer="+answer+"&module="+module+"",
dataType: 'html',
url: "/ajax.php",
success: function(data)
{
$("#poll_content").html(data);
}
});
});
I would hope on your fast help, i'm begginer in java, so can't dicide it myself.
If what you want is to create a delay so the loading animation shows (I believe that is... mmm different, I'm going with that...)
what you need is to set a timeout like so:
setTimeout(function(){ alert("Hello"); }, 3000);
now in your code the function could contain the ajax call:
$("#poll_vote").click(function(){
var answer = $("input.panswer:checked").val();
var p_id = $("#p_id").val();
$("#poll_load").html("<tr><td align='center'><img src='/images/ajax/ajax4.gif'/></td></tr>");
setTimeout(function(){
$.ajax({
type: "POST",
data: "action=poll_vote&p_id="+p_id+"&answer="+answer+"&module="+module+"",
dataType: 'html',
url: "/ajax.php",
success: function(data)
{
$("#poll_content").html(data);
}
});
}, 3000);
});
or be inside the success function, which I believe is better:
$("#poll_vote").click(function(){
var answer = $("input.panswer:checked").val();
var p_id = $("#p_id").val();
$("#poll_load").html("<tr><td align='center'><img src='/images/ajax/ajax4.gif'/></td></tr>");
$.ajax({
type: "POST",
data: "action=poll_vote&p_id="+p_id+"&answer="+answer+"&module="+module+"",
dataType: 'html',
url: "/ajax.php",
success: function(data)
{
setTimeout(function(){$("#poll_content").html(data);}, 3000, data);
}
});
});
I didn't test it, so check if in the second case data can be seen inside the callback function (it should I think...)
Hope it helps.

Check if some ajax on the page is in processing?

I have this code
$('#postinput').on('keyup',function(){
var txt=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt='+txt,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
$('#postinput2').on('keyup',function(){
var txt2=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt2='+txt2,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
Suppose user clicked on #postinput and it takes 30 seconds to process.If in the meantime user clicks on #postinput2 . I want to give him an alert "Still Processing Your Previous request" . Is there a way i can check if some ajax is still in processing?
Suppose I have lot of ajax running on the page. Is there a method to know if even a single one is in processing?
You can set a variable to true or false depending on when an AJAX call starts, example:
var ajaxInProgress = false;
$('#postinput2').on('keyup',function(){
var txt2=$(this).val();
ajaxInProgress = true;
$.ajax({
..
..
success: function(html) {
ajaxInProgress = false;
Now check it if you need to before a call:
if (ajaxInProgress)
alert("AJAX in progress!");
Or, use global AJAX events to set the variable
$( document ).ajaxStart(function() {
ajaxInProgress = true;
});
$( document ).ajaxStop(function() {
ajaxInProgress = false;
});

.keyup() is only working once, why?

I am using this pretty simple jquery function, but it seems to work only on the first keyup..
$('#cmentuser').keyup(function() {
var mess = document.getElementById('cmentuser').value;
var dataString = 'message='+ mess;
$.ajax({
type: "POST",
url: "atuamae.org/comentbyuser.php",
data: dataString,
success: function() {
}
});
});
any ideas on how to keep it active?
It works, also in the following form (changed mess into jQuery(this).val() and relied on jQuery when encoding the data string):
$('#cmentuser').keyup(function() {
$.ajax({
type: "POST",
url: "atuamae.org/comentbyuser.php",
data: {
'message': jQuery(this).val()
},
success: function() {
// success callback
}
});
});
Proof that it works: jsfiddle.net/xfxPR/
You may be dynamically changing some elements (eg. changing ID or assuming id does not need to be unique), or maybe unbinding the event. Just make sure the event is being attached and stays attached to the element you need.
$(document).on('keyup', '#cmentuser', function(e) {//try to find lower element then doc
var dataString = 'message='+ $(e.target).val();
$.ajax({
type: "POST",
url: "/comentbyuser.php", //no cross domain requests, no need for domain name
data: dataString,
success: function() {}
});
});
try this
$('#cmentuser').live('keyup',function() {
var mess = $(this).val();
var dataString = 'message='+ mess;
$.ajax({
type: "POST",
url: "atuamae.org/comentbyuser.php",
data: dataString,
success: function() {
}
});
});

Setting data-content and displaying popover

I'm trying to get data from a resource with jquery's ajax and then I try to use this data to populate a bootstrap popover, like this:
$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);
and the function for retrieving data is:
get_data_for_popover_and_display = function() {
var _data = $(this).attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}
What is happening is that the popover is NOT showing when I click, but if I hover the element later it will display the popover, but without the content (the data-content attribute). If I put an alert() inside the success callback it will display returned data.
Any idea why is happening this? Thanks!
In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display().
Don't worry! The this keyword is hairy; misinterpreting its value is a common mistake in JavaScript.
You can solve this by keeping a reference to this by assigning it to a variable:
get_data_for_popover_and_display = function() {
var el = $(this);
var _data = el.attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
el.attr('data-content', data);
el.popover('show');
}
});
}
Alternatively you could write var that = this; and use $(that) everywhere. More solutions and background here.
In addition to the answer above, don't forget that according to $.ajax() documentation you can use the context parameter to achieve the same result without the extra variable declaration as such:
get_data_for_popover_and_display = function() {
$.ajax({
type: 'GET',
url: '/myresource',
data: $(this).attr('alt'),
dataType: 'html',
context: this,
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}

Categories

Resources