How can I send a http delete request from browser? - javascript

Is there a way to send a DELETE request from a website, using xmlhttprequest or something similar?

As someone mentioned above, jQuery will do this for you, via the following syntax:
$.ajax({
type: "DELETE",
url: "delete_script.php",
data: "name=someValue",
success: function(msg){
alert("Data Deleted: " + msg);
}
});

You can test if your browse has DELETE implemented here
Supposing req is a XMLHttpRequest object, the code would be req.open("DELETE", uri, false);

I use fetch API on one of the projects:
fetch(deleteEndpoint, {
method: 'delete',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({id: id, token: token})
})
I have deleteEndpoint, id and token previously defined.

This can be done with jQuery, if you don't mind the dependence on a framework. I believe jQuery uses XmlHttpRequest to perform this action. You'd use the $.ajax function with the type parameter set to DELETE.
Please note that not all browsers support HTTP DELETE requests.

I believe that both PUT and DELETE are not implemented (in the case of Prototype) due to flaky browser support.

You can use php to do this:
setup your XMLHTTPRequst to call a phpscript that deletes a named file, and then pass the filename that you intend to be removed to the php script and let it do its business.

Related

W3C Validator offline on localhost by ajax

I use to programming Brackets text editor and I have already installed W3C validator but it working while I'm online but offine not. I try install https://validator.w3.org/docs/install.html and I running to localhost:8888 but brackets's extension connecting only via ajax (javascript). Is possible send ajax like to original W3C website?
Maintainer of the W3C HTML checker (validator) here. Yes it is possible to send an ajax request to a local instance of the current checker. To use Fetch to do it and get JSON-formatted results back:
var checkerUrl = "http://localhost:8888/?out=json"
fetch(document.location.href)
.then(function(currentDoc) { return currentDoc.text(); })
.then(function(htmlSource) {
fetch(
checkerUrl, {
method: "POST",
mode: "cors",
body: htmlSource,
headers: new Headers({ "Content-Type": "text/html;charset=utf-8" })
})
.then(function(checkerResponse) { return checkerResponse.json(); })
.then(function(jsonOutput) {
console.dir(jsonOutput.messages);
})
});
That shows the basic steps to follow to deliver the request in the way the checker expects:
send a document to the checker as the body of a POST (in this example, the current doc)
tell the checker to format its results as JSON (out=json)
make text/html;charset=utf-8 the media type of the POST body you send to the checker
The checker also supports multipart/form-data for giving it the HTML source to be checked, but giving it the source as a POST body instead is the preferred (and better) way for doing it.
If instead of using fetch() you want to use JQuery $.ajax(…), here’s an example:
var checkerUrl = "http://localhost:8888/?out=json"
$.get(document.location.href,
function(htmlSource)
{
$.ajax({
url: checkerUrl,
type: "POST",
crossDomain: true,
data: htmlSource,
contentType: "text/html;charset=utf-8",
dataType: "json",
success: function (jsonOutput) {
console.dir(jsonOutput.messages);
}
});
});
And if instead of either fetch() or JQuery $.ajax(…) you want to use old-school XHR but it’s not clear how to handle the details in that case, let me know and I can post an example of that too.
In all cases, the .messages JSON output is an array of objects that each contain something like:
firstColumn: 1
lastColumn: 6
lastLine: 4
message: "Unclosed element “span”."
type: "error"
The documentation for the checker JSON format gives more details of the JSON the checker emits.

jQuery $.ajax done callback not firing

I have the following code :
$("#loginSubmitButton").on("click",function(){
var loginUserDetails = {
email: $("#email").val(),
password: $("#password").val()
};
//Send the AJAX request to authenticate the user
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: JSON.stringify(loginUserDetails),
contentType: "application/json;charset=UTF-8",
dataType: "json",
}).done(function() {
$("#loginResult").text("Login successful");
})
.fail(function() {
$("#loginResult").text("Login failed");
});
});
As per the jquery documentation (unless I am understanding something incorrectly) I expect the done to be fired if I receive a 200 OK from my web server. However, in chrome console I can see a 200 OK response but jquery seems to fire the fail handler.
Does anyone have any idea what I might be doing wrong here?
You need to remove:
dataType: "json"
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's probably ignoring the underlying issue. It's most likely caused by a parser error (the browser parsing the json response). Firstly examine the XHR parameter in either .always() or .fail().
Assuming it is a parser fail then why? Perhaps the return string isn't JSON. Or it could be errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
If your server returns empty string for a json response (even if with a 200 OK), jQuery treats it as failed. Since v1.9, an empty string is considered invalid json.
Whatever is the cause, a good place to look at is the 'data' parameter passed to the callbacks:
$.ajax( .. ).always(function(data) {
console.log(JSON.stringify(data));
});
Its contents will give you an understanding of what's wrong.
Need to remove , from dataType: "json",
dataType: "json"
The ajax URL must be the same domain. You can't use AJAX to access cross-domain scripts. This is because of the Same Origin Policy.
add "dataType:JSONP" to achieve cross domain communication
use below code
$.ajax({
URL: cross domain
dataType: 'jsonp'
// must use dataType:JSONP to achieve cross domain communication, otherwise done function would not called.
// jquery ajax will return "statustext error" at }).always(function(data){}
}).always(function(data){
alert(JSON.stringify(data));
}
A few things that should clear up your issue and a couple hints in general.
Don't listen for a click on a submit button. You should wait for the submit event on the form.
The data option for $.ajax isn't expecting a JSON string. It wants a serialized string or an array with name and value objects. You can create either of those easily with .serialize() or .serializeArray().
Here is what I was thinking for your script.
$('#form-with-loginSubmitButton').on('submit', function(e){
e.preventDefault():
var $form = $(this),
data = $form.serializeArray();
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: data
}).done(function(result){
console.log(result);
});
});

Calling a web service in JQuery and assign returned Json to JS variable

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.

jQuery .getJSON vs .post which one is faster?

Using
$.getJSON();
or
$.post();
I'm trying to send some parameters through a page that is just for AJAX request
and get some results in JSON or html snippet.
What I want to know is that which one is faster?
Assume the HTML file would be simply plain boolean text (true or false)
As others said there is no real difference between the two functions, because both of them will be sent by XMLHttpRequest.
If the server is handling both of the requests with the same code then the handling times should be the same.
Therefore the question can be translated to which one is faster the HTTP GET request or the POST request?
Because the POST request needs two additional HTTP headers (Content-Type and Content-Length) comparing to the GET request the latter should be faster (because less data will be transferred).
But that's just the speed, I think it's better to follow the REST guidelines here. Use POST if you're modifying something, use GET if you want to fetch something.
And one another important thing, GET responses could be cached, but I was having problems caching POST ones.
i dont think it will make a difference both make use of ajax, .post loads the data using http post request where as getJSON uses a http get request more over you dont have to explicitly tell getJSON the dataType
If it is a HTTP action that is retrieving data from the server without persisting (updating) anything, GET is the correct semantic to use.
Both post and get use HTTP so performance difference will be negligible, especially considering the variables of WAN communication.
They are both wrappers/shorthand methods for jQuery.ajax, so there wont be a performance difference.
This is old but ...
We all have to remember about: CSRF/XSRF.
If you do it this way:
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: {
token : 'pass-some-security-token-here'
},
cache: false,
success: function(data) {
//do your stuff here
}
});
you can receive it then like this, nullifying most CSRF/XSRF
if (isset($_POST['token'])) { //you can also test token further
//do your stuff her and send back result
} else {
//error: sorry, invalid, or no security token
}
In many cases GET is an invitation for bad guys, as getJSON uses GET HTTP request.
$.getJSON(); is a shortcut to $.ajax(); which also calls $.post(); so you won't see much difference (but it will be easier to use $.getJSON() directly).
See the jquery doc
[EDIT] NimChimpsky was faster than me...
There are no difference, Because both are using XMLHttpRequest.
First, $.getJSON() is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
https://api.jquery.com/jQuery.getJSON/
Second, $.post() is also a shorthand Ajax function, which is equivalent to:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
https://api.jquery.com/jquery.post/

jQuery JSONP, only works with same site URLs

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.

Categories

Resources