Ajax request to GAE not working? - javascript

I have a GAE app which accepts JSON requests and replies with JSON in the response. I know it works as I have an Android app that works with it. I'm trying to set up a JavaScript browser based interface as well. To do this I'm trying to send a request via JQuery from a page hosted on a different GAE domain. However, as far as I can see the ajax is not sent at all.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
alert("before ajax.....");
$.ajax({
type: "POST",
url: "CORRECT URL HERE",
data: {
type:"GAMES_LIST"
},
jsonpCallback: function(){
alert("success");
},
async: false,
crossDomain : true,
dataType: 'jsonp'
});
alert("after ajax...");
}
</script>
</head>
<body onLoad="loadXMLDoc()">
<div id="myDiv"></div>
</body>
</html>
Only the first 'before ajax' alert is fired.
Has anyone got an idea what I'm doing wrong?

By making an AJAX request to a different domain, you are violating the Same-origin policy.
If you have access to the JSON endpoint, you can allow specific domains to access your endpoint in the Access-Control-Allow-Origin HTTP header.
If you don't have access to the endpoint e.g. it's a third-party provider, you can make a JSONP request if the provider supports it.

Related

Basic Auth through Ajax for accessing a page secured with https without entering Username and Password in dialog box

I need to access and display a website page hosted on this url - https://xxxxx.com , without any authentication dialog box from my applicattion hosted in the same network.But i am not able to bye - pass the dialog box to enter username and password.
I used Basic Auth for Authorization and it works fine with Postman.I get a successful response in Postman by supplying the Basic Auth value in header as Authorization.The same encrypted value for Basic Auth, i used in Springboot code to fetch some details from that page and it works fine too.
But when i tried to navigate/display this page using tag and Javascript , after setting the required headers for Basic Auth, i am getting the error response and unauthorized - 401 with message -
WWW-Authenticate: Basic realm="Please sign in with your Office email userid (without the #xxx.xx)"
I tried different ajax combinations but not getting 200 code ,and it always ask to enter dialog box asking me to enter username and password.Otherwise ends up in 401.
Below is the code used.
function handleSubmit(e){
$.ajax({
url: 'https://xxxxxx.com/se/',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type':'application/json',
},
type: 'GET',
dataType: 'json',
async: false,
data: '',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic cmlqdS5mcmFuY2lzOkN1cmlwczIxxxxxxxx==");
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
},
success: function(){
alert('succes: ');
}
});
}
This is my form in HTML -
This is my basic code for Ajaxrequests. I use this to request a secured Dir on my Webspace. As URL i use a CORS Proxy with just to bypass Problems with CORS and get AuthAccess working.
Maybe you can try this for your application. If you get it to work without 401 Error and without asking for Login, you can work on adding CORS Header without using CORS Proxy URL.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function ajax() {
user = "test"; // Insert your
pass = "test"; // real Login here
$.ajax({
url : "https://--insert-a-cors-proxy-here--.com/https://youdomain.here/secured/index.php",
type : "get",
cache : false,
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(user+":"+pass));
},
success : function (result) {
$("#result").html(result);
},
"error": function() { $('#errorbox').html('Oh noo, Error!'); }
});
}
</script>
</head>
<body>
<input type="button" value="Request with Ajax!" onclick="ajax();">
<div id="errorbox" style="background-color:red"> </div>
<div id="result" style="background-color:yellow"> </div>
</body>
</html>
This is working fine after i modified to history.pushState({}, null, '/xxx.com') in my then function

create javascript file for use on different servers

I want to create a JS file that others can include on their websites so they can reference the functions which access my db using an api similar to the facebook like button which shows the total liked and who of your friends like the page. What I've been doing as part of my testing is the following:
JS file
function getItemRating(id){
var result = "";
$.ajax({
type: "POST",
url: "http://siteurl.com/api/rating.php",
data: {i : id},
dataType: "json",
async: false,
success: function(data) { // callback for successful completion
result = data;
},
error: function() { // callback if there's an error
result = 'error';
}
});
return result;
}
Reference file includes:
header("Access-Control-Allow-Origin: *");
and on the other server I've tried a few ways including:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="www.siteurl.com/api/rating-file.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var result = getItemRating(1);
console.log(result);
});
</script>
</head>
<body></body>
</html>
But currently I'm getting the error in console:
VM133:1 Access to XMLHttpRequest at 'http://siteurl.com/api/rating.php' from origin 'http://otherurl.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
siteurl.com = my server where the js file (with function) is located
otherurl.com = different server that the html including the js is located
The error message tells you that the problem is with the response to the preflight request, but you shouldn't be triggering one in the first place.
Remove:
contentType: "application/json; charset=utf-8",
because:
It is a lie. You aren't POSTing JSON in your GET request.
Setting the content-type to that value triggers a preflight request.

Unable to parse the json from url

<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
async: false,
contentType: "application/json",
url: "http://www.XXX.XXX.in/api/categories",//url:"dir/categories",
dataType: "jsonp", //dataType: "jsonp",
success: function (data) {
$.each(data, function(i,data) {
var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
$(det).appendTo("#display");
//alert(det);
});
alert(data);
},
error: function (data) {
alert("this is error "+data);
}
});
});
</script>
<div id="display"></div>
</body>
</html>
In the above code I am trying to access the categories json and print the details.
I am doing it in two ways:
I have kept the categories file in dir/ folder and accessing it which shows me result properly.
When I try to access it online it gives me an error:
When I give dataType:"json" instead of jsonp I gives following error:
OPTIONS http:// XXX.XXX.in/api/categories 404 (Not Found)
XMLHttpRequest cannot load http:// XXX.XXX.in/api/categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost:8080' is therefore not allowed access.
I dont know whether the server has cross platform ref. added.
You can't access data of another domain from your domain using JAVASCRIPT. It is a security rule known as the "Same origin Policy"
So, to get data of another domain, you could write server side script (maybe in PHP or some other language you're familiar with.), then you can make ajax request from your script to the server.
The same origin policy is enforced by the browser to protect websites from other websites making xhr requests and displaying their content as if it was their own.
So site A.com cannot connect to B.com with XHR or:
http://A.com cannot connect to http://sub.A.com
localhost:80 cannot connect to localhhost:8080
Edit
As you requested, here is the solution using PHP script.
get_json_from_url.php
<?php
header("Content-type: text/json");
$response = fopen('http://www.eazydial.logicengine.in/api/categories', "rb");
echo stream_get_contents($response);
?>
HTML page
<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "get_json_from_url.php",
dataType: "json",
success: function (data) {
$.each(data, function(i,data) {
var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
$(det).appendTo("#display");
});
console.log(data); //alert can't print [object] so always use console.log() to inspect object and it values. (see output in browser console)
},
error: function (data) {
console.log("Err:");
console.log(data);
}
});
});
</script>
<div id="display"></div>
</body>
</html>
The solution provided here in PHP script will work only for GET request method. If you want to use POST request for any API then look for cURL library to get data from api.

Send a request to a route in Symfony2 using Javascript (AJAX)

I have a working prototype Symfony2 RESTful webservice which I am still working on and I am trying to figure out how a client can send JSON or consume JSON data from the webservice. All I need is an example(s) on how to send a request or post data to it and I can figure out the rest. From my browser, if I visit http://localhost/app_dev.php/users.json, I get the correct result from my database as JSON, e.g.
[{"id":1,"username":"paulo","username_canonical":"paulo","email":"a#ymail.com","email_canonical":"a#ymail.com","enabled":true,"salt":"66r01","password":"UCxSG2v5uddROA0Tbs3pHp7AZ3VMV","last_login":"2013-12-03T13:55:15-0500","locked":false,"expired":false,"roles":[],"credentials_expired":false,"first_name":"Monique","last_name":"Apple"}, ... etc.
All other routes are working correctly and I can get the same result by using httpie or cURL. Now, the problem I am trying to solve is to get the same JSON data using AJAX (and mobile iOS, Android, etc later). Here is my attempt at using AJAX JS:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$.ajax({
dataType: "json",
type: "GET",
url: "http://192.168.1.40/symfony/web/app_dev.php/users.json",
success: function (responseText)
{
alert("Request was successful, data received: " + responseText);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
</script>
The AJAX alerts the following results which indicates an error:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
What am I doing wrongly and how can I solve the problem. Kindly give an example.
This is a cross-domain request issue. You need to make the request to the same domain you are on. This is a browser-level security feature.
For example, you can only request URLs on http://192.168.1.40 if you are currently ON http://192.168.1.40. This means that a request from http://192.168.1.39 (for example) won't work

API call over jQuery

I'm trying to build a .js file that sends data to an external API, waits for a response and interprets the results. The external API is XML-based and accepts an HTTPS Post with the XML as body (content-type; text/xml). I can call the API correctly via cURL.
This is what I have so far:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body onload="CallService()">
<script type="text/javascript">
var webServiceURL = 'https://www.url.com';
var xmlString = '<xml><parameter1>value1</parameter1>
<parameter2>value2</parameter2></xml>';
function CallService() {
$.ajax({
url: webServiceURL,
type: "POST",
dataType: "xml",
data: xmlString,
processData: false,
contentType: "text/xml; charset=\"utf-8\"",
success: OnSuccess,
error: OnError
});
return false;
}
function OnSuccess(data, status) {
alert(data.d);
}
function OnError(request, status, error) {
alert('error');
}
$(document).ready(function() {
jQuery.support.cors = true;
});
</script>
</body>
</html>
When I open the HTML I get an alert saying "error" and nothing appears on the other end (the external API's). Is there a way to do this using just JavaScript/Ajax/jQuery or do I need a "supporting" code that receives the JS call?
When you want to make cross domain queries, you have basically 3 types of solution :
1) use JSONP, which won't interest you if you're using XML and not JSON
2) not really do cross-domain, by setting a kind of proxy (or any type of get) on the server serving the main html page
3) changing headers on the server to specify to the browser that you accept cross-domain queries. This is new but yet accepted by all major browsers. That's called CORS. It's easy to change the headers ("Access-control-...") in all server-side languages so that should now be the preferred way (if you have issues (security, rights, bandwidth, ad, etc.) with cross-domain access to the data you serve, you can restrain the allowed origins).

Categories

Resources