how to call another method inside jquery ajax?
methods : {
calert(type,msg="",error=""){
console.log("call me");
},
getData(){
$.ajax({
type: "GET",
success: function(data){
// error calert not found
calert(true,"","asd");
},
error: function (error) {
// also error calert not found
this.calert(false,"",error);
},
complete: function(){
},
url: "/test",
});
},
}
i have try to using this.calert but it doesn't work, still error
You simply need to update your code to use arrow functions, as follows:
methods : {
calert(type,msg="",error=""){
console.log("call me");
},
getData(){
$.ajax({
type: "GET",
success: (data) => {
this.calert(true,"","asd");
},
error: (error) => {
this.calert(false,"",error);
},
complete: (){
},
url: "/test",
});
},
}
Or alternatively, store a local reference to the method, like:
methods : {
calert(type,msg="",error=""){
console.log("call me");
},
getData(){
const { calert } = this;
$.ajax({
type: "GET",
success: function(data){
// error calert not found
calert(true,"","asd");
},
error: function (error) {
// also error calert not found
calert(false,"",error);
},
complete: function(){
},
url: "/test",
});
},
}
btw i found the solution, looks like little bit tricky using this
methods : {
calert(type,msg="",error=""){
console.log("call me");
},
getData(){
let vm = this;
$.ajax({
type: "GET",
success: function(data){
// error calert not found
vm.calert(true,"","asd");
},
error: function (error) {
// also error calert not found
vm.calert(false,"",error);
},
complete: function(){
},
url: "/test",
});
},
}
i store the this to variable and then i use the variable to call another methods.
Anyone have any solutions better than this?
Thanks
Related
I have some js for which I want to write unit test cases using sinon. My js looks like following
var succesHandler = function() {
console.log("yeah success");
};
var failureHandler = function() {
console.log("oops error");
};
var ajaxCall = function(payload, successHandler, failureHandler) {
$.ajax({
type: "POST",
url: "/myUrl",
contentType: 'application/json',
data: JSON.stringify(payload),
success: successHandler,
error: failureHandler
});
};
$('#my-button').live('click', function() {
var dummyPayload = {
"hello" : "coder"
};
ajaxCall(dummyPayload, successHandler, failureHandler);
});
return {
ajaxCall: ajaxCall,
successHandler: successHandler,
failureHandler: failureHandler
};
I want to know how do I spy the ajaxCall() method attached to the #my-button click? Also, how to spy successHandler and failureHandler
I have a simple API call that sets the state of a list array with its response. I was wondering how I would go about implement a try/catch or error message if there is a bad search (i.e like a typo) or if the array is not set with the response. The code snippet is below:
componentDidMount() {
this.search('https://itunes.apple.com/search?term=modern_baseball');
}
search(URL) {
return $.ajax({
type: 'GET',
dataType: 'json',
url: URL,
success: function (response) {
this.showResults(response);
}.bind(this),
error: function() {
alert("Error handling request");
}
});
}
showResults(response) {
console.log(response);
this.setState({
searchResults: response.results,
moveResults: []
});
}
Try something like this:
componentDidMount() {
this.search('https://itunes.apple.com/search?term=modern_baseball');
}
search(URL) {
let self = this; //avoid the .bind call and store a ref to the current context for use inside the ajax handlers.
return $.ajax({
type: 'GET',
dataType: 'json',
url: URL,
success: function (response) {
self.showResults(response);
},
error: function() {
alert("Error handling request");
self.setState({error: "Error handling request", moveResults:[], searchResults:[]}); //set the state directly if there is an error
}
});
}
showResults(response) {
console.log(response);
this.setState({
searchResults: response.results,
moveResults: []
});
}
It sets a variable (self) to the current context (this) and then calls the setState directly in the error handler for the ajax call. Alternatively you could define a callback function just like you do for the success handler.
I know this has been asked multiple times but I'm having a problem executing $.ajax by order using $.when.
In the sample code below, I want to run the first ajax inside $.when() then the second $.ajax inside .done().
var api = {
getFoo: function(callback) {
$.when(this.getBar()).done(function() {
chrome.storage.local.get(['bar'], function(data) {
// omitted some code here for brevity
$.ajax({
type: 'GET',
url: /api/foo/,
dataType: 'json'
}).done(function(result) {
console.log('success', 'went here!');
}).fail(function(request) {
console.log('failed', 'went here!');
});
});
});
},
getBar: function() {
chrome.storage.local.get(['data1'], function(data) {
if(typeof data['data1'] !== 'undefined') {
// omitted some code here for brevity
$.ajax({
type: 'POST',
url: /api/bar/,
data: data['data1'],
dataType: 'json'
}).done(function(result) {
console.log('success', 'went here!');
}).fail(function(xhr, status, error) {
console.log('failed', 'went here!');
});
}
});
}
}
When I ran the code, the second $.ajax execute immediately without waiting for the first $.ajax to finish. Please, could anyone redirect me to the right way?
We need to return a promise for async actions
try this:
getFoo: function(callback) {
this.getBar().then(function(){
chrome.storage.local.get(['bar'], function(data) {
// omitted some code here for brevity
$.ajax({
type: 'GET',
url: /api/foo/,
dataType: 'json'
}).done(function(result) {
console.log('success', 'went here!');
}).fail(function(request) {
console.log('failed', 'went here!');
});
});
});
},
getBar: function() {
var deferred = $q.defer();
chrome.storage.local.get(['data1'], function(data) {
if(typeof data['data1'] !== 'undefined') {
// omitted some code here for brevity
$.ajax({
type: 'POST',
url: /api/bar/,
data: data['data1'],
dataType: 'json'
}).done(function(result) {
deferred.resolve(result);
}).fail(function(xhr, status, error) {
deferred.reject(error);
});
}
});
return deferred.promise;
}
There is a good example at jQuery - when() page. Here is a short example:
var api = {
flag: $.Deferred(),
getFoo: function(callback) {
$.when(this.flag).done(function() {
console.log('getFoo');
});
},
getBar: function() {
console.log('getBar');
this.flag.resolve();
}
}
I have one html element (elem1) and 2 JS functions (func1, func2) that hides and shows elem1 respectively. These JS functions make individual ajax calls and func2 is calling func1 internally.
Problem: I need to call func2, which internally calls func1. Calling func1 hides elem1. After calling func1, I want to show elem1. But this show is not working.
JSFiddle: https://jsfiddle.net/46o93od2/21/
HTML:
<div id="elem">
Save ME
</div>
<br/>
<button onclick="func1()" id="func1">Try Func1</button>
<button onclick="func2()" id="func2">Try Func2</button>
JS:
function func1() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
$('#elem').hide();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
func1();
$('#elem').show();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
Make func1 take a callback function that tells it what to do after it gets the response. func2 can pass a function that shows the element.
function func1(callback) {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
if (callback) {
callback();
} else {
$('#elem').hide();
}
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
func1(function() {
$('#elem').show();
});
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
DEMO
Using Qunit and MockJax, I seek to have two tests, simplified here for ease of understanding. One of the following two tests fails, presumably because the two tests run in parallel and thus they do not each get their own detour of $.ajax(). (The only difference is the responseText in each.) Any ideas on a good way to tweak it so that both the following tests pass?
function testAjax() {
return $.ajax({
type: 'POST',
dataType: 'json',
url: '/fakeservice/1',
data: {'a':'b'}
});
}
asyncTest("testAjax 1", function () {
$.mockjax({
url: '/fakeservice/1',
type: 'POST',
dataType: 'json',
responseText: { 'name1': 'foo' }
});
testAjax().then(
function (response) {
deepEqual(response.name1, 'foo', "no name1");
start();
},
function (error) {
ok(false, "got AJAX error");
start();
}
);
});
asyncTest("testAjax 2", function () {
$.mockjax({
url: '/fakeservice/1',
type: 'POST',
dataType: 'json',
responseText: { 'name1': 'bar' }
});
testAjax().then(
function (response) {
deepEqual(response.name1, "bar", "no name1");
start();
},
function (error) {
ok(false, "got AJAX error");
start();
}
);
});
You must call $.mockjaxClear() at the end of each test (e.g. in the teardown() method of your module). This destroys the mock and prepares the environment for the next test.
function testAjax() {
return $.ajax({
type: 'POST',
dataType: 'json',
url: '/fakeservice/1',
data: {'a':'b'}
});
}
module("AJAX tests", {
teardown: function() {
$.mockjaxClear();
}
});
asyncTest("testAjax 1", function () {
$.mockjax({
url: '/fakeservice/1',
type: 'POST',
dataType: 'json',
responseText: { 'name1': 'foo' }
});
testAjax().then(
function (response) {
deepEqual(response.name1, 'foo', "no name1");
start();
},
function (error) {
ok(false, "got AJAX error");
start();
}
);
});
asyncTest("testAjax 2", function () {
$.mockjax({
url: '/fakeservice/1',
type: 'POST',
dataType: 'json',
responseText: { 'name1': 'bar' }
});
testAjax().then(
function (response) {
deepEqual(response.name1, "bar", "no name1");
start();
},
function (error) {
ok(false, "got AJAX error");
start();
}
);
});
See your adapted example on jsFiddle.