this context in ajax data option [duplicate] - javascript

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I have object with data array and mark_read method, which sends PUT request to my Rails app. It looks like this in data option is not the object instance, how can I fix it?
Notifications.prototype = {
constructor: Notifications,
...
mark_read: function() {
$.ajax({
method: "PUT",
url: '/notifications/mark_read',
data: this.data.slice(0,5)
});
}
...
}

You should store "this" in a closure before trying to access it from inside of $.ajax function.
It should be something like this
Notifications.prototype = {
constructor: Notifications,
...
mark_read: function() {
var me = this;
$.ajax({
method: "PUT",
url: '/notifications/mark_read',
data: me.data.slice(0,5)
});
}
...
}

The scope for this is the mark_read function, so the context for this is whatever Notification object mark_read() is called upon.

Related

How to get "this" object in to a callback function? [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
How do I get this into a callback?
Started out with this, worked.
$('#grid').w2grid({
name : 'grid',
// Lost of setup
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
});
this.reload();
},
});
Then to only call reload if the request worked.
$('#grid').w2grid({
name : 'grid',
// Lost of setup
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
this.reload();
});
},
});
Of course "this" is no longer references the object I want to access.
Or how would I gain access the parent object?
You may just bind your this inside the callback.
Note: Beware of any side-effects. Apparently you don't seem to need the new this inside the callback.
Try:
$('#grid').w2grid({
name: 'grid',
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], (function(data) {
this.reload();
}).bind(this));
}
});
When arrow-functions are available, I'd suggest to use them rather than binding this.
You can do it like this:
let parent = this;
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
parent.reload();
});

How to pass array through jquery get function? [duplicate]

This question already has answers here:
Pass array to mvc Action via AJAX
(12 answers)
Closed 6 years ago.
let's assume I have controller method like this
public ActionResult GetSelected(int[] ids)
{
//do something
return Json (ids, JsonRequestBehavior.AllowGet)
}
and in view file I have function which creates array named list.
How can I pass my array to controller using $.get function?
I would do this :
var data = { 1, 2 };
$.ajax({
url: '#Url.Action('GetSelected','ControllerName')',
data: {
getSelected : data
},
success:function(data){
//Do Something With the return data or HttpStatusCode
}
});

Object scope. Why does this give a null object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 8 years ago.
initialize: function() {
var store = {};
var item = {};
var me = this;
Ext.Ajax.request({
url: "some_valid_url",
success: function(response) {
try {
var parser = new DOMParser();
var xml = parser.parseFromString(response.responseText, "text/xml");
store = Ext.create('Ext.data.Store', {
autoLoad: true,
fields: ['temp', 'low', 'high', 'desc', 'icon'],
data: xml,
proxy: {
type: 'memory',
reader: {
type: 'xml',
rootProperty: 'current',
record: 'day'
}
}
});
item = Ext.create("Ext.Container", {
var bla = "hello world",
})
} catch (err) {
//err
}
}
});
}
console.log("STORE AND ITEM");
console.log(item);
console.log(store);
Why item and store give back null objects?
However I can see that it's parsing some data, as if I put console.log in between store and item elements I will get a valid element.
STORE AND ITEM
Object {} ArticleWeatherList.js:105
Object {} ArticleWeatherList.js:106
Ajax is asynchronous which basically means that the code continues executing without waiting for the request to complete. Therefore, when you are trying to use item and store, the request has not yet completed and the success method which sets them has not yet run. The only ways round this are to force the request to happen synchronously (although this is generally a bad idea) or to put all the code that depends on the request into the success callback or functions that are called from within the success callback.
Because,
you have declared store and item as local variables inside intialize function. If you want access these variable outisde you must declare them in the global not in the function. The same can be achived omitting the var keywords in the declaration of the variables.
initialize: function () {
store = {};
item = {};
var me = this;
....
this should works but is a considered a bad practice.

Passing a reference to an object to a callback function in jQuery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
$.ajax context option
I've got some code that looks like this:
$.post(self.baseUrl + 'api/method',
{param1: data},
function (response) {
// Do something
});
I want to pass a reference to the self object through to the callback, which I imagined would be something like this:
$.post(self.baseUrl + 'api/method',
{param1: data},
function (response, self) {
// Do something
});
However, it doesn't work like this, the jQuery documentation doesn't show a way that would make this possible and a cursory Google search hasn't turned up anything. Is this possible, and how can I do so?
If you use the $.ajax method you can specify a context:
$.ajax({
type: "post",
context: self,
data: {param1: data},
success: function (response) {
console.log(this); // now 'this' refers to self
}
});
#karim79 shows the best solution. I just want to show some other possible ways
var App = {
baseUrl: "http://.../",
fetchData: function() {
var self = this;
$.post(self.baseUrl + 'api/method', {
param1: data
}, function(data) {
self.onDatafetch(data);
//or
globalDataFetch(data, self);
});
},
onDatafetch: function(data) {
this.showMsg();
},
showMsg: function() {
alert("Success");
}
}
App.fetchData();
function globalDataFetch(data, object){
// received data and object
}
why do you want to do sth like that?
you could easily use a closure:
var param1 = data;
$.post(self.baseUrl + 'api/method', function (data) {
// access param1 here
});

How do i fix this JS scope in GM_xmlhttpRequest

When i run this code alert 2 shows 6 different href links. alert 3 shows the last href 6 times. How do i make it use the same object (linkdom aka thelink) as alert 2.
NOTE: This is in a greasemonkey script
{
var linkdom = thelink;
alert('2' + linkdom.getAttribute("href"));
GM_xmlhttpRequest({
method: 'GET',
url: href,
onload: function(resp){
//...
alert('3' + linkdom.getAttribute("href"));
}
});
//...
}
If this were your own function, I'd say to pass it in as a parameter. Or if JavaScript had default parameters, I'd say pass it in as a default parameter. The way it is now, though... try this.
{
var linkdom = thelink;
alert('2' + linkdom.getAttribute("href"));
GM_xmlhttpRequest({
method: 'GET',
url: href,
onload: (function() {
var localvar = linkdom;
return function(resp){
//...
alert('3' + localvar.getAttribute("href"));
}})()
});
//...
}
This creates an outer function and sets a local variable to the current value of linkdom. It then creates your function and returns it. I then immediately apply the outer function to get your function back. The outer functions won't share the same local variable, so the code should work.

Categories

Resources