I want to execute a function inside a remote URL. I know the page URL where the function is and I know the Function name too. The server-side application is built on NodeJs Express. And the function itself look like this
function executer(param1, parama2){
//logic
return true;
}
Is there any way to achieve this?
You can use for example an AJAX call to trigger an endpoint on server like this:
$.ajax({
url: "/remoteservice/executer/",
type: "get",
data: {"param1": "param1","param2":"param2"},
success: function(result){
alert("Job is done");
}
});
But you need to know the endpoint(url) and the method that it waits(get, post or whatever)
If it is some API. Then you can use any node module for request like request or node-fetch. First is for callback and second for promises based. Examples are listed in modules description.
Related
I am calling the twitch TV API to get users info from one endpoint and I want also to call another endpoint in the same API to check if those users are streaming live or not, but only if the first ajax call is successful. Can anyone give me a hint on how to do it?? My first call below:
var getUserInfo = $.ajax({
type: "GET",
url: "https://api.twitch.tv/helix/users/?login=ESL_SC2&login=freecodecamp&login=noobs2ninjas",
// contentType: ('application/x-www-form-urlencoded; charset=UTF-8'),
crossDomain: true,
headers: {
"Client-ID": "5k4g3q59o69v6p9tudn39v50ro1mux",
},
dataType: "json",
success: function (json) {
console.log(JSON.stringify(json, null, 2));
},
error: function () {
console.log("OOPS!!!");
},
})
The jQuery ajax function is built using the callback design to deal with its asynchronicity. You have two callbacks, success and error, one of which will fire when you receive a response from the Twitch API. If you want to make another ajax request depending on if your previous request was successful then you can simply write a very similar ajax request inside your success callback function pointing to the new location you are trying to acccess. I would recommend splitting that off into a separate function to maintain the readability of your code however.
The success function only runs if the call was successful.
Trigger the code for the second request from the success function.
There are many questions out there about JSONP requests and the fact that they cannot be made synchronously. Most workarounds involve using the callbacks, or the success function in an ajax request to do what you want, but I don't think that's going to work for me.
Background: I'm working on a search application using Solr. I'm developing a javascript API for others to use to interact with Solr so they don't need to understand the ins and outs of a Solr search request.
In my api, I have a Request object, with a function called doRequest. The purpose of the function is to perform the call to the solr server (on another domain, thus the need for JSONP), and return a Response object.
Request.prototype.doRequest = function (){
var res = new Response();
$.ajax({
url: this.baseURL,
data: 'q=*:*&start=0&rows=10&indent=on&wt=json',
success: function(data){
res.response = data.response;
res.responseHeader = data.responseHeader;
/*
other...
stuff...
*/
},
dataType: 'jsonp',
jsonp: 'json.wrf'
});
res.request = this;
return res;
};
The "user" would use this function like so...
var req = new Request();
var res = req.doRequest();
and then do something or other with the results in res.
Given that I cannot do a synchronous JSONP request, and I cannot return from within the ajax function, I can't figure out anyway to make sure res is fully populated for the user before they start using it.
Thanks,
It looks like using callback functions is the way to do this. Here's how I ended up doing it in case you're interested.
Request.prototype.doRequest = function (callback){
var res = new Response();
$.ajax({
url: this.baseURL,
data: 'q=*:*&start=0&rows=10&indent=on&wt=json',
success: function(data){
res.response = data.response;
res.responseHeader = data.responseHeader;
res.request = this;
/*
other...
stuff...
*/
callback(res);
},
dataType: 'jsonp',
jsonp: 'json.wrf'
});
};
And now the user uses the function like so:
var req = new Request();
var res = req.doRequest(parseResults);
Where parseResults is the callback function defined by the user that takes the response object as a parameters.
function parseResults(res){
//Doing work
}
Whether or not the rest of your program is synchronous, there are times when you need to touch a REST interface synchronously. An example is where you have a request to get an array of assets (perhaps asset Ids) and then hydrate each of the Ids to get the full data/asset. If you've used the Ooyala API then you know what I mean.
I created what seems to be the first synchronous JSONP module to allow each next request to only run once its previous request has finished. It uses recursion instead of Promises, which means the next request will not be sent until the previous one is successful. The API lives here: https://github.com/cScarlson/jsonpsync
Hope this helps.
This is my first time attempting working with JQuery, Json AND calling a web service.. So please bear with me here.
I need to call a webserivce using JQuery, that then returns a Json object that I then want to save to a javascript variable. I've attempted writing a little something. I just need someone to confirm that this is indeed how you do it. Before I instantiate it and potentially mess up something on my company's servers. Anyways, here it is:
var returnedJson = $.ajax({
type: 'Get',
url: 'http://172.16.2.45:8080/Auth/login?n=dean&p=hello'
});
So there it is, calling a webservice with JQuery and assigning the returned jsonObject to a javascript variable. Can anyone confirm this is correct?
Thanks in advance!
var returnedJson = $.ajax({
type: 'Get',
url: 'http://172.16.2.45:8080/Auth/login?n=dean&p=hello'
});
If you do it like this returnedJson would be an XHR object, and not the json that youre after. You want to handle it in the success callback. Something like this:
$.ajax({
// GET is the default type, no need to specify it
url: 'http://172.16.2.45:8080/Auth/login',
data: { n: 'dean', p: 'hello' },
success: function(data) {
//data is the object that youre after, handle it here
}
});
The jQuery ajax function does not return the data, it returns a jQuery jqHXR object.
You need to use the success callback to handle the data, and also deal with the same origin policy as Darin mentions.
Can anyone confirm this is correct?
It will depend on which domain you stored this script. Due to the same origin policy restriction that's built into browsers you cannot send cross domain AJAX requests. This means that if the page serving this script is not hosted on http://172.16.2.45:8080 this query won't work. The best way to ensure that you are not violating this policy is to use relative urls:
$.ajax({
type: 'Get',
url: '/Auth/login?n=dean&p=hello'
});
There are several workarounds to the same origin policy restriction but might require you modifying the service that you are trying to consume. Here's a nice guide which covers some of the possible workarounds if you need to perform cross domain AJAX calls.
Also there's another issue with your code. You have assigned the result of the $.ajax call to some returnedJson variable. But that's not how AJAX works. AJAX is asynchronous. This means that the $.ajax function will return immediately while the request continues to be executed in the background. Once the server has finished processing the request and returned a response the results will be available in the success callback that you need to subscribe to and which will be automatically invoked:
$.ajax({
type: 'Get',
url: '/Auth/login?n=dean&p=hello',
success: function(returnedJson) {
// use returnedJson here
}
});
And yet another remark about your code: it seems that you are calling a web service that performs authentication and sending a username and password. To avoid transmitting this information in clear text over the wire it is highly recommended to use SSL.
I need to make a request to an API which returns json formatted data. This API is on a sub-domain of the domain this script will run off (although at the moment it's on a totally different domain for dev, localhost)
For some reason I thought that jsonp was supposed to enable this behavior, what am I missing?
Using jQuery 1.4.2
$.ajax({
url:'http://another.example.com/returnsJSON.php',
data: data,
dataType:'jsonp',
type: "POST",
error: function(r,error) {
console.log(r);
console.log(error);
},
success:function(r){
console.log(r);
}
});
Change your type from "POST" to "GET".
That is, only if you intend to retrieve data.
You'll need a combination of Arnaud's answer (don't use POST) and R. Bemrose's answer (make sure server-side returns JSONP), with the added specification of a callback function.
In other words, here's your modified request code:
function dosomething(data) {
console.log(data);
}
$.ajax({
url: 'http://another.example.com/returnsJSON.php',
data: data,
dataType: 'jsonp'
});
Helpful to note that in the generated code you'll see that when the dataType is "jsonp", jQuery outputs a script tag pointing at the url; it's not a typical XHR. You could also use jQuery's getJSON() here.
Then your response will have to be formatted as such:
dosomething({
test: 'foo'
});
When the call is complete, your specified callback will fire.
Did you modify the server-side component to use JSONP?
You can't just tell the client to use JSONP and suddenly expect a JSON script on the server-side to return the correct result.
Specifically, JSONP requires the server to return a JavaScript string that calls a specific function (whose name is passed in with the other arguments) with the return results, which the client then evals.
I'm trying to access the Facebook API Admin.getMetrics method via jQuery. I'm correctly composing the request url on the server side (in order to keep my app secret secret). I'm then sending the url over to the browser to be request using jQuery.getJSON().
Facebook requires that I send a copy of all of my request params hashed with my application secret along with the request in order to verify my authenticity. The problem is that jQuery wants to generate the name of the callback function itself in order to match the name it gives to the anonymous function you pass in to be called when the data returns. Therefore, the name of the function is not available until jQuery.getJSON() executes and Facebook considers my request to be inauthentic due to a mismatched signature (the signature I send along does not include the correct callback param because that was not generated until jQuery.getJSON() ran).
The only way I can think of out of this problem is to somehow specify the name of my function to jQuery.getJSON() instead of allowing it to remain anonymous. But I cannot find any option for doing so in the jQuery AP.
The only thing that did the work for me were the following settings
jQuery.ajax({
url: fbookUrl,
dataType: "jsonp",
type: "GET",
cache: true,
jsonp: false,
jsonpCallback: "MyFunctionName" //insert here your function name
});
The use of jQuery.getScript turned out to be close to -- but not quite -- the answer. Using getScript eliminates jQuery's need to add the dynamically named anonymous function to the request params (though it will still do that if you go ahead and pass it an anonymous function as in the above code). However, the default in jQuery.getScript, as in all the other calls in jQuery's Ajax library, is to append a further additional argument _=12344567 (where 1234567 is really a time stamp). jQuery does this to prevent the browser from caching the response. However, this additional breaks my signing of the request just like the auto-named callback function.
With some help on #jquery, I learned that the only way to get jQuery not to mess at all with your params is to make the request using the base jQuery.Ajax method with the following arguments:
jQuery.ajax({
url: fbookUrl,
dataType: "script",
type: "GET",
cache: true,
callback: null,
data: null
});
(where fbookUrl is the Facebook API url I'm trying to request with its full params including the signature and the callback=myFunction). The dataType: "script" arg specifies that the resulting JSONP should be stuffed into a script tag on the page for execution, cache: true tells jQuery to allow the browser to cache the response, i.e. to skip the addition of the time stamp parameter.
You can pass the JSONP option to $.ajaxSetup that will allow you to fix the function name that gets called, the docs read as follows:
jsonp String
Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url for a GET or the data for a POST. So {jsonp:'onJsonPLoad'} would result in 'onJsonPLoad=?' passed to the server.
See here http://docs.jquery.com/Ajax/jQuery.ajax#options for more details
This is a better solution with a fixed callback:
window.fixed_callback = function(data){
alert(data.title);
};
$(function() {
$.getScript("http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&tagmode=any&format=json&jsoncallback=fixed_callback", function(data) {
alert('done'); } );
});
The problem with this callback is you can only handle one kind of request at a time as the function is globally registered. The callback function would probably have to turn into a dispatcher for the different kinds of data that it could retrieve and call the appropriate function.