I have the following function below which I am trying to re-write using $http provider. The documentation shows so many different ways of doing this and I cant get it right. Here is the function:
function Ingest(Filename, ID, baseUrl, logger){
var url = baseUrl + '/php/' + 'Ingest.php';
var dataString = 'Filename=' + encodeURIComponent(Filename) + '&ID=' + encodeURIComponent(ID);
$.ajax({
type: "POST",
url: url,
async: true,
cache: false,
data: dataString,
success: function(results){
logger.success('Ingestion process has been finished.', '', 'Success');
}
//fail
, error: function (jqXHR, textStatus, errorThrown){
alert("error:\r\n" + errorThrown);
}
});
}
and here is a sample of $http code:
$http({
method: 'POST',
url: config.appBaseUrl + '/php/' + 'Ingest.php',
data: { ID: encodeURIComponent(ID), Filename: encodeURIComponent(Filename) }
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Thank you
In the 1st sample you do a post, in the second a get.
You can just use shortcut method provided by $http.
$http.post( config.appBaseUrl + '/php/' + 'Ingest.php', Filename: encodeURIComponent(Filename), ID: encodeURIComponent(ID)).then(function(response){
}, function(rejection){
});
If you want to set some specific configuration for the $http (headers,...) use the 3rd argument of the functions.
Note that shortcut post/put have a second argument for request body, 3rd for configurations.Delete and get does not have request body argument so configuration are the 2nd argument of the function.
Related
I use the following ajax script.
$.ajax({
dataType: 'json',
url: url,
data: tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
The attribute Route in Web API before method.
[Route("api/tudisp/Edit/{tuDispId}")]
public IHttpActionResult Edit(int tuDispId)
{
}
The genarated request from ajax.
http://localhost:xxxxx/api/tudisp/Edit/?179
How to force ajax to not generate sign '?' by id parameter.
The simplest way to do it is to change the url property of the Ajax options...
$.ajax({
dataType: 'json',
url: "http://localhost:xxxxx/api/tudisp/Edit/" + tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
GET parameters are automatically appended to the Url as a querystring, which is fine if that's what your application is expecting, but not when you're using routing as you are.
However, if you wanted to modify existing Ajax requests you can use prefiltering. This example modifies the Url of the ajax call, replacing {variable} with a given value from the data object...
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.data = ""; // this removes the querystring
for (key in originalOptions.data) {
options.url = options.url.replace("{" + key + "}", originalOptions.data[key]);
}
});
$.ajax({
url: "http://localhost:xxxxx/api/tudisp/Edit/{tuDispId}",
data: {
"tuDispId": 179
}
});
If you wanted to use something like that then I'd strongly recommend spending a bit of time making it more robust, but it's an example of how you could do what you want.
I am trying to include an API key for the first time from New York Times API ( http://developer.nytimes.com/) and use ajax to fetch news from it to populate a local website but I'm not seeing any results. I was told to Make sure your API key is set in the URL's query parameters but I'm not sure how to do it.
?api-key=your-key
Here is what I have done:
// Built by LucyBot. www.lucybot.com
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "111111111111111111111111111111"
});
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
I need to see the url in json format for various stories such as business, technology, etc and use them for an ajax call.
Try this I am getting data from this
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "11111111111111111111111"
});
$.ajax({
url: url,
method: 'GET',
dataType: 'JSON',
success: function(data) {
console.log(data)
},
error: function(err) {
console.log('error:' + err)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you can also try like as follows
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
$.ajax({
url: url,
method: 'GET',
dataType: 'JSON',
data: {
'api-key': '11111111111111111'
},
success: function(data) {
console.log(data)
},
error: function(err) {
console.log('error:' + err)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Its not a good practice expose API Key directly in client-side context.
I strongly recommend to create an abstraction layer between the browser and the API.
The idea is target the AJAX request to one own backend action, like:
var url = "www.mydomain.com/api/articlesearch";
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
And inside the backend (/api/articlesearch) we place the request that target to NY Times, using the API Key
This way you get a more suitable code for javascript, keeping the responsibilities correctly distributed.
PS: If you want it even more safe, you can define the API Key using env variables. Here is an example made in Ruby (just for figure it):
# Inside ApisController
def articlesearch
response = RestClient::Request.execute(
method: :get,
url: 'https://api.nytimes.com/svc/search/v2/articlesearch.json',
headers: {api_key: ENV['API_KEY']})
render json: response
end
Using this approach the API Key will also not be present in GIT repository :)
Well, you should try it this way. It should give you a result without cross-origin errors:
$.ajax({
type: 'GET',
url: 'http://api.nytimes.com/svc/search/v2/articlesearch.json',
data: {
'q': queryString,
'response-format': "jsonp",
'api-key': nytApiKey,
},
success: function(data) {
// passed function object for data processing
console.log(data);
},
error: function(err) {
console.log('error:' + err)
}
});
I have a litte problem.
I call an file and this file has to know from which level it was called.
I'm developing in an special tool, and thats how it works here.
for example:
var Url = baseUrl + "?func=ll&objId=" + WebreportId + "&objAction=RunReport";
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
success: function(response){
$('#thirdPartyContent').html($(response).find('#cvDossier').html());
}
});
In my JavaScript Functions in the Call, i have to know from which level it was called. Like here "dossier".
How can i read out an string in the call? With the URL Parms i can just check the superior url, and not the url from the ajax call, isn't it?
I hope you understand my probs.
Try utilizing beforeSend option of $.ajax()
jQuery.ajax({
url: Url,
type: "GET",
data: { level: 'dossier' },
beforeSend: function(jqxhr, settings) {
// set `data` property at `jqxhr` object
jqxhr.data = settings.url..match(/=.*/)[0].split(/=|&.*/).filter(Boolean)[0];
},
success: function(response, textStatus, jqxhr){
// do stuff with `jqxhr.data` : `"dossier"`
console.log(jqxhr.data);
$('#thirdPartyContent')
.html($(response).find('#cvDossier').html());
}
});
I am doing this ajax call:
$.ajax(this.apipath + "/login/refreshToken/", {
type: "POST",
async: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Token ' + localStorage.getItem("loginToken"));
},
dataType: "json",
success: function (response) {
alert("success");
self.set('authenticated', true);
self.set('user', JSON.stringify(response.user));
self.set('loginToken', response.loginToken);
localStorage.setItem("loginToken", response.loginToken);
window.$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Token ' + response.loginToken);
}
});
}
});
Now I want to use Jasmine to write a test. I use SinonJS to create a fake server. I want to test, if the success function is called and if the loginToken item was set. Therefore I use this instruction:
server.respondWith(session.apipath + "/login/refreshToken/", [200, { 'Content-Type': 'application/json' }, JSON.stringify([{user:"asdf",loginToken:true}])]);
success is called but the response object does not contain a loginToken attribute. How can I make the server give the correct response object to the success function?
I am trying to post a request to the google authSub for youtube. I use jQuery for AJAX posts etc. When I make the POST I get a 405 error: "405 Method Not Allowed".
Here is my js:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
},
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
});
The page I am using in the API for this is here.
Here is what the error looks like:
Your data parameters for the request are misplaced see below:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
data: {
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
}
});
Now it may be something youre doing wrong additionally, but this for sure needs to be corrected.
Ah, here is a solution to the problem. If I make the request with the url built out and assigned as an href to an anchor or call it in window.open(); it works.
window.open('https://www.google.com/accounts/AuthSubRequest?scope=http://gdata.youtube.com&next=http://' + globalBrand + '/sitecreator/view.do&session=1');
As for why jQuery's method with the ajax was being rejected I know not. It seems to be an issue elsewhere also.
Solution to error HTTP HEADER OPTIONS in JQuery, this request is ok for me:
var word = 'search+word';
$.ajax({
type: "GET",
url: "http://gdata.youtube.com/feeds/api/videos?q="+word+"&max-results=10&alt=json-in-script&format=5,
cache: false,
dataType:'jsonp',
success: function(data){
//json 'data' var treatment
},
error: function(XMLHttpRequest, textStatus, errorThrown, data){
alert("Not able to fetch the data due to feed unavailability!!!");
}
});
Reference: http://www.mohammedarif.com/?p=180