This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 4 years ago.
I'm new to JS. I try the function closure, just as in the documentation example and I get an uncaught reference. Why?
function fetchData(filter) {
return $.ajax({
type: "GET",
contentType : "application/json; charset=utf-8",
dataType: "json",
url: "my_url"+route,
data: filter
});
};
function fetchDataSource(filter) {
var route = "data_source";
return fetchData(filter);
};
And now, when I call the function:
var filter;
fetchData(filter);
I have the following error:
Uncaught ReferenceError: route is not defined
at fetchData (:6:49)
at fetchDataSource (:3:10)
at :1:1
Why is route not visible in my function?
Thanks
the fetchData function does not include route in its closure because route is defined inside a sibling function. There are ways to make it closure around route as you would expect, somethign like this would work:
var route;
function fetchData(filter) {
return $.ajax({
type: "GET",
contentType : "application/json; charset=utf-8",
dataType: "json",
url: "my_url"+route,
data: filter
});
};
function fetchDataSource(filter) {
route = "data_source";
return fetchData(filter);
};
Because route is defined in the scope that contains fetchData here, whereas it's not in yours.
Related
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 2 years ago.
I am making a successful AJAX call which returns data but I keep getting sortable.class.js:50 Uncaught ReferenceError: buildTabs is not defined in the success handling and I cannot figure out what the problem is.
Does anyone see what's wrong with this?
Instantiated and called with
const sortable = new Sortable();
sortable.v2Test();
The Class(shortened)
class Sortable {
constructor() {}
v2Test() {
this.v2Tabs();
}
buildTabs(dataset) {
console.log('working');
}
v2Tabs() {
$.ajax({
type: 'GET',
url: '/v2/tabs',
contentType: 'application/json',
success: function (data) {
buildTabs(data);
},
});
}
}
===== Working version with passed function ====
this.v2Icons(1, 'tab1', this.processIcons); //call
v2Icons(tab, targetElement, callback) {
$.ajax({
type: 'GET',
url: '/v2/icons/' + tab,
contentType: 'application/json',
success: function (data) {
callback(targetElement, data.icons, data.maxrow);
},
});
}
processIcons(targetElement, dataset, maxrow) {
// do the shizzle
});
success function doesn't have reference to the parent object methods without a reference, to fix this you can use arrow function which bind to the parent by default:
class Sortable {
constructor() {}
v2Test() {
this.v2Tabs();
}
buildTabs(dataset) {
console.log('working');
}
v2Tabs() {
$.ajax({
type: 'GET',
url: '/v2/tabs',
contentType: 'application/json',
success: (data) => {
this.buildTabs(data);
},
});
}
}
This question already has answers here:
How to pass parameters to jQuery document.ready() function (ASP.NET MVC, C#)
(4 answers)
How to add parameters to a #Url.Action() call from JavaScript on click
(2 answers)
Closed 4 years ago.
Why does the "action" input parameter not recognized by the ajax call?
My code looks like this:
<script type="text/javascript">
$(document).ready(function (string action) {
$.ajax({
type: "GET",
url: #Url.Action(action, "Default") ,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
}).done(function () {
alert("Success");
}).error(function () {
alert("Faile");
});
}
</script>
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 4 years ago.
I have an AJAX call, where I use a variable bound to this in my URL call. I also need this in the callback.
Initially I was using the var _that = this pattern, but that didn't pass code review. I threw in the context: this, but unsure if it works on that second link, where I need to actually access this or if it's only available in the callback.
Question:
What is the cleanest approach for accessing the this context variable to use in the url param and also the callback?
$.ajax({
url: "/search/".concat(_this.options.modelId),
contentType: "application/json; charset=utf-8",
dataType: "json",
type: 'PUT',
data: JSON.stringify(templatePerms),
context: this,
success: function(data) {
this.message('Success!', 'Updated', 'success');
this.cleanup();
}
});
Instead of creating an extra variable (e.g. _this), utilize Function.bind() passing this as the thisArg:
success: function(data) {
this.message('Success!', 'Updated', 'success');
this.cleanup();
}.bind(this)
class Test {
constructor() {
this.options = {};
this.options.modelId = '1';
this.doIt();
}
doIt() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/' + this.options.modelId,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: 'PUT'
})
.then(data=>this.success.call(this, data));
}
success(data) {
this.message(data);
}
message(msg) {
alert(msg.id);
}
}
new Test();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am trying to retrieve certain values in a JSON object retrieved from AJAX.
Using console.log(), I was able to view these:
0: Object
title: "First post"
body: "This is a post"
id: 1
userId: 27
.
.
.
100: //same format of data as object 0
Now I want to try storing the whole JSON object above so that I can use the userId and match it with another list of data to find the user who made the post. Problem is, I can't store it to a global variable. Here is my jscript snippet:
var postJson; //global variable
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
console.log(response);
}
});
I also tried doing postJson = $.ajax but nothing happened and postJson continues to be undefined.
$.ajax is async function, you need to use callback or do all the code in success function
var postJson; //global variable
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
postJson = response;
//do something with postJson or call function doSomething(response)
}
});
function doSomething(r){
//r is here
}
---somewhere in a function---
$.ajax({
url: root + '/posts',
type: "GET",
dataType: "JSON",
success: function(response){
doSomething(response);
//do something with postJson or call function doSomething(response)
}
});
You can do directly via calling function from response no need to declare variable. Hope it will also helps you
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have this code:
function aaa (){
var db_data;
$.ajax({
url: "http://localhost:8888/aaa/{{$article->id}}",
type: "GET",
async: true,
dataType: "json",
success: function(data) {
db_data = data;
console.log(db_data);
},
error: function (data) {
console.log(data);
console.log('GRESKA NEKA');
}
});
console.log(db_data);
};
but then I get at least line console.log(aaa) - > undefined...
Why? First console.log work ok but outside ajax I cant get db_data... WHy?
You are ordering a pizza, then trying to eat it before it is delivered! Ajax is an async call and the success gets called-back long after the last console.log executes.
You need to only use Async data in side the callbacks.
An alternative is to use the promise returned by Ajax so you code becomes a function that "promises to return the data":
// Return the Ajax promise
function aaa() {
return $.ajax({
url: "http://localhost:8888/aaa/{{$article->id}}",
type: "GET",
async: true,
dataType: "json",
});
}
// and use like this
aaa().then(function(data){
// Do something with the data
}).fail(function(data){
// Do something with the data when it fails
});
Promises make the functions reusable.