My html page is making the following call:
<html>
<script src="https://someURL.com/api/getData?api_key=xyz&%26format=json">
</html>
It returns the following response:
data: abc123-abc456-efg678-ertyui789
How do I extract the
abc123-abc456-efg678-ertyui789
part into a var, so I can use it in other calls?
(I tried jquery, but it fails with CORS error, this is the only way I could get the response from the server)
var url ='https://someURL.com/api/getData?api_key=xyz&%26format=json',
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
success:function(res){
console.log("success");
console.log(res.data);
});
You can't.
The <script> element is designed to load a script and run it. A JSON document is not a script.
JSONP is a script, but if the service doesn't provide data in that format, then you can't use it.
Since an API key is involved, it is very likely that the service provides no mechanism for direct client-side access to the data because that would require that you give your secret key to all your visitors.
Fetch the data server-side instead.
Further reading
Aside, data: abc123-abc456-efg678-ertyui789 isn't a valid JSON document anyway so you might need a custom parser and not a JSON parser.
Related
I am testing the code here:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_get
Here is the code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var processJSON = function(data, textStatus, xhr) {
alert(xhr.status);
}
// for whatever reason, the following URL is not working any more, so you won't be able to test it anymore.
var myURL='https://ckeqt3eoea.execute-api.us-east-1.amazonaws.com/pettest/test?name=223';
// var myURL="https://jsonplaceholder.typicode.com/users"
$("button").click(function(){
$.ajax({
url: myURL,
dataType: "json",
contentType: 'application/json',
success: processJSON
});
});
});
</script>
</head>
<body>
<button>Send Request</button>
</body>
</html>
As indicated in the code, I am trying to parse the response from this URL:
https://ckeqt3eoea.execute-api.us-east-1.amazonaws.com/pettest/test?name=223
And you can go to that URL directly and find out that the response from the AWS-API-Gateway is simply:
{
"cc":"dd",
"name":"ee"
}
I was able to use the above javascript to parse other json responses from other sources. But I am pulling my hair trying to parse the above response from AWS-API-Gateway.
if you uncomment the second line of var myURL, you will see that the code just really works for other URLs.
==========
In response to existing answers:
I tried both json and jsonp. Both worked for other URLs (including the one I commented). But neither works for the AWS Gateway API.
I also updated the code to use a named function. But again, it works for other URLs, but not for the AWS URL.
I tested it on Firefox and Safari.
It's the data type. You are telling jQuery to expect jsonp callback. What you are looking for is dataType: "json".
UPDATE
I just tested your code. Issue is that you don't have an OPTIONS method defined in your pettest/test resource. Using the API Gateway console, open the test resource (assume pettest is the stage and test is the resource), then use the "Actions" dropdown button to Enable CORS. This will automatically create the OPTIONS method and setup the required headers in your GET method.
Worked for me with your API. Probably doesn't matter, but instead of using 'resp' as the variable label, I used 'data'.
Also, calling a named function rather than embedding the function inline
function processJSON(data) {
alert(data.name);
}
dataType: "json",
contentType: 'application/json',
Trying to make a REST web service call using an ajax call. Whenever I try to run it, I receive the error, Interpreted as script but transferred with MIME type text/xml. Here's my code ("website" is actual website where web service is):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function testCall() {
var webMethod = "website";
var un = 'un'
var pw = 'pw'
var parameters = "username=un&password=pw&change_ticket_number=CRQ000000011334&restuser=TEMPESP&restpass=restpw";
$.ajax({
url: webMethod,
type: 'Post',
data: parameters,
crossDomain: true,
username: un,
password: pw,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
dataType: 'jsonp',
success: function(data) {
alert('Success: ' + data);
},
error: function(errorThrown){
alert('Try again ' + errorThrown);
}
});
}
I have been searching all over the web and this website for something like this but I haven't had any success.
I have initially had my dataType as "xml" as that's what the web services provdies but changed it to "jsonp" when I read about cross domain calls.
The parameters are what the web service is looking for. If I was to open an internet browser and put the url + parameters, it does show me the xml message.
I'm not sure how much control I have over the web service itself so my hope would be to figure out a way on how to translate this back to xml after jsonp successfully brings it over.
So the question remains, am I able to change my code in order to make this work, leaving the web service as is? If it's truly not possible, what needs to be done to the web service? Keeping in mind xml is being used.
Thank you for any help you can provide.
The JSONP data format is a JavaScript program consisting of a function call (to a function defined in the URL) with the requested data as the argument.
You are getting the error because you are making a JSONP request and getting XML.
Change the server so it returns JSONP or change the JavaScript so it expects XML (and also change the server so it gives your site permission to read the XML using CORS).
Recently i am learning json to create apps.I have a doubt in a Json , php based chat system .
In this , the code work fine for same origin policy.But for sending and receiving data from external url, it successfully sends data to external php.But not receiving any data from server.I search in internet to solve this problem , and found jsonp as alternative. I tried jsonp , but i m not sure if am correct because i am new to ajax itself.
Please don't mis understand my question.I want to load a index.html file from localhost , when i send request to external url (anysite.com/xx/ajax.php) .It process and returns the data back to index.html.But the problem is my data is sended finely and processed on the server but it doesn't return to remote file.But it works fine for same server.
$.tzPOST = function(action,data,callback)
{
$.post('http://anysite.com/xx/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('http://anysite.com/xx/ajax.php?action='+action,data,callback,'json');
}
please help me with a code.
You cant receive JSON from external web by JavaScript, because of the policy.
But you can do AJAX request on your PHP file and there you can get the JSON by file_get_content http://cz2.php.net/file_get_contents function.
For using(working) with jsonp, u can take ready solution jquery-jsonp
from GitHub.
Example of using (by you question):
$.tzGET = function(action,data,callback){
var url = 'http://anysite.com/xx/ajax.php?action='+action;
$.jsonp({
type: 'GET',
url: url,
callbackParameter: callback,
dataType: 'jsonp',
data: data,
timeout: 10000,
success: function(json){
alert('success')
},
error: function(){
alert('error')
}
});
I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});
Im trying out the new graph api for facebook. I'm trying to fetch some data using jquery ajax.
This is a sample of my javascript code, very basic...
var mUrl = 'https://graph.facebook.com/19292868552';
$.ajax({
url: mUrl,
dataType: 'json',
success: function(data, status) {
$('#test').html(data);
alert(data);
},
error: function(data, e1, e2) {
$('#hello').html(e1);
}
});
The url is to a page that does not need access tokens (try it using a browser), but the success function returns an empty object or null.
What am I doing wrong? Thankful for all help!
I have covered this and asked this question before. I made a quick tutorial which covers exactly this and explains it all.
In short:
JSON is not made for cross domain usage according to its same-origin policy. However the work around is to use JSONP which we can do in jQuery using the supported callback parameter in facebook's graph api. We can do so by adding the parameter onto your url like
https://graph.facebook.com/19292868552?callback=?
by using the callback=? jQuery automatically changes the ? to wrap the json in a function call which then allows jQuery to parse the data successfully.
Also try using $.getJSON method.
I was trying to do something similar, in testing I was able to get a working result which I saved on jsFiddle: http://jsfiddle.net/8R7J8/1/
Script:
var facebookGraphURL = 'https://graph.facebook.com/19292868552';
$.ajax({
url: facebookGraphURL,
dataType: 'json',
success: function(data, status) {
$( '#output' ).html('Username: ' + data.username);
},
error: function(data, e1, e2) {
$( '#output' ).html(e2);
}
})
HTML:
<html>
<body>
<div id="output">BorkBorkBork</div>
</body>
</html>
Hope that helps! :)
...The Graph API supports JSONP. Simply pass callback=methodname as an extra parameter and the returned content will be wrapped in a function call, allowing you to use a dynamically inserted script tag to grab that data.
http://forum.developers.facebook.com/viewtopic.php?pid=253084#p253084
You can't do cross-domain AJAX requests like that due to the same-origin policy. Instead, use Facebook's JavaScript SDK, which is based on a script tag.