Ajax Request to AWS API Gateway can not parse json response - javascript

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',

Related

How to load <script src="...."> response into variable?

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.

Jquery ajax function returns wrong webpage

I have 2 local servers connected to a local switch. Ip adresses: 192.168.0.10 and 192.168.0.20. I am trying to get some data from the second one to the first using jquery Ajax as follows:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: "GET",
url: "192.168.0.20/d",
dataType: '',
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
window.alert(response);
}
});
});
});
</script>
</head>
<body>
<button id="get-button">Toggle</button>
</body>
</html>
When I put "192.168.0.20/d" in the browser url I get "data = xyz" as expected but using the method above I get that exact script back, its returning itself(192.168.0.10) instead of 192.168.0.20. How can I resolve this?
Thanks.
Edit.
The following gets rid of the Access-Control-Allow-Origin error but the returned data does not appear in the message box but it is present in developer mode.
$.ajax({
type: "GET",
crossDomain: true,
dataType: "JSONP",
url: "//192.168.0.20/d",
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
window.alert(response);
}
You need to alter your URL to:
url: "//192.168.0.20/d"
The way you've specified it now is as a relative URL. In other words it will assume that you want to make the request to the current domain, and that 192.168.0.20 is a subfolder of your website. You'd have the same problem if you created a hyperlink to it - it's not an ajax issue, it's the way browsers interpret URL fragments. This normally helps programmers when deploying the same site to multiple environments (e.g. dev, test, live) on different servers, so they don't have to replace all the URLs to point to a different place just because the deployed location changed. However in this case you're pointing to a resource on another server entirely, so that situation doesn't apply.
If you place the // before it, this indicates that it's an absolute URL (so always points to exactly the same place, no matter where the originating page is deployed) and that the first part following the slashes is a domain name or IP address.
(N.B. The // without http: or https: before it means that the browser will use the same protocol as the originating page is currently running under. So if your page is loaded via HTTP it'll make the ajax request via HTTP too, and if your page is loaded via HTTPS it'll make the ajax request via HTTPS. If that's not suitable for this scenario then you can add http: or https: at the beginning as appropriate.)
Look at https://jsfiddle.net/9uyuj96f/ (your code) and https://jsfiddle.net/9uyuj96f/1/ (fixed version) and watch the ajax request in the browser's network tools to see the difference.

Ajax request succeeds but result is empty

I am building a Google Chrome browser extension that uses $.ajax requests to send data from webpages to my server (currently hosted using localhost). The content_script.js file that is being executed in the context of the webpages (more on content scripts) that the extension has access to runs this code:
//note: encode64String is assigned earlier in the script...
$.ajax({
type: "POST",
url: "http://localhost:8888/quartzsite/uploadendpoint.php",
type: "jsonp",
data: {img: encode64String},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data){
console.log("The ajax request succeeded!");
console.log("The result is: ");
console.log(data);
},
error: function(){
console.log("The request failed");
}
});
The problem is that the Ajax request is succeeding but the data argument that it returns is empty...
The console looks like this after the code is run:
Currently the contents of the uploadedendpoint.php file are:
<?php
header("Access-Control-Allow-Origin: *");
echo 'This comes from php file'; die();
?>
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>
This means there should be at least something being returned in the data variable.
I have further confirmed that the request is succeeding because when I send the request to a broken url (i.e. uploaddddddendpoint.php) the code inside the $.ajax's error parameter is executed.
I have read similar questions like jQuery $.ajax response empty, but only in Chrome but to no avail...
UPDATE:
I have removed the invalid second type: "jsonp" parameter entirely and have added dataType: "text/html". I am now getting a failed ajax request each time the code is run.
UPDATE: Strangely changing dataType : "text/html" to dataType : "html" causes the ajax request to succeed but again with a blank data variable.
UPDATE: When using the dev toolkit to monitor the Network XHR these are the sent/response messages:
With regards to the flag of possible duplication to
Impossible to cross site ajax api calls in a chrome extension? I suggest otherwise! I have investigated that question and the problem does NOT seem to be the same.
Why do you have two type fields in your AJAX request? jsonp and POST.
$.ajax({
type: "POST", // OK
url: "http://localhost:8888/quartzsite/uploadendpoint.php",
type: "jsonp", // ???
// ...
});
UPDATE:
I think you should be using the relative path for the URL. Try changing your request to the following:
$.ajax({
type: "POST",
url: "/quartzsite/uploadendpoint.php",
dataType: "text/html",
data: {img: encode64String},
success: function(data){
console.log("The ajax request succeeded!");
console.log("The result is: ");
console.dir(data);
},
error: function(){
console.log("The request failed");
}
});
You can see I replaced the URL with /quartzsite/uploadendpoint.php. This may solve the problem... the absolute URL might signal a cross-domain request which is not what you're after.
Also, as a side note, it's unnecessary to set the contentType, since what you're setting it to is already the default value. If you were sending a JSON or XML, then you'd want to set the contentType.
Use "echo" instead of "return" while sending the response data to ajax.

Jquery unable to get the response from WCF REST service

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

Using the new facebook graph api, ajax calls returns null (empty)

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.

Categories