I'm trying to use an ajax request to connect, and gather data from, a PHP file. THe AJAX JS is on a different website than the PHP, just an FYI.
Here is the JS:
var quer;
try
{
quer = new XMLHttpRequest();//I'm running in safari, so this gets called.
}
catch (e)
{
try
{
quer = new ActiveXObject("Msxml2.XMLHttp");
}
catch (e)
{
try
{
quer = new ActiveXObject("Microsoft.XMLHttp");
}
catch (e)
{
return false;
}
}
}
quer.onreadystatechange = function(){
if (quer.readyState == 4)//Good to go.
{
var resp = quer.responseText;
alert(resp);
}
}
quer.open("POST", "(blanked URL for security reasons)", true);
quer.send(null);
Resp is always, and I mean ALWAYS blank. Can anyone offer any help?
THe AJAX JS is on a different website
than the PHP
There is your problem. You can't do an XMLHttp request from a different domain.
You can read more about the same origin policy.
You cannot make AJAX requests to scripts that reside on other domains. It is a violation of the same origin policy.
Related
I am using WHMCS billing system. WHMCS have an own affiliate program, but it does work only on a subdomain. Since billing should be on a different server, just in case.
So we made a script for this one because users want to use the main link, instead of subdomain link. Because then you are using subdomain my.xeovo.com instead of xeovo.com you are going straight to billing, and have no choice to look at the main site.
JavaScript takes "r" from the link. This is how referral links looks like (/?r=1)
function ref() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value; });
return vars;
}
function file_get_contents( url ) {
var req = null;
try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {
try { req = new XMLHttpRequest(); } catch(e) {}
}
}
if (req == null) throw new Error('XMLHttpRequest not supported');
req.open("GET", url, false);
req.send(null);
return req.responseText;
}
function start() {
var id = ref()["r"];
var nl = file_get_contents("https://my.xeovo.com/aff.php?aff=" + id);
console.log("REF ID:" + id);
$.get("https://my.xeovo.com/aff.php?aff=" + id, function( data ) {
$( ".resss" ).html( data );
console.log('ok');
});
}
window.onload=function(){
start();
}
The script works totally fine, but we are getting a small problem in FireFox. We tested on Chrome/Opera/IE and everything was fine.
If you open https://www.xeovo.com in FireFox and click on certificate you are going to get this
here is screenshot
So any idea how we can fix this? Thanks.
If you check the browser console (Tools > Web Developer > Web Console), it gives the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my.xeovo.com/aff.php?aff=undefined. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
According to this SO answer, it is a header to prevent others from using your resources, that answer have the solution:
In my.xeovo.com add the following line to your .htaccess:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
You might need to read more about this header to refine it to custom files, instead of everything.
Trying to implement the simplest server-client on my PC.
The argv part is because I'm debugging it in VS and it started as an application. It works as a standalone app and I want to make it a server. If I enter
http://localhost:8080/
in the browser I can see in the node.exe window that the server runs properly. But when I run the html with the script nothing happens (I get no response, although no error either, and the server doesn't get the request)
If anyone could help I would appreciate it.
Client:
<html>
<body>
<script type = "text/javascript">
<!--
//Browser Support Code
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
document.myForm.response.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "http://localhost:8080", true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
<button onclick="ajaxFunction()">request</button> <br />
<input type='text' name='response' />
</form>
</body>
</html>
Server:
var fs = require("fs"),
my_http = require("http"),
sys = require("sys");
my_http.createServer(function(request,response){
fs.readFile(process.argv[2], 'utf8', function(err, data) {
if (err) {
console.log("FILE READ ERROR: ", err);
process.exit();
}
response.writeHeader(200, {"Content-Type": "text/plain"});
response.write("message");
response.end();
});
}).listen(8080);
sys.puts("Server Running on 8080");
EDIT:
Well, I made some progress you could say, but I don't like not knowing what the problem is. I created a new TypeScript project in VS and put my ajaxFunction in it and the button\textbox as in the initial html file. Now the server does get the request but it doesn't seem to call the callback function onreadystatechange.
The new client code:
default.htm:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TypeScript HTML App</title>
<link rel="stylesheet" href="app.css" type="text/css" />
<script src="app.js"></script>
</head>
<body>
<h1>TypeScript HTML App</h1>
<div id="content"></div>
<button onclick="ajaxFunction()">request</button> <br />
<input type='text' name='response' />
</body>
</html>
app.ts: (it's in js though)
var response;
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
var response;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
response.innerHTML = "hi";
}
}
ajaxRequest.open("GET", "http://localhost:8080", true);
ajaxRequest.send(null);
}
window.onload = () => {
response = document.getElementById('content');
};
I am now getting a "Cancelled" network request in Chrome's dev tools.
New answer:
What do you get if you log some values out in your onreadystatechange handler?
ajaxRequest.onreadystatechange = function () {
console.log('ajaxRequest.readyState=', ajaxRequest.readyState, ajaxRequest.status);
if (ajaxRequest.readyState == 4) {
document.myForm.response.value = ajaxRequest.responseText;
}
}
Original answer:
There are a couple of possibilities that might be occurring.
Your ajaxRequest variable is local to the ajaxFunction() and might be getting garbage collected after the function is executed.
Try moving the ajaxRequest outside ajaxFunction() like this:
var ajaxRequest; // The variable that makes Ajax possible!
function ajaxFunction() {
... rest of your client code.
}
That way the variable will still be in scope after the function has been invoked.
Alternatively, you might be running into a cross-domain security issue if your client is running on a different domain to your server (e.g. http://localhost:8081/ vs http://localhost:8080/).
Can you check if the browser is actually making the request (i.e. check with the browser's development tools and not on the server)? There should be a 'network' tab in the development tools for whichever browser you are using.
Have a look at the documentation for CORS (Cross-Origin Resource Sharing) to get an idea of what might be happening.
Edit: Here's a nice overview of cross-domain security errors and how to address it in a standard Node.js server: http://bannockburn.io/2013/09/cross-origin-resource-sharing-cors-with-a-node-js-express-js-and-sencha-touch-app/
This answer shows how to add the headers in a Connect server:
How can I add CORS-Headers to a static connect server?
I have a small,simple application.Its on Tomcat 7.Testing on Firefox browser.
My html page resides in
%CATALINA_HOME%\webapps\examples\servlets.
So, I access my html page using the URL:
http://localhost:8080/examples/servlets/userinputs.html
My java servlet(calls a third party API and returns a text/html response) resides in %CATALINA_HOME%\webapps\examples\WEB-INF\classes.
I am using AJAX call in my js file to call this servlet via the URL:
http://localhost:8080/examples/servlets/servlet/challengetask
The responseText returned is empty.If I access the servlet from browser,I can see the response.
I did go through the same-domain policy and searched
the internet for similar problems.However, I am unable to figure out as to why the responseText is empty and what EXACTLY is the problem.
My AJAX call :
var request =false;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
}
}
if(request){
request.open("GET",url,true);
request.onreadystatechange = callBack;
request.setRequestHeader("Connection","Close");
request.setRequestHeader("Method","GET"+url+"HTTP/1.1");
request.send();
}
else {
alert("Sorry could not create an XMLHttpRequest");
}
}
function callBack(){
if(request.readyState == 4){
if(request.status == 200){
alert(request.responseText);
}
} }
P.S: Both the html and js are in the same folder.
Please help.
In your code there's unwanted curly bracket (see like in the and of my snippet), remove it.
Second thing is why are you using connection=close, remove it if you don't really need it.
if(request){
request.open("GET",url,true);
request.onreadystatechange = callBack;
request.setRequestHeader("Connection","Close");
request.setRequestHeader("Method","GET"+url+"HTTP/1.1");
request.send();
}
else {
alert("Sorry could not create an XMLHttpRequest");
}
}
Fixed it by replacing localhost with 127.0.0.1.
I am trying to consume the weather web service provided by wsf.cdyne.com/WeatherWS/Weather.asmx. I am sure that I can get a response in XML format by using the uri " 'http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=' + zipcode".
So what I want to do now is sending the uri above using XmlHttpRequest. I added some alerts to monitor the status. After open() the readyState is 1. After that I can't get any other response. If I remove the statement "xmlHttpRequest.onreadystatechange = processRequest;", I cannot see any response after send(). So I just hope someone can help me to check what is wrong.
<html>
<head>
<title>weather app</title>
</head>
<body>
<script language="JavaScript">
function httpGet()
{
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
if (xmlHttp.overrideMimeType)
xmlHttp.overrideMimeType('text/xml');
}
else if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
xmlHttp.open( "GET", "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityForecastByZIP?ZIP=85281", false );
alert("1 " +xmlHttp.readyState);
xmlHttpRequest.onreadystatechange = processRequest;
alert("2 " +xmlHttp.readyState);
xmlHttp.send();
alert("3 " +xmlHttp.readyState);
document.write(xmlHttp.responseText);
return xmlHttp.responseText;
}
httpGet();
</script>
</body>
</html>
As correctly stated by #robertklep this request is cross-domain. Browsers disallow cross-browser requests as a security measure so you don't hijack the user's sessions on their sites etc.
To get it to work you can create a proxy on the local site. If the site offers support to use JSONP cross-domain, you could use that.
For more information lookup some information on cross-domain policies or if they have some API docs, they may have information there on your problem too.
Does anyone know of a tutorial on how to read data from a server side file with JS? I cant seem to find any topics on this when I google it. I tried to use but it does not seem to work. I just want to read some data from a file to display on the page. Is this even possible?
var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
To achieve this, you would have to retrieve the file from the server using a method called AJAX.
I'd look into JavaScript libraries such as Mootools and jQuery. They make AJAX very simple use.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
<script type="text/javascript">
//This event is called when the DOM is fully loaded
window.addEvent("domready",function(){
//Creating a new AJAX request that will request 'test.csv' from the current directory
var csvRequest = new Request({
url:"test.csv",
onSuccess:function(response){
//The response text is available in the 'response' variable
//Set the value of the textarea with the id 'csvResponse' to the response
$("csvResponse").value = response;
}
}).send(); //Don't forget to send our request!
});
</script>
</head>
<body>
<textarea rows="5" cols="25" id="csvResponse"></textarea>
</body>
</html>
If you upload that to the directory that test.csv resides in on your webserver and load the page, you should see the contents of test.csv appear in the textarea defined.
You need to use AJAX. With jQuery library the code can look like this:
$.ajax({ url: "test.csv", success: function(file_content) {
console.log(file_content);
}
});
or if you don't want to use libraries use raw XMLHTTPRequest object (but you I has different names on different browsers
function xhr(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
} catch(e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
req = xhr();
req.open("GET", "test.cvs");
req.onreadystatechange = function() {
console.log(req.responseText);
};
req.send(null);
UPDATE 2017 there is new fetch api, you can use it like this:
fetch('test.csv').then(function(response) {
if (response.status !== 200) {
throw response.status;
}
return response.text();
}).then(function(file_content) {
console.log(file_content);
}).catch(function(status) {
console.log('Error ' + status);
});
the support is pretty good if you need to support browser that don't support fetch API you can use polyfill that github created