Give the following Ajax call in jQuery:
{
.
.
.
,
getSomeData: function(args, myUrl, foo) {
$.ajax( {
type: "GET",
url: myUrl,
data: args,
async: true,
dataType: 'json',
success: myHandler
});
},
myHandler: function (data, textStatus, oHTTP, foo){ ... }
};
Can value foo be somehow appended to the arguments that are passed to success-handler myHandler? Is there any way to pass a value up to the server on the GET, and have that value come back to the client in a round-trip, reappearing in the success-handler's arguments list? I cannot change the structure of what is returned in data.
If you declare myHandler within the request, you can use a closure.
getSomeData: function(args, myUrl, foo) {
$.ajax( {
type: "GET",
url: myUrl,
data: args,
async: true,
dataType: 'json',
success: function (data, textStatus, oHTTP){ ... }
});
},
this way, foo will be available to you inside the success callback.
If you're $.ajax call is in a class and the success callback is passed a method of that class, it does not work.
EDIT: Here is the answer. Note that I am defining the function ajaxCall as a method in a class. I define this.before, this.error, and this.success as methods of ajaxCall because they can call methods from the superClass.
function main(url){
this.url = url;
this.ajaxCall = function(){
this.before = function(){
//Can call main class methods
};
this.error = function(){
//Can call main class methods
};
this.success = function(data){
//Can call main class methods
};
//This is how you pass class arguments into the success callback
var that = this;
$.ajax({
url: this.url,
type: 'GET',
dataType: 'json',
beforeSend: this.before(),
error: this.error(),
success: function(data){that.succes(data);}
});
//Run internally by calling this.ajaxCall() after it is defined
//this.ajaxCall();
}
//Or externally
var main = new main(SOME_URL);
main.ajaxCall();
#Unicron had the right answer but didn't give a good example. Check this out:
$( 'tr.onCall' ).on( 'click', function( event ) {
let pEvent = function() { return event; } // like a fly in amber...
$.ajax( {
...
success: function( data ) {
let x = pEvent(); // x now equals the event object of the on("click")
}
});
});
By declaring the pEvent function inside the anonymous function that fires on("click"), the event object is "frozen" (encapsulated) in its original context. Even when you call it in the different context of the ajax success function, it retains its original context.
More specific example: I'm going to open a modal dialog (styled Div) on click, but when the dialog is closed I want to return the focus to the element that was clicked to open it in the first place...
$( 'tr.onCall' ).on( 'click', function( event ) {
let rTarget = function() { return event.currentTarget; }
$.ajax( {
url: 'ajax_data.php',
...other settings...
success: function( data ) {
modal_dialog(
data,
{
returnTarget: rTarget(),
...other settings...
}
);
}
});
});
On success, it calls a custom function modal_dialog() (defined elsewhere), passing in an object containing various settings. The returnTarget setting contains the HTML ID attribute of the element that was clicked; so when I close the dialog I can run $(options.returnTarget).focus(); to return focus to that element.
Related
Simple ajax query, but being triggered for every item of a class using the .click() event. When it gets to the .done() I cannot figure out how to look up the element which was clicked so I can properly remove the m_action class.
Below is the code. I'm sure I'm missing something simple, but I've been searching with Chrome and Firefox web tools without luck, and can't find a duplicate question here on Stack.
In short: using the code below, how do I properly remove the m_action class of the clicked element on a successful jQuery ajax return?
<script type="text/javascript">
jQuery("div#normal .m_action").click(function() {
jQuery.ajax({
url: "./action.php",
type: "POST",
data: { action: this.id }
}).done(function(result) {
jQuery(this).removeClass("m_action");
jQuery(this).html(result);
}).fail(function(result) {
alert("There was an error.")
});
})
</script>
You can just store a reference to it so that it is available anywhere in that scope:
jQuery("div#normal .m_action").click(function() {
var elem = this; // <-- right here
jQuery.ajax({
url: "./action.php",
type: "POST",
data: { action: this.id }
}).done(function(result) {
jQuery(elem).removeClass("m_action"); // <-- elem is still available
jQuery(elem).html(result); // <--
}).fail(function(result) {
alert("There was an error.")
});
});
Just a note for the future, your problem doesn't have to do with jQuery. This is just a simple use of variables within a scope. The this pointer changes within the done function, so you just needed to cache the reference.
This code should work:
$(document).ready(function()
{
jQuery(".m_action").click(function() {
var self = $(this);
jQuery.ajax({
url: "./action.php",
type: "POST",
data: { action: this.id }
}).done(function(result) {
self.removeClass("m_action");
self.html(result);
}).fail(function(result) {
alert("There was an error.")
});
})
});
</script>
I want to access the value of #schooSelect inside ajax so i can send some data to php onChange.
$.LoadBooks = function () {
$(document).on('change', '#SchoolSelect', (function (e) {
var SchoolVal = ($(this).val())
$.LoadBooks()
}))
var SchoolVal = ($('#SchoolSelect').val())
$.ajax({
type: "GET",
data: {
data: SchoolVal
},
url: "../php/booksads.php"
}).done(function (feedback) {
$('#booksads').html(feedback)
});
}
$.LoadBooks()
Your code is strangely structured. You are somehow "recursively" calling $.LoadBooks inside the event handler, which will cause a new event handler to be added to the element, which is certainly not what you want.
Just bind the event handler once, outside the function:
var loadBooks = function(schoolVal) {
$.ajax({
type: "GET",
data: {
data: schoolVal
},
url: "../php/booksads.php"
}).done(function (feedback) {
$('#booksads').html(feedback)
});
}
$(document).on('change', '#SchoolSelect', function(e) {
loadBooks($(this).val());
});
You can either pass the value of the select element to the function (as shown here) or call var schoolVal = $('#SchoolSelect').val() inside of it to get the value.
The convention is that only the name of constructor functions start with a capital letter. And if your function is related to jQuery in particular, you shouldn't add it to $.
The error in the title of the post came from jQuery version 1.10.2, line 637
I've got a modal that pops up on a button click with some textboxes and when a button inside the modal is clicked, the information that's in the text boxes is added to a database via AJAX. In order to make the page a little more user-friendly I added a setTimeout function to pause the hiding of the modal so the user can see a verification message that the data was added to the database. Block 1 of my code adds the record to the database, but the setTimeout call doesn't work right:
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
//something about the setTimeout function
//that gives the error in the title
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
//*******this function doesn't run
window.setTimeout(function () {
$('#contact').modal('hide');
$('.modal-body input').each(function () {
$(this).val('');
}, 1000);
});
}
});
}
I fixed it using the code:
(the success function is what we need to pay attention to here)
function insert(data) {
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../Service.asmx/InsertPerson",
dataType: "json",
contentType: "application/json",
data: data,
//record gets added to the database
success: function () {
console.log('success before setTimeout');
var successMessage = $('<div>').text('Successfully added to the database...').css('color', 'green');
$('.modal-body').append(successMessage);
window.setTimeout(function () {
$('.modal-body input').each(function () {
$(this).val('');
});
$('#contact').modal('hide');
}, 1000);
}
});
}
I see that I in the first block I didn't close the each function, and I fixed that in the second block and that's why it works, but for future reference, what does this error really MEAN in this context?
It means that you left off the second argument to setTimeout and instead passed it as the second argument to .each().
edit — it looks like jQuery is picking up the argument (that 1000) and trying to pass it through to its internal each implementation. The .apply() function expects it to be an array.
i have this simple jquery function here.Clicking over a button i want to alert its own class before ajax and again upon succession..but the selector "$(this)" in the last situation is not working and the alert returns "undefined"..
why?
$(".button").live("click",function(){
alert($(this).attr('class')); //returns "button"
$.ajax({
type: "POST",
url: myUrl,
data: myData,
cache: false,
success: function(html)
{
alert($(this).attr('class')); //returns undefined
}
});
I would do it like this, store $(this) in a variable so you can use it throughout the function without having to perform a jQuery lookup every time, and you also will not have to depend on the scope to provide the correct element for $(this)
$(".button").live("click",function(){
var button = $(this);
alert(button.attr('class')); //returns "button"
$.ajax({
type: "POST",
url: myUrl,
data: myData,
cache: false,
success: function(html)
{
alert(button.attr('class')); //should also return "button"
}
});
});
wrapping this only once also is a performance enhancement
This will make it work:
$(".button").live("click", function() {
var button = this;
$.ajax({
type: "POST",
url: myUrl,
data: myData,
cache: false,
success: function(html) {
alert($(button).attr('class'));
}
});
});
You cannot use the this reference inside nested functions. The success function is a nested function and it has its own this value. If you need the reference to the button inside that nested function, you have to declare a local variable (like button).
function clickHandler() {
// this == element that was clicked
function ajaxHandler() {
// this != element that was clicked
}
}
Try adding var self = $(this); when you declare the function, and then use self instead of $(this)
So your code looks like this:
$(".button").live("click",function(){
var self = $(this);
alert($(this).attr('class')); //returns "button"
$.ajax({
type: "POST",
url: myUrl,
data: myData,
cache: false,
success: function(html)
{
alert(self.attr('class')); //returns undefined
}
});
Lots of people have posted the solution for this so I won't post the code. Just wanted to mention the reason is because since the success method is a callback your context of $(this) isn't valid anymore. So you need to assign it to a variable and store it for your own use.
$(this) only exists when referencing an HTML object in the DOM. Since you've tried using in the success function of the AJAX call, $(this) has no reference. So for example, in the following code $(this) refers to the item to returned by the jQuery selector:
$('.button').each(function() {
alert($(this));
});
You will need to use a selector to return the item in global scope, and then pass this to the success function in the AJAX call:
var myButton = $('.button');
$.ajax({
type: "POST",
url: myUrl,
data: myData,
cache: false,
success: function(html) { alert(myButton.attr('class')); /* returns button */ }
});
Take a look at the context section here. Basically, what seems to be happening in your code is that the reference to this no longer applies. Makes sense, given that the context of the code has moved on while the AJAX callback is being handled asynchronously. Explicitly setting the context to a particular object in the .ajax() call will carry a reference to the context into the callback function.
You can either add a context: this property to the hash that is passed to the $.ajax call, that way the success handle will it's context set properly, or you can also do something like:
success: $.proxy(function(html) { // using $.proxy will bind the function scope to this
alert($(this).attr('class'));
}, this);
or, another technique I've seen:
$(".button").live("click",function(){
var self = this;
alert($(self).attr('class')); //returns "button"
$.ajax({
type: "POST",
url: myUrl,
data: myData,
cache: false,
success: function(html)
{
alert($(self).attr('class')); //returns undefined
}
});
I'm trying to modify the class of an element if an ajax call based on that element is successful
<script type='text/javascript'>
$("#a.toggle").click(function(e){
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
success: function(data,text){
if(data.error=='')
{
if($(this).hasClass('class1'))
{
$(this).removeClass('class1');
$(this).addClass('class2');
}
else if($(this).hasClass('class2'))
{
$(this).removeClass('class2');
$(this).addClass('class1');
}
}
else(alert(data.error));
}
});
return false;
});
</script>
<a class="toggle class1" title='toggle-this'>Item</a>
My understanding of the problem is that in the success function this references the ajax object parameters, NOT the calling dom element like it does within other places of the click function. So, how do I reference the calling dom element and check / add / remove classes?
You can just store it in a variable. Example:
$("#a.toggle").click(function(e)
{
var target = $(this);
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
success: function(data,text)
{
if(data.error=='')
{
if(target.hasClass('class1'))
{
target
.removeClass('class1')
.addClass('class2');
}
else if(target.hasClass('class2'))
{
target
.removeClass('class2')
.addClass('class1');
}
}
else(alert(data.error));
}
});
return false;
});
jQuery passes the target of the event, along with some other information about it, to your handler function. See http://docs.jquery.com/Events_%28Guide%29 for more info about this.
In your code, it'd be referenced like $(e.target).
Better set ajax parameter : context: this. Example:
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
context: this,
success: function(data,text){
if(data.error=='')
{
if($(this).hasClass('class1'))
{
$(this).removeClass('class1');
$(this).addClass('class2');
}
else if($(this).hasClass('class2'))
{
$(this).removeClass('class2');
$(this).addClass('class1');
}
}
else(alert(data.error));
}
});
I know it's old but you can use the 'e' parameter from the click function.