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.
Related
Is there an event that'll run whether on success or error with Node.js's XMLHttpRequest module? According to the docs, the onloadend event should trigger both on error and success, but it only runs on success. For example:
var XMLHttpRequest = require( 'xmlhttprequest' ).XMLHttpRequest;
var url = 'https://www.example-bad-url.com/json.php';
var xhr = new XMLHttpRequest();
xhr.open( 'GET', url );
xhr.send();
xhr.onloadend = function() {
// This should get logged, but it doesn't.
console.log( 'The request has completed, whether successfully or unsuccessfully.' );
}
In the above script, onloadend doesn't run, why? The URL doesn't exist, so it should trigger onloadend as an error and log "The request has completed..." but the callback function never runs, why?
The xmlhttprequest library for node.js does not fully implement the spec correctly.
If we dig into the code on github, we see the following line of code:
if (self.readyState === self.DONE && !errorFlag) {
self.dispatchEvent("load");
// #TODO figure out InspectorInstrumentation::didLoadXHR(cookie)
self.dispatchEvent("loadend");
}
So the load and the loadend event handlers are only triggered when there is NOT an error, consistent with our observations where
xhr.onloadend = function() {
// This should get logged, but it doesn't.
console.log( 'The request has completed.' );
};
will only log when the event succeeded.
My advice would be to trigger the event manually in the .onerror() handler, which does work. Keep in mind that this is a 3rd party node.js module, not a native one.
Personally I just wrote a small wrapper around xmlhttprequest that mimics the .fetch() interface. The node.js version uses the native node.js http library and the client side version uses xmlhttprequest.
That way I can use the same .fetch() API for both front end and back end code, and just let the system decide if it'll use native fetch, xmlhttp powered fetch, or http powered fetch.
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've been looking for an AJAX function that receives an URL and then returns the JSON object.
Let's say I need to display some Users info from a JSON in URL1 and also mix that display with some Posts info from a JSON in URL2.
I'll like to do this without JQquery.
Let's say something like this:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
function getInfo(){
var users, posts;
loadJSON('http://.com/users',
function(dataU) {
users = dataU;
},
function(xhr) { console.error(xhr); }
);
loadJSON('http://.com/posts',
function(dataP) {
posts = dataP;
},
function(xhr) { console.error(xhr); }
);
console.log(users);
console.log(posts);
}
getInfo();
To achieve this without jQuery, you can fall back to plain JavaScript XMLHttpRequests. This will allow you to establish an HTTP connection with a remote host and e.g. GET data.
To get started with those requests, you can have a look at MDN's getting started guide.
The JSON.parse() function will help you convert the JSON string into a JavaScript object.
As an alternative to XMLHttpRequests, you can also look into the fetch API. It provides a cleaner interface for HTTP calls. Since it is still experimental however, you may want to use a polyfill.
With or without jQuery the XMLHttpRequest objest is asynchronous. jQuery uses it internally. FIY AJAX stands for Asynchronous Javascript And Xml. It means that you cannot receive a synchronous result from an asynchronous function. But you can and should use the result in a callback function you send to the request.
So correct usage is to call console.log (or whatever you want) from success or error callbacks.
There are known solution how to degrade gracefully when XMLHttpRequest is not available. Among these solutions are create and append script or iframe and then read from their .onload handlers. All of them are asynchronous and all previous considerations apply directly to them.
You Cannot Receive Synchronous Result From Asynchronous Function.
I hold this truth against all downvotes.
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.
I need to call a Javascript function from the server side in Client side. I looked and didn't find any way how to do it. I looked also over AJAX but can't figure it out. I am using ASP ( clasic) not .net .
I need to call the function in client-side with a variable that comes from the client-side. Please help me!!! Thanks a million !!!
I am using a FlashMovies that is sending a value to a Javascript function through ExternalInterface class. The function in javascript receiving it is gAnswer(result) and in this function i would need to have something like :
Server side:
function saveResult(result)
{code to be saved on the server goes here }
Client side :
function gAnswer (result)
{ saveResult(result) } <- THis is the part i dont know how to do.
The function gAnswer is being called when the flash movie finished by itself.
Would you be able to provide some code on how to ? thanks to each one of you who helped me =)
Call serverside function from client side via Ajax using this here:
function CallServersideFunction() {
url = "CmsAjax.asp";
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
}
// code for IE
else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
}
if (http) {
http.open("GET", url, true)
http.onreadystatechange = handleHttpResponsearticleID;
}
isWorking = true;
http.send(null);
}
function handleHttpResponsearticleID() {
if (http.readyState == 4) {
if (http.responseText.indexOf('invalid') == -1) {
var xmlDocument = http.responseXML;
fno = xmlDocument.getElementsByTagName('id').length;
if (fno > 0) {
alert('Successfully done.')
}
}
}
}
On this page "CmsAjax.asp" you can do your serverside operations.
See http://beaconpush.com, http://pubnub.com, http://pusher.com, et al.
You can't call a function on the server from the client.
The client makes an HTTP request
The server constructs a response (HTML for this example)
The server delivers the response to the client
The client parses the HTML and executes any JS
By stage 4, the program generating the page will have terminated.
If you want something to happen on the server based on a client side script executing, then you need to make a new HTTP request. There are lots of ways you can do this:
Click a link (and include the data in the URI)
Submit a form
Set the src or an iframe
Use XMLHttpRequest (the most common form of Ajax)
Create an <img> and include the data in the src
etc