Reputation: 5315
I am working with jQuery. I have a scenario where I have one callback method/function that is being called by two different functions/methods.
Problem: how can I know in my callback method/function that which of the two functions / methods called my callback method / function? Because I have some variables that I want assign some values depending upon which method/function called the callback.
Sample code:
var One = "";
var Two = "";
function first(){
var urlink = "https://192.168.150.3/api1?jsonpCallback=myCallback";
$.ajax({
type: "GET",
url: urlink,
dataType:"jsonp",
async: false,
});
}
function second(){
var urlink = "https://192.168.150.3/api2?jsonpCallback=myCallback";
$.ajax({
type: "GET",
url: urlink,
dataType:"jsonp",
async: false,
});
}
myCallback = function(data){
/* if the caller is first then
alert('first') & set value of var One;
else alert("second") & set value of var Two;
How to do this?*/
}
As far as I have read here and there, there is no solution and it didn't work for me atleast. Any suggestions/work around will be appreciated. :)
Upvotes: 1
Views: 367
Reputation: 207
I have updated code. see if this helps you and inform. fiddle
See does this helps you.
var tryFun = function(obj) {
var callerFunction =this.name;
alert(obj +" calling function "+callerFunction);
};
function first() {
this.name="first";
tryFun.call(this,"akash");
}
function second() {
this.name="second";
tryFun.call(this,"akash");
}
first();
second();
Upvotes: 0
Reputation: 1
Try
$(function () {
var one = "",
two = "",
_name = "",
_url = urlink; // without `?jsonpCallback=callback"`
callback = function (data) {
$("#result")
.append("<br>" + _name + ":" + data.result);
alert(_name)
};
var cb = function (name) {
$.ajax({
beforeSend: function (jqxhr, settings) {
_name = name
if (_name === "first") {
one = _name
} else {
two = _name
}
},
type: "GET",
url: _url,
dataType: "jsonp",
jsonpCallback: "callback"
})
};
// call as `cb("first")` , `cb("second")
// allow 1s between calls
$.when(cb("first"),
setTimeout(function() {
cb("second")
},1000))
});
See also
Pass additional parameter to a JSONP callback ,
Can I make a jQuery JSONP request without adding the '?callback=' parameter in URL?
$(function () {
var one = "",
two = "",
_name = "",
_url = "https://gist.githubusercontent.com/"
+ "anonymous/9a6997f09de9b68c59b2/"
+ "raw/f7d7b756005ad6d2b88cf0211f78a2990d7d2dc7/"
+ "content.json";
callback = function (data) {
$("#result")
.append("<br>" + _name + ":" + data.result);
alert(_name)
};
var cb = function (name) {
$.ajax({
beforeSend: function (jqxhr, settings) {
_name = name
if (_name === "first") {
one = _name
} else {
two = _name
}
},
type: "GET",
url: _url,
dataType: "jsonp",
jsonpCallback: "callback"
})
};
$.when(cb("first"),
setTimeout(function() {
cb("second")
},1000))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
Upvotes: 1