How to make a DELETE http request with Javascript (not jQuery) - javascript

I'm trying to figure out how to make a DELETE request using just Javascript. I have a service written in Java Spring where the controller for the url that I am working on has method = RequestMethod.DELETE. My url is, say, http://192.168.50.51/my-service/deleteLocation/{value1}/{value2}/{value3}. In my JavaScript, I have an AJAX function like so:
ajaxFunction : function(url, callback, httpMethod) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var jsonParse = JSON.parse(xhttp.responseText);
callback(jsonParse);
}
}
xhttp.open(httpMethod, url, true);
xhttp.send();
}
When I want to use the DELETE url, I have an event handler attached to a button that runs this method:
deleteConfirm : function() {
var valuel = this.value1;
var value2 = document.getElementById('element-id').getAttribute('data-element');
var value3 = document.getElementById('element-id').getAttribute('data-element2');
var url = 'http://192.168.50.51/my-service/deleteInfo/' + value1 + '/' + value2 + '/' + value3;
var httpMethod = 'DELETE';
var deleteCallback = function() { alert('deleted!'); }
this.ajaxFunction(url, deleteCallback, httpMethod);
}
However, I keep getting an error in my console: my-javascript.js:59 DELETE http://192.168.50.51/my-service/deleteInfo/123456789/123-456-7AB/12699 406 (Not Acceptable).
I've read that XMLHttpRequest only accepts GET and POST. How do I go about making a delete request using just JavaScript?

Given the information, it looks like your browser is actually making a DELETE request, because the server gave you back a 406 (Not Acceptable) response. It wouldn't do that if your client never sent the request in the first place. This means that the server received your DELETE request and decided it wouldn't process it. So you'll need to look at the server's API to see what gives you HTTP406 and what needs to be different about your request to make it work.
A good way to debug these kinds of things is through your browsers developer tools. Most browsers have a tab in there that shows you the HTTP requests and responses that the browser made. It will make it easier for you to verify these things, going forward.

Related

What is the proper way to call multiple XMLHttpRequests in the same/multiple script?

I think I ran into a problem of the same variable being used, I might have gotten lucky in some cases where they were separated by function scope. I recently replaced all of my jQuery code with plain JS and this broke a few things however the gained speed/lack of dependency(extra file to download) was good for me in this situation.
So I have the basic form of:
var http = new XMLHttpRequest(),
url = "php/my-script.php",
params = encodeURI('some-param='+value);
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function(data) {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
var result = JSON.parse(http.responseText);
if (result['status'] === "success") {
someFunction(result['some_key']);
}
}
}
http.send(params);
When I ran into the problem of the same http variable being used, I started to replace new ones with http1, http2, etc... seems like a bad idea. Especially having to replace all the http-method(?) calls afterwards like http2.responseText, etc... Should I make this into a function... then pass in the values to post and return the data out?
I guess I don't understand what happens when you call:
var http = new XMLHttpRequest();
Is that a one time use case, where after it has been called you need a new one for another post?
I will try the single-global-function approach. Everywhere I needed to do an AJAX call whether get or post, I always just used $.post/$.get on the spot, not sure if that's bad.

Parse Error from JS AJAX requests only on live server - Python GAE

I have a number of AJAX requests (made with regular JS) that seem to be causing trouble when they make requests of my Python GAE back end. Here's an example:
newGame: function() {
// Calls API to begin a new game, tells view to show placements
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
// ... removed unnecessary code for this question
}
};
var requestOjb = {"user_name": battleshipCtrl.user};
xhttp.open('POST', requestPath + 'game', true);
xhttp.send(JSON.stringify(requestOjb));
},
I am getting a code 400 with a Parse Error, but only on my deployed server. Everything works fine on the dev server. The error says the problem is with my back-end function "new_game", but does not specify a line where the error occurred. The endpoint function works correctly when I access it directly from the API explorer, so I figure the problem must be a result of the data sent from my JS file. Here's that function anyway:
#endpoints.method(request_message=NEW_GAME_REQUEST,
response_message=GameForm,
path='game',
name='new_game',
http_method='POST')
def new_game(self, request):
"""Creates new game"""
user = User.query(User.name == request.user_name).get()
# ... removed unnecessary code for this question
return game.to_form('Good luck playing Battleship!')
The request message it's expecting takes the form of {'user_name': 'some_name'} and it appears, through console.log, that JS is sending it in the right format.
The log where the parse error comes up is interesting, because it shows a 200 code POST request, although it mentions the 400 error when I dive into that log.
I've double and triple checked that my code works on the dev server, and that I've got the exact same code deployed. I don't know where to look next to continue debugging this thing. Any help is appreciated.
Figured it out. I tried running the AJAX request with jQuery, and got a slightly different error message, which lead me to find that I had to set the request header, because it was causing the server to read the incoming data differently than it should have. The following AJAX request now works perfectly.
newGame: function() {
// Calls API to begin a new game, tells view to show placements
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
// ... removed unnecessary code for this question
}
};
var requestOjb = {"user_name": battleshipCtrl.user};
xhttp.open('POST', requestPath + 'game', true);
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify(requestOjb));
},

Calling WebAPI from JavaScript second time

I have very simple OWIN WebApp that hosts one simple controller in console application. Then I have ASP.NET MVC Application and from view I am calling that Web API from JavaScript like this:
function callRest() {
var url = "http://localhost:9151/api/values";
var request = new XMLHttpRequest();
request.open("GET", url, false);
request.send();
if (request.status == 200)
alert("The request succeeded!\n\nThe response representation was:\n\n" + request.responseText)
else
alert("The request did not succeed!\n\nThe response status was: " + request.status + " " + client.statusText + ".");
}
This works. Call really make a call into WebAPI controller and it returns a value. However if I call callRest() function again within the same session (second time click on button), it does not really call WebAPI, but instead immediately returns cached values. How can I make that whenever I call WebAPI it is actually called and not returned from cache?
try using getTime() :
var url = "http://localhost:9151/api/values?"+new Date().getTime();
Enjoy :)
This is by intent to save round-trip time. If you want a new request, the request parameters need to be different otherwise it will cache.
To accomplish that, you could follow the advice given here.
By simply adding a random number to the request it forces the browser to NOT cache.

difference between youtube's request and mine

i want to make a script that makes every video's comment section look like the ones that still have the old kind.
for example, videos on this channel:https://www.youtube.com/user/TheMysteryofGF/videos
in Firebug, in the Net tab, i noticed the comment JSON file's URL it is requested from is different.
i tried to run a code on the youtube watch page which would request the file the same way, but it doesnt work, and in firebug it says it was forbidden.
the URL is the same, they are both POST, and i cant figure out what is different. i can even resend the original request in firebug and it works... so anyway, here is a code i tried on a video with "1vptNpkysBQ" video url.
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://www.youtube.com/watch_fragments_ajax?v=1vptNpkysBQ&tr=time&frags=comments&spf=load', function(data) {
alert('Your public IP address is: ' + data);
}, function(status) {
alert('Something went wrong.');
});
You are using Ajax to get data. Ajax has 1 restriction: You can only get data from your own server. When you try to get data from another server/domain, you get a "Access-Control-Allow-Origin" error.
Any time you put http:// (or https://) in the url, you get this error.
You'll have to do it the Youtube way.
That's why they made the javascript API. Here is (the principal of) how it works. You can link javascript files from other servers, with the < script > tag
So if you could find a javascript file that starts with
var my_videos = ['foo', 'bar', 'hello', 'world'];
then you can use var my_videos anywhere in your script. This can be used both for functions and for data. So the server puts this (dynamically generated) script somewhere, on a specific url. You, the client website can use it.
If you want to really understand it, you should try building your own API; you'll learn a lot.
Secondary thing: Use GET.
POST means the client adds data to the server (example: post a comment, upload a file, ...). GET means you send some kind of ID to the server, then the server returns its own data to the client.
So what you are doing here, is pure GET.

How to read JSON data, that is sent from Android, using Javascript?

I have created a mobile application that scans the surrounding Bluetooth devices and I am able to put the devices into an array list.
Now, using the http POST method, I have to send a JSONObject having this array list to a url and even for this I have written an expected code on the android app(I am sure this code will work because I have already worked on this using POST method to URL's and displaying the response on the activity).
But, how to listen the JSONObject, sent by any android app to the URL, parse it and show it on that particular URL's webpage ?
(In short I am looking for a Javascript code which can handle this and show the list.)
if you already have the URL where the JSON is being posted to you can do:
plain js:
var request = new XMLHttpRequest();
request.open('GET', 'URL', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
with jquery:
var getData = $.getJSON('URL');
getData.done(function(data){
// you have access to data here
});

Categories