calling delete rest api by jquery - ajax

I had called the GET REST API by following code :
$.getJSON('http://myapisite.com/user/1?callback=?', function(msg){
console.log(msg);
});
But for calling DELETE REST API through jquery
what i had tried is :
$.ajax({
url: 'http://mysite.com/user/1?callback=?',
type: 'DELETE',
dataType: 'json',
data: '',
success: function(response) { console.log('PUT completed'+response); }
});.
and this api is not being called , I want to know how should i call the DELETE REST API .
Thanks

You are trying to do a cross-domain request. This means that you cannot use XMLHttpRequest (the basis of AJAX) because of the same-origin policy. You are using a workaround called JSONP, which works by inserting <script> tags into your document.
Script tags will always fetch content via GET, so you can't do a DELETE, POST, PUT or suchlike with them.
The best workaround would be to have a script on your own server that proxies the DELETE request for you.

Related

Avoid CORS in rest API

I'm having a problem to make a call to a rest API.
In the document (FAQ) of the web application there is an example that use AJAX request to make the call. Here an example:
var url = 'https://example.com/yyy';
$.ajax({
type: 'POST',
url: url,
cache: false,
data: {
opt: JSON.stringify(example)
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result)
{
console.log(result);
} });
I created a local page with this code to made the post to the API that is located on a remote server but I receive an error about CORS.
Is there any solution to circumvent this problem? I tried to use firefox plugin to allow CORS but it didn't solve the problem. The session is authenticated via form before use the endpoint.
I see several issues:
Try to run the code from a domain and not from local disk (alternatively you can consider using https://crossorigin.me/ )
How does the authentication work? if with cookies you need to add withCredentials to the ajax request.
Make sure the API returns Access-Control-Allow-Origin: foo header where foo is the domain your code runs in. If you also used withCredentials, you should add Access-Control-Allow-Credentials: true

AWS API Gateway CORS Ajax Request Returning Error

I'm trying to use API Gateway as my server for a small database project, and I'm using Ajax to upload data to the server. I know I need to enable CORS to allow me to have cross-domain requests, and I've tried over and over multiple different methods of enabling CORS that I've found online, with no luck. No matter what I do, I seem to get the same error callback: {"readyState":0,"responseText":"","status":0,"statusText":"error"}
Here is the code I am using in the ajax request (for obvious reasons I omitted the URL of the API):
$.ajax({
type: 'POST',
url: API_URL,
data: data,
crossDomain: true,
dataType: "text",
contentType: 'text/plain',
success: (data, status, xhr) => {
alert("Success");
},
error: (e) => {
alert(JSON.stringify(e));
}
});
CORS is in fact enabled in my API, I can confirm this by checking the integration response for my OPTIONS method (there's only one resource and the only methods that exist for it are POST and OPTIONS). Any pointer in the right direction would be appreciated, trying to make this work has been very frustrating.

Why Ajax headers property doesn't work but beforeSend event works in sending http headers to server?

I use #Html.AntiForgeryToken() to decorate the form and try to send the token in an ajax call, at the beginning I used code below:
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: "POST",
url: newurl,
headers: {'__RequestVerificationToken': token},
data: form.serialize(),
datatype: "JSON",
success: function..,
error: function..
})
And it didn't work, server didn't get value I set in the above headers for __RequestVerificationToken, but kept using some old token value.
However, after I switched the "headers" line to the one below, it picked up the token I set.
beforeSend: function (request)
{
request.setRequestHeader("__RequestVerificationToken", token);
},
How come headers doesn't work, but only beforeSend works? So far I couldn't find any clue through online search.
Headers was introduced in jQuery 1.5 and is in the documentation:
https://api.jquery.com/jquery.ajax/
I'm using jQuery 1.11.1, and .Net MVC 5.1.
I set a debugger in jQuery's setRequestHeader method, it turned out that it was called multiple times through the ajax call:
1st:
Content-Type "application/x-www-form-urlencoded; charset=UTF-8"
2nd:
Accept "*/*"
3rd:
__RequestVerificationToken [the token I set]
But it was also called the 4th time, to set __RequestVerificationToken as well:
__RequestVerificationToken [some other token]
By tracking the call stack, I found in our application framework there is a $.ajaxSetup method
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
jqXHR.setRequestHeader("__RequestVerificationToken", environment.antiForgeryToken);
}
});
That was the culprit that overwrote the token I set. By using 'beforeSend' in my ajax call, the 'beforeSend' in ajaxSetup is not called.

How to add Correlation Token parameter to web api request?

I'm using web api without deep understanding what it is, just knowing that each editable entity become a resource, that means has the uri, when web api provides the interpretation of PUT, POST, GET, DELETE HTTP commands to support CRUD operations. But what if for tracing/logging purpose I need to send correlation token together with e.g. GET request? Are there any recommendations and techniques to add to the HTTP request/routing "technical parameters"?
I have found something that need to be tested https://webapicorrelator.codeplex.com/ But actually I would prefer just to understand how it could work...
Or just add it to the heder using jquery ajax headers:
return $.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
url: url,
data: { ElectrodeId: electrodeId },
headers: { "X-CorrelationToken": correlationToken },
method: "POST",
dataType: "json",
success: function (data) {
}

Ajax with JQuery: 200 ok, but not "success"

I'm trying to use AJAX to send a query to Google Books and display the results on my website. I'm using JQuery to send the request and handling the response, like so:
var query = [formatted input from a form];
var URL = "http://books.google.com/books/feeds/volumes?q="+query+"&start-index=1&max-results=5";
$.ajax({
type: "GET",
url: URL,
dataType: "xml",
success: function(data, status){
alert(status);
}
});
Currently, I just have the script alerting "success" if a response is received. If I use my script to send that query to a local page for testing, this works just fine. But when I set the URL to the Google one listed above, as instructed on the Developer API page, I never see the alert. According to Firebug, I am receiving a response and a status of 200 ok as I should, but it's not getting to that "success" path. Does anyone know why?
Edit: I should add that if I follow the URL directly, to http://books.google.com etc. with some random q, it displays the feed XML with no problems, so the query is not the issue.
You can't make cross-domain requests using XMLHttpRequest under the standard browser security settings. One possible solution is to write a local proxy function (assuming you can create server-side code) that forwards the query to the external site, and then returns the response.
Edit: It looks like Google provides a JavaScript API as well. I would assume that they've crafted in such a way to avoid the cross-domain XHR issue.
http://code.google.com/apis/books/docs/js/devguide.html#execute
Edit: The JavaScript API for books was deprecated. While it's no longer practically useful, you can see the original referenced documentation text via the Wayback Machine archive: http://web.archive.org/web/20120414070427/http://code.google.com/apis/books/docs/js/devguide.html#execute
It's a cross-domain problem with ajax calls because browsers have a security model based on a domain policy.
if you don't wan to include the whole Google Books API, you can also use Google Ajax API with jsonp for cross-domain ajax calls.
Docs here:
http://code.google.com/apis/books/docs/js/jsondevguide.html#basic_query
jQuery example
var query = 'jquery';
var URL = 'https://ajax.googleapis.com/ajax/services/search/books?v=1.0&q=' + query;
$.ajax({
type: 'GET',
url: URL,
dataType: 'jsonp',
success: function( data, status ){
alert( data.responseData.results.length + ' results found!' );
},
error: function() {
alert( 'Something goes wrong!' );
}
});
Ciao!

Resources