How to Send a Http Delete Request from Browser

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

No. The HTML 5 spec mentions:

The method and formmethod content attributes are enumerated attributes
with the following keywords and states:

The keyword get, mapping to the state GET, indicating the HTTP GET
method. The GET method should only request and retrieve data and
should have no other effect.

The keyword post, mapping to the state
POST, indicating the HTTP POST method. The POST method requests that
the server accept the submitted form's data to be processed, which may
result in an item being added to a database, the creation of a new web
page resource, the updating of the existing page, or all of the
mentioned outcomes.

The keyword dialog, mapping to the state dialog, indicating that
submitting the form is intended to close the dialog box in which the
form finds itself, if any, and otherwise not submit.

The invalid value default for these attributes is the GET state

I.e. HTML forms only support GET and POST as HTTP request methods. A workaround for this is to tunnel other methods through POST by using a hidden form field which is read by the server and the request dispatched accordingly.

However, GET, POST, PUT and DELETE are supported by the implementations of XMLHttpRequest (i.e. AJAX calls) in all the major web browsers (IE, Firefox, Safari, Chrome, Opera).

How can I make an HTTP DELETE request through JavaScript?

It looks like jquery but I guess it must be ajax?

Ajax is a term used to mean "Making an HTTP request, using JavaScript, from a webpage, without leaving the page". There is no way to make a DELETE request from a webpage without using Ajax.

The example code you have uses the jQuery library to achieve it.

Does ajax need a library to be referenced like jquery does?

You need some means to make the HTTP request. JavaScript has nothing for that built in, but most host environments provide at least one mechanism for it. In the case of a web browser, the standard mechanism is XMLHttpRequest. jQuery's Ajax function is a wrapper around that (usually, there are some exceptions, notably when a JSONP request is made).

Is it as simple as putting this function inside my for-loop and passing the URL I'm building inside the for loop to the 'url' field in the ajax call...?

Yes.

What is the best function to pass to the 'success' parameter here so I know my request was successful?

That depends on what you mean by "know" and "successful".

The code you have will log the response to the console if a successful HTTP status was achieved. If you want to be informed by some other mechanism then you'll need to be more more specific.

If the server doesn't give any content in the response or (in the unlikely event of) it doesn't give a sane HTTP status code, then you might need something else.

Is it possible to return the response from the delete request i.e. success:true if it works?

No. Ajax is asynchronous.

How to send a DELETE Request to the browser in RoR 4

Make sure you have

//= require jquery
//= require jquery_ujs

in your application.js. Also review browser's javascript console after page loaded. Maybe there are some javascript errors, they can block jquery_ujs from working.

Also, note that you need to change :confirm => "You sure?" to :data=> {:confirm => "You sure?"}

Explanation: RUBY is trying to be RESTful, so it's sending PATCH requests for edit action, DELETE requests for destroy action. But most browsers can only submit GET and POST forms. Hyper-links are always opened via GET (and link_to generates <a href=...> tag). So rails do some hackery and "emulate" DELETE, PUT and PATCH requests.

form_tag helper creates additional hidden input: <input name="_method" type="hidden" value="delete" />, then Rails parses requests parameters and assumes that it's DELETE request. You can read about it in documentation.

link_to 'delete', '/some/url', :method => :delete, in its turn, will generate following html: <a href="/some/url/" data-method="delete">delete</a>. Then jquery_ujs javascript intercepts all clicks on links with data-method attribute and creates hidden form with method="POST" and, yes, hidden input with name="_method" value="delete", then this form is submitted. Take a look at jquery_ujs source code, it's rather straightforward.

SO if you see GET request in server console after clicking link with method: :destroy, most likely, there are some problems with javascript.

How make a request in the browser to a DELETE http method in ASP.NET (.NET FRAMEWORK)

After some digging, I found that later in the chain of ASP.NET the HttpContext Changes into HttpContextBase. This context contains GetHttpMethodOverride().

I looked the Method up on github, because it's open source and ASP.NET does contain a middleware such as mentioned.

You can override the actual http method using the key X-HTTP-Method-Override in either the Header, Form or Query string and the actual http method must be POST for the middleware to even consider a http method override.

HTTP DELETE Works From Browser But Not From Postman or IOS App

Preface: You leave out too much relevant information from the question for it to be properly answered. Your Swift code looks, and please don't be offended, a bit beginner-ish or as if it had been migrated from Objective-C without much experience.

I don't know why POSTMAN fails, but I see some red flags in the Swift code you might want to look into to figure out why your iOS app fails.

I first noticed that eventUrl seems to be a String property of the type that contains the deleteEvent function. You mutate it by appending the event id, construct a URL from it (weirdly, see below), then mutate it back again. While this in itself is not necessarily wrong, it might open the doors for racing conditions depending how your app works overall.

More importantly: Does your eventUrl end in a "/"? I assume your DELETE endpoint is of the form https://somedomain.com/some/path/<id>, right? Now if eventUrl just contains https://somedomain.com/some/path your code constructs https://somedomain.com/some/path<id>. The last dash is missing, which definitely throws your backend off (how I cannot say, as that depends how the path is resolved in your server app).

It's hard to say what else is going from from the iOS app, but other than this potential pitfall I'd really recommend using proper Swift types where possible. Here's a cleaned up version of your method, hopefully that helps you a bit when debugging:

func deleteEvent(id: Int) {
guard let baseUrl = URL(string: eventUrl), let token = token else {
// add more error handling code here and/or put a breakpoint here to inspect
print("Could not create proper eventUrl or token is nil!")
return
}
let deletionUrl = baseUrl.appendingPathComponent("\(id)")
print("Deletion URL with appended id: \(deletionUrl.absoluteString)")

var request = URLRequest(url: deletionUrl)
request.httpMethod = "DELETE"
print(token) // ensure this is correct
request.allHTTPHeaderFields = ["Authorization": "Token \(token)"]
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Encountered network error: \(error)")
return
}

if let httpResponse = response as? HTTPURLResponse {
// this is basically also debugging code
print("Endpoint responded with status: \(httpResponse.statusCode)")
print(" with headers:\n\(httpResponse.allHeaderFields)")
}
// Debug output of the data:
if let data = data {
let payloadAsSimpleString = String(data: data, encoding: .utf8) ?? "(can't parse payload)"
print("Response contains payload\n\(payloadAsSimpleString)")
}
}
task.resume()
}

This is obviously still limited in terms of error handling, etc., but a little more swifty and contains more console output that will hopefully be helpful.
The last important thing is that you have to ensure iOS does not simply block your request due to Apple Transport Security: Make sure your plist has the expected entries if needed (see also here for a quick intro).



Related Topics



Leave a reply



Submit