Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call REST API from javascript

I have a url which gives json data...

I want to hit that URL from javascript but I am getting this error :

character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature

Code :

function a(){
$.getJSON(url,function(data) { alert(data);});
}

full code :

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta>
<script language="JavaScript" type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>

function a(){
$.getJSON(url,function(data) { alert(data);});
}
</script>
</head>
<body>
<input type="text"/>
<input type="submit" value="search" onclick="a()"/>
</body>
</html>
like image 597
Rishi Avatar asked Jan 21 '13 06:01

Rishi


People also ask

Can I call API in JavaScript?

We'll create a request variable and assign a new XMLHttpRequest object to it. Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint. The request completes and we can access the data inside the onload function.

How does REST API work JavaScript?

A REST API is a way of easily accessing web services. When a RESTful API is called, the server will transfer to the client a representation of the state of the requested resource.


1 Answers

Your code seems correct.

Are you making a fully qualified URL call?

If you are making a fully qualified URL call, make sure of the following.

  1. You are calling the same domain(same server). You can not make a simple JSON call to another domain.
  2. If you want to use a cross domain call, you'll have to use JSONp

Update: This is not working since it is a cross domain call.

Work around for this

JavaScript

Create a function

function getMyData(data) {
    alert(data);
    //Do the magic with your data
}

Server side

On server end wrap your data inside function syntax

getMyData("Enter your data here");

JavaScript

Then create a script tag and add a link to your cross-domain page

 <script type="text/javascript"
         src="cross ref url">
 </script>

For reference: wikipedia

EDIT: Another option is Create a proxy on your domain. ie create a page in your domain which internally calls the cross-domain page and return the same data to your Ajax call.

like image 130
Wolf Avatar answered Sep 20 '22 15:09

Wolf