Ajax URL appears blocked by company firewall - javascript

I am working on an ajax function that loads another page as a way to get around iframe limitations on Shopify. My issue seems to be that the URL is blocked or headers stripped. Nothing too complex, everything worked as I needed it to by using the following:
function get_report() {
var params = {
type: "GET",
url: "https://example.com/mypage.php",
dataType: 'html',
success:function(html) {
$("#content_div").load("https://example.com/mypage.php");
},
error: function(XMLHttpRequest, textStatus) {
alert('Error : ' +XMLHttpRequest.response);
}
};
jQuery.ajax(params);
};
<button onclick="get_report()">Get</button>
<div id="content_div"></div>
This works through public networks with no problem. However, when my client uses it behind a company firewall it fails to load the page. Upon further inspection it appears that the site URL my php is hosted on cannot be loaded either (I cannot be there to physically confirm). Here is a sample of that page if its relevant:
<?php
$allowedOrigins = [
"https://myexample.com",
"https://myexample2.com"
];
if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$origin = $_SERVER['HTTP_ORIGIN'];
} else if (array_key_exists('HTTP_REFERER', $_SERVER)) {
$origin = $_SERVER['HTTP_REFERER'];
} else {
$origin = $_SERVER['REMOTE_ADDR'];
}
if (in_array($origin, $allowedOrigins)) {
header("Access-Control-Allow-Origin: " .$origin);
}
setcookie('cross-site-cookie', 'name', ['samesite' => 'None', 'secure' => true]);
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TEST ALT IFRAME</title>
</head>
<body>
<div><?php echo "IT WORKS"; ?></div>
</body>
</html>
What I know:
-Walked client through accessing chrome console, zero errors listed
-URL never loads when client tries to load it via browser
-Ajax never gives an error response
-Webmaster/IT team is unreachable (I have tried to contact them for at least 4 months)
What I've tried:
-Recently adding meta tags and !DOCTYPE (just in case)
-Validating both the iframe site and URL site with W3C
-Confirming both the iframe site and URL site work with VPN and public networks
-Checking for correct categorization on major network filtering groups (semantics, paleo-alto, etc) and set to 'SAFE'.
My Question:
-How do I find out if the URL is blocked or the ajax request is being stripped?
-If the network is filtering my ajax URL am I at a dead end or is there another option?

How do I find out if the URL is blocked or the ajax request is being stripped?
If there's a network error, you can respond to it in the error callback you pass to the AJAX call:
function get_report() {
var params = {
type: "GET",
url: "https://example.com/mypage.php",
dataType: 'html',
success:function(html) {
$("#content_div").load("https://example.com/mypage.php");
},
error: function(XMLHttpRequest, textStatus) {
// inspect XMLHttpRequest to determine if network error occurred
alert('Error : ' +XMLHttpRequest.response);
}
};
jQuery.ajax(params);
};
If the network is filtering my ajax URL am I at a dead end or is there another option?
You're sort of at a dead end at the application level, unless you're willing to do something really convoluted like have a third party service, that you know will not have firewall restrictions, request the page, and then forward it to a service that is accessible from behind that firewall. So the short answer is, no, not really (at least not practically)

Related

Checking if a URL exists or not in Client Side Code

My objective is to check whether a URL is valid or not from client side. I tried the following things:
1. Tried using a ajax request using dataType as JSON. - Got the Cross-Origin Request Blocked error.
2. Tried using the JSONP as datatype. - Worked fine for some websites like google.com but it cribed for others like facebook.com
Got the error like "Refused to execute script from
FaceBook
callback=jQuery32107833494968122849_1505110738710&_=1505110738711'
because its MIME type
('text/html') is not executable, and strict MIME type checking is enabled."
Is there any workaround for this. I just want to make sure that the URL is valid irrespective of the content in the response.
Following is the code I wrote:
<html>
<body>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
function CallPageMethod() {
$.ajax({
type: "GET",
url: "https://www.google.com/",
dataType: "jsonp",
success: function (data, textStatus, xhr) {
alert("Success");
},
error: function (data, textStatus, xhr) {
if (data.status === 200) {
alert("Finally I am done")
} else {
alert("Error");
}
},
});
}
</script>
<Button onclick="CallPageMethod()">Test URL</Button>
</body>
</html>
Any Suggestions or any alternative approach that I should follow to resolve this issue?
Not properly, but Most sites have a favicon.ico either from the site directly or provided from the hosting company for the site if it is a 404 image.
<img src="https://www.google.com/favicon.ico"
onload="alert('icon loaded')">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"
onload="alert('ajax loaded')"></script>
Although iframe and object do have onload events, invalid pages also trigger the event.
This would be the fastest site test I can think of ...
var img = new Image();
img.onload = function () {
alert("image width is " + img.naturalWidth + " not zero so site is valid");
}
img.src = "https://www.google.com/favicon.ico";
As for facebook, the each page uses resources from another url, iframes are blocked as well as scripts. You would need to make the request from a server to test if a page existed.
You're best off writing a proxy on your server so:
Client hits your server with the URL you want to check
Your server makes the request to that URL and gets a response (or not)
Server returns status code to the client
This way will avoid the CORS issues you're having to navigate and will allow you to set any HTTP headers you need to.

Why does JavaScript alert display an empty string in Phonegap Android App while the code is working perfectly fine on browser?

I'm working on a simple PhoneGap application that communicates with a server that runs PHP, gets a string and displays it in JavaScript alert.
The App works perfectly fine on a browser. The JavaScript alert displays the string returned by the PHP code on the server. This action happens on click event of a button.
Here is the markup:
<!DOCTYPE html>
<html xml:lang="en" lang="en">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;">
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="jquery.min.js"></script>
<script src="cordova.js" charset="utf-8" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8" src="index.js"></script>
</head>
<body>
<h1>Hello World!</h1>
<button id="eventfire">Click</button>
</body>
</html>
JS code
$(document).ready(function(){
$("#eventfire").click(function(){
var data = {
"action": "test"
};
data=$.parseJSON('{ "name": "John" }');
$.ajax({
type: "POST",
dataType: "text",
url: "http://192.168.x.x/HelloWorldTest/response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
alert(data);
alert("type is " + typeof data + ". Length is " + data.length);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(xhr.responseText);
alert(xhr.status);
alert(thrownError);
},
statusCode: {
400: function () {
alert("Bad request!");
},
401: function() {
alert("Unauthorized!");
},
403: function() {
alert("Forbidden!");
},
404: function() {
alert("Page not found!");
},
408: function() {
alert("Request Timeout!");
},
200: function() {
alert("page reached");
},
}
});
});
})
PHP code
<?php
echo 'john';
?>
When I run this code on a AVD, the alert does not display the string. I have never seen such a alert getting displayed. The alert displayed inside the success function is shown below.
On inspecting this string, I understood that the length is 0.
I was able to reproduce the same issue on browser with a string of 0 characters length.
I'm not sure why the piece of code that is working fine when run on browser but acts weirdly on AVD. The string was getting displayed as expected on browser but not on AVD.
Find below the screenshots of the same code displaying the correct alert on browser.
I want to know the possible reasons of why the string from PHP is getting lost ?
I've never used PhoneGap but since your php file is stored on a different server than the files trying to call it, you will need to enable Cross-Origin Resource Sharing (CORS) (though I can't be sure this is the only issue)
Try adding Header set Access-Control-Allow-Origin "*" in your server's .htaccess file
By default, servers block access to resources like php files when the request comes from a file that is not stored on the same server.
For example, if I have a js file located at http://myfirstwebsite.com/awesome.js and in that file I make an ajax call to http://mysecondwebsite.com/loadstuff.php, the request will be blocked by the server and will produce the following error in the console:
XMLHttpRequest cannot load http://mysecondwebsite.com/loadstuff.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysecondwebsite.com' is therefore not allowed access.
I'm not sure if you can see this error in PhoneGap or where as I have never used it.
As the warning alludes to, in order to fix this, you must set the 'Access-Control-Allow-Origin' header to allow remote files to access the ones on your server.
Here is a tutorial explaining how to do that on Ubuntu
Just in case that link ever dies, here are the steps (copied right from that site)
Make sure you have the mod_headers Apache module installed. to do this check out /etc/apache2/mods-enabled/ and see if there’s a ‘headers.load’ in there. If there isn’t then just sudo ln -s /etc/apache2/mods-available/headers.load /etc/apache2/mods-enabled/headers.load
Add the Access-Control-Allow-Origin header to all HTTP responses. You can do this by adding the line Header set Access-Control-Allow-Origin "" to the desired section in your configuration file (like the /etc/apache2/sites-available/default file). Saying "" will allow cross-site XHR requests from anywhere. You can say "www.myothersite.com" to only accept requests from that origin.
Reload apache server. sudo /etc/init.d/apache2 reload

ajax GET - XMLHttpRequest cannot load

I'm trying to get data from a external api, but
I keep getting the error message:
XMLHttpRequest cannot load... No 'Access-Control-Allow-Origin' header is present on the requested resource.
here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
(function () {
$.support.cors = true;
$.ajax({
type: "GET", url: "http://zhettoapi.azurewebsites.net/api/Values?product=Coca Cola", success: function (data) {
window.alert("" + data);
//example of setting innerHTML of object
document.getElementById("myElement").innerHTML = "The number is:" + data;
}, error: function (xhr, status, error) {
// Display a generic error for now.
alert("Error: " + xhr + " " + status + " " + error);
}
});
})();
</script>
</head>
<body>
<div id="myElement"></div>
</body>
</html>
Since i can see that use have used azurewebsites mentioned in Get url ( "http://zhettoapi.**azurewebsites**.net/api/Values.... ), and i have some experience on that, i thought of solving your problem, even if this question was not tagged with Azure.
Assumption : You have used WebAPI.And deployed on Azure as website. ( i am sure, it is).
Since you are trying to access Azure Web API url from other domain in form of ajax.get request, it gets blocked because of cross domain ( CORS) security. So first thing here, is to make it(hosted WebAPI project) CORS enabled.
Steps to make it CORS enabled:
Install this - Install-Package Microsoft.AspNet.WebApi.Cors using NuGet
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.
Next, add the [EnableCors] attribute to the Controller class:
With following params
[EnableCors(origins: "http://zhettoapi.azurewebsites.net", headers: "", methods: "")]
Redeploy your WebAPI project.
SOURCE - http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
More links - http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En
Thanks!
Also this tutorial was helpful(describing):
http://www.codeguru.com/csharp/.net/net_asp/using-cross-origin-resource-sharing-cors-in-asp.net-web-api.html

jquery ajax readystate 0 responsetext status 0 statustext error

I am getting the following error: jquery ajax readystate 0 responsetext status 0 statustext error when giving it: url(http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm), however it's working fine when I give it url(localhost:""/embparse_page) on my localhost.
I have tried using the headers which I found on a Google search, and I have used beforeSend:"" too, but it's still not working.
I think the main problem is: XMLHttpRequest cannot load http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm. Origin "local server" is not allowed by Access-Control-Allow-Origin. but I don't understand it.
Can anyone please explain the problem to me, as I'm quite new to this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:ng="http://angularjs.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta Access-Control-Allow-Origin="*" />
<title>Page Parsing</title>
<script type="text/javascript" src="/js/jquery-1.9.1.min.js"></script>
<script>
getit=function(){
jQuery.support.cors = true;
$.ajax({
type:"GET",
url:"http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm",
dataType:"html",
crossDomain:true,
beforeSend: function(xhr) {
xhr.overrideMimeType('text/plain;charset=UTF-8');
},
success:function(XMLHttpRequest,jqXHR ,data) {
//alert(data.title);
var starttitl=data.lastIndexOf('<title>');
var endtitl=data.lastIndexOf('</title>');
var title1=data.substring(starttitl+7,endtitl);
alert(title1);
},
error:function(errorStatus,xhr) {
alert("Error"+JSON.stringify(errorStatus));
}
});
}
</script>
</head>
<body>
<div id="siteloader">
<input type="button" onclick="getit()" />
</div>
</body>
</html>
I was getting this error and in my case it was not due to same origin policy. I got some help from this link. Other possible reasons can be seen in here.
My case was, I had a link button and I was not using e.PreventDefault()
ASPX
<asp:LinkButton ID="lnkSearch" runat="server" CssClass="DockCmdSearch" CommandName="Search" OnClientClick="return VerifySearch(this, event);" />
Javascript
function VerifySearch(sender, e) {
e.preventDefault();
$.ajax({
type: 'POST',
.............
}
return false;
}
same origin policy. the browser does not allow when you're on
http://site1.com
to connect to:
site2.com
sub.site1.com
site1:99.com
https://site1.com (not sure about this one)
This is so site1 cannot steal content from site2 and pretend it's the content of site1. Ways around this is JSONP (google maps use that I think) and having site2 provide cors headers but cors are not supported in jQuery 1.* (maybe not in 2.* either) because IE has some problems implementing it. In both situations you need site2 to cooperate with your site so your site can display it's content.
If you only use this yourself then you can use Firefox and install the forcecors plugin. To activate you can choose view => toolbars => add on bar and click on the text "cors" in the right bottom of the screen.
I was getting that error from my Ajax call, and what fixed it for me was just putting in the 'return false'.
I had same problem with Nginx ( server side ) and AngularJs ( User side )
as other developer said its Cors problem , here i just want to say how i solve my problem maybe some one use this approach ;)
first I added below lines to my Nginx config files( in linux -> /etc/nginx/sites-available/your domain) :
add_header Access-Control-Allow-Origin *;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
and with angularJs I send my request like this :
$http({
method: "POST",
data: { //params},
url: "//address",
headers: { //if its form data
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Cache-Control": "no-cache"
},
crossDomain: true,
contentType: false,
processData: false
}).then(function mySucces(response) {
alert(JSON.stringify(response));
}, function myError(response) {
alert("error");
});
I was testing reading a txt/XML file for json/xml data and got an error... the values read: Status[0] & readyState[0] and StatusText[error]; This was working successfully on Internet explorer but not on Chrome because the domain needed to be the same
This is what fixed it
Go to C:\WINDOWS\system32\drivers\etc\hosts
Put a name against your localhost app:
127.0.0.1 SampleSiteName.com
Now open the code in chrome as http://SampleSiteName.com/YourAjaxFileName.htm (if it opens, it means that you have entered a host name correctly)
go to your HTML file and give a relative address of the file which you are trying to read (if FileToBeRead.txt is in the same folder as YourAjaxFileName.htm, then just enter url: "/FileToBeRead.txt")
Now your code will work on Chrome as well.

How to check port availability in client-side JavaScript?

Is it possible to detect in JavaScript (in the browser) if a port is disabled by the firewall or router?
No, with pure javascript this is not possible (aside of making http requests to the specific ports, but those results mean little), what you can do however is check from the outside (in other words your server) whether the specific port is open. Another option would be to use a java applet or browser plugin which could do this for you if you really need it, in which case there are various open source tools which you could probably port if you have the necessary experience with those. Do note however that this isn't exactly user friendly. (Either way, it would be useful if you would describe the exact scenario where you need this, as there might be an altogether different solution.)
You can only see if the expected response is there or not.
One has to stay in the boundaries of HTTP when using javascript.
Of course you can send an Ajax request on whatever port of server and see if you get an error. If you want to check port for current machine then probably sending a request on "localhost:843" could help.
But the error could be of some other reasons and not necessarily firewall issue.
We need more information to help you out.
If you are flexible enough to use jQuery, then see this Answer by me. This will not only check the availability of port, but also whether a success response code 200 is coming from the remote (or any , I meant it supports cross-domain also) server. Also giving the solution here. I will be checking here for port 843.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.7.2-min.js"></script>
</head>
<body>
<script type"text/javascript">
var isAccessible = null;
function checkConnection() {
/*make sure you host a helloWorld HTML page in the following URL, so that requests are succeeded with 200 status code*/
var url = "http://yourserverIP:843/test/hello.html" ;
$.ajax({
url: url,
type: "get",
cache: false,
dataType: 'jsonp', // it is for supporting crossdomain
crossDomain : true,
asynchronous : false,
jsonpCallback: 'deadCode',
timeout : 1500, // set a timeout in milliseconds
complete : function(xhr, responseText, thrownError) {
if(xhr.status == "200") {
isAccessible = true;
success(); // yes response came, execute success()
}
else {
isAccessible = false;
failure(); // this will be executed after the request gets timed out due to blockage of ports/connections/IPs
}
}
});
}
$(document).ready( function() {
checkConnection(); // here I invoke the checking function
});
</script>
</body>
</html>

Categories

Resources