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.
Related
First of all I have to say that I have NO EXPERIENCE in Ajax and I just need this one explanation in order for me to create a simple chrome extension.
There is not much I could find on internet even tho I believe this is very simple.
I need a part of code where I would "call" url from website and I need to adjust certain arguments in that url.
Request URL:http://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE
Request Method:POST
Request Payload :
{amount: 1, user_id: 12345678}
amount: 1
user_id: 12345678
(this is something I get from Network panel- with url and token changed to real things - while calling url automatically from website, but I need to be able to call it manually too.)
So I have an idea of mixing AJAX(which I don't know) and JS in order for me to call this url.
I would use variables for both TOKEN_VALUE and amount&user_id, but I don't know how to even call that url and how to set "request payload" in order for site to do the thing I want it to do.
I would really appreciate if someone would be kind enough to help :)
Work I have done, but doesn't work:
var request=new XMLHttpRequest;
request.open("POST","https://URL_OF_THE_WEBSITE/v1/send?token=TOKEN_VALUE"),request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"),request.Payload("user_id=12345678&amount=5");
I basically tried to remake an example I found online, but it didn't work out, therefore I need someone to actually explain to me how this works and how can I adjust arguments that I need.
function callAjax() {
// the XMLHttpRequest returns the ajax object that has several cool methods, so you store it in the request variable
// #data contains the $_POST[amount],$_POST[user_id],$_POST[whatever] since we are using POST method, if you're using PHP as a server side language
var request = new XMLHttpRequest(),
url = 'place_here_the_url_only',
data = 'amount=1&user_id=12345678&whatever=dataYouWantToSendToServerFromBrowser',
token = document.querySelector('meta[name="csrf-token"]').content;
// when the server is done and it came back with the data you can handle it here
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// do whatever you want!
console.log("The request and response was successful!");
}
};
// method post, your giving it the URL, true means asynchronous
request.open('POST', url, true);
// set the headers so that the server knows who is he talking to, I'm using laravel 5.5
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
// Token needed
request.setRequestHeader('X-CSRF-TOKEN', token);
// then you send the data and wait for the server to return the response
request.send(data);
}
Ajax: Asynchronous JavaScript And XML
It is a mean of communication between the browser and the server hosting the website, it cannot call any other server.
Asynchronous means the website continues to function normally, until the request is returned from the server and the:
if (this.readyState == 4 && this.status == 200) { }
gets triggered
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.
I am trying to make api call to get spotify albums in native javascript without using any js frameworks. I am running into issues where I am unable to send Oauth token using native js. For spotify I have client id and client scret. I can either use that or the Oa
(function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.spotify.com/v1/albums", false);
xhr.send();
document.getElementById("results").innerHTML = xhr.responseText;
})();
function request(callback) {
var xobj = new XMLHttpRequest();
// true parameter denotes asynchronous
xobj.open('GET', YOUR_URL_HERE, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// This marks that the response has been successfully retrieved from the server
// Utilize callback
callback(xobj.responseText);
}
};
xobj.send(null);
}
I would definitely recommend taking a look at the link Frobber provided. It's always better to understand why something does/doesn't work rather than just getting it to work. Here is a mock request to get you started. Hope this helps!
I think you need to read a basic tutorial on how to use XMLHttpRequest, which you can find here
One immediate problem with your code is that it's not using any callback to read the result that comes back from the server. This is all happening asynchronously, so what's occurring in your case is that you're send()ing the request, and then immediately setting innerHTML to a value that probably isn't even available from the server yet.
Check the tutorial for how to get that information back from the server when it's ready.
Note the use of the myFunction callback, and note the use of onreadystatechange. What's happening here is that send() is sending something to the server, in a separate execution thread. You need to register a callback function that will perform the data fetching and DOM update when the server reports back that the data is available, not immediately.
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.
I've been searching on the web for some time and couldn't find an example of how to use the GitHub API from plain client-side javascript (no node-js, jquery etc). I wanted something like authenticate then push a blob, put as simply as possible so I can understand it. Shouldn't be too complicated, I bet you can do that in a dozen lines of code but I don't know a lot about ajax, json and jsonp.
Can you provide an example to get me started?
Thanks!
edit: found this: http://blog.vjeux.com/category/javascript, but I'm still confused as to what are exactly the steps of the process.
If you're looking to use with vanilla JavaScript (i.e. no framework), you need to play around with the XMLHttpRequest object. The XMLHttpRequest provides the core for AJAX implementations.
Despite the XMLHttp prefix, you're not limited to XML or HTTP. You can retrieve any data type (such as JSON) and use other protocols such as FTP.
Say we'd like to GET your user information from GitHub. From a browser, we can easily make the request by visiting https://api.github.com/users/funchal.
Sending an HTTP request in JavaScript is just as simple with XMLHttpRequest:
// Create a new request object
var request = new XMLHttpRequest();
// Initialize a request
request.open('get', 'https://api.github.com/users/funchal')
// Send it
request.send()
If you give this a go from a JavaScript console, you might feel a bit disappointed: nothing will happen immediately. You'll have to wait for the server to respond to your request. From the time you create the instantiate the request object till when the server responds, the object will undergo a series of state changes denoted by the value of the readyState property:
0 UNSENT: open() uncalled
1 OPENED: send() uncalled
2 HEADERS_RECIEVED: headers and status are available after a send()
3 LOADING: the responseText is still downloading
4 DONE: Wahoo!
Once all is finished, you can check the response attribute for the data:
request.readyState // => 4 (We've waited enough)
request.response // => "{whatever}"
When using XMLHttpRequest#open(), you have a few options to consider. Here's the method signature:
void open(
DOMString method,
DOMString url,
optional boolean async,
optional DOMString user,
optional DOMString password
);
The third parameter, which defaults to true, dictates whether the response should be made asynchronously. If you set this to false, you'll have to wait until the response is complete for #send() to return, and you'll pay the price of blocking your whole program. As such, we code in an asynchronous fashion so that our program remains responsive even while we wait. This asynchronicity is achieved by using and event listeners (a.k.a. event handlers) and callback functions.
Say we want to simply dump the response to the console once it arrives. We first need to create a callback function that we'd like to execute onload:
function dumpResponse() {
// `this` will refer to the `XMLHTTPRequest` object that executes this function
console.log(this.responseText);
}
Then we set this callback as the listener/handler for the onload event defined by the XMLHttpRequest interface:
var request = new XMLHttpRequest();
// Set the event handler
request.onload = dumpResponse;
// Initialize the request
request.open('get', 'https://api.github.com/users/funchal', true)
// Fire away!
request.send()
Now since you'll be receiving the data as a string, you'll need to parse the string with JSON.parse() to do anything meaningful. Say I want to debug the number of public repositories you have along with your name. I can use this function to parse the string into JSON, and then I can pull the attributes I want:
function printRepoCount() {
var responseObj = JSON.parse(this.responseText);
console.log(responseObj.name + " has " + responseObj.public_repos + " public repositories!");
}
var request = new XMLHttpRequest();
request.onload = printRepoCount;
request.open('get', 'https://api.github.com/users/funchal', true)
request.send()
// => Giovanni Funchal has 8 public repositories!
See the W3C spec and the Mozilla Developer Network for more info on XMLHttpRequest.