I'm using php on a linux machine. My html code issues an ajax request to the local apache server (http://localhost), and the data from the server should be printed out on the screen. However, nothing gets printed.
The code on the "client" side (the html file which I load in the browser) is:
<html>
<body>
<script language="javascript" type="text/javascript">
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;
}
}
}
ajaxRequest.onreadystatechange = function(){
if( ajaxRequest.readyState == 4 ){
document.writeln( ajaxRequest.responseText );
}
}
ajaxRequest.open("GET", "http://localhost/s.php", true);
ajaxRequest.send(null);
}
</script>
</body>
</html>
and the "server" script (which is /var/www/s.php) is:
<html>
<body>
<?php
echo date("H:i:s");
?>
</body>
</html>
Any suggestions?
TIA
You should debug your code
Check Apache access log that s.php was loaded
If it loaded then add debug alert function to onreadystatechange callback function
If this function is called then check what return code it received: alert(ajaxRequest.readyState);
If code is 4 then check what content it returned: alert(ajaxRequest.responseText);
There doesn't seem to be anything calling ajaxFunction when the page loads, so the request is never sent.
Related
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 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.
I wrote a cgi-script with c++ to return the query-string back to the requesting ajax object.
I also write the query-string in a file in order to see if the cgi script works correctly.
But when I ask in the html document for the response Text to be shown in a messagebox i get a blank message.
here is my code:
js:
<script type = "text/javascript">
var XMLHttp;
if(navigator.appName == "Microsoft Internet Explorer") {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
XMLHttp = new XMLHttpRequest();
}
function getresponse () {
XMLHttp.open
("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
XMLHttp.send(null);
}
XMLHttp.onreadystatechange=function(){
if(XMLHttp.readyState == 4)
{
document.getElementById('response_area').innerHTML += XMLHttp.readyState;
var x= XMLHttp.responseText
alert(x)
}
}
</script>
First Names(s)<input onkeydown = "javascript: getresponse ()"
id="fname" name="name"> <br>
Surname<input onkeydown = "javascript: getresponse();" id="sname">
<div id = "response_area">
</div>
C++:
int main() {
QFile log("log.txt");
if(!log.open(QIODevice::WriteOnly | QIODevice::Text))
{
return 1;
}
QTextStream outLog(&log);
QString QUERY_STRING= getenv("QUERY_STRING");
//if(QUERY_STRING!=NULL)
//{
cout<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<< QUERY_STRING.toStdString()<< "\n";
outLog<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<<QUERY_STRING<<endl;
//}
return 0;
}
I'm happy about every advice what to do!
EDIT: the output to my logfile works just fine:
Content-type: text/plain
The Query String is: fname=hello&sname=world
I just noticed that if i open it with IE8 i get the query-string. But only on the first "keydown" after that IE does nothing.
You don't have to use javascript: in on___ handler, just onkeydown="getresponse();" is enough;
IE>=7 supports XMLHttpRequest object, so directly checking if XMLHttpRequest exists is better than checking whether navigator is IE. Example:
if(XMLHttpRequest) XMLHttp=new XMLHttpRequest();
else if(window.ActiveXObject) XMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
inside your getresponse() function, try to add below code at the beginning (before open):
try{XMLHTTP.abort();}catch(e){}
Because you're using a global object, you may want to "close" it before opening another connection.
Edit:
Some browser (maybe Firefox itself?) do not handle non-"text/xml" response very well in default state, so to ensure things and stuffs, try this:
function getresponse () {
try{XMLHttp.abort();}catch(e){}
XMLHttp.open("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
if(XMLHttp.overrideMimeType) XMLHttp.overrideMimeType("text/plain");
XMLHttp.send(null);
}
My problem had nothing to do with the code...
I was testing my script on the local IIS7 and I opened the html-page with double-clicking on the file. But you have to open the webpage via browser (localhost/mypage.htm) because otherwise for the browser the html and the executable have different origins. which is not allowed.
I'm trying to pass a variable to a javascript function, but I'm not sure what's going on as I am primarily a PHP person.
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction( str){
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.getElementById("emailconfirm").innerHTML= ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "Atest.php?Email="+str, true);
ajaxRequest.send(null);
}
//-->
</script>
the form
<form name='myForm'>
<input name="email" id="email"type="text" />
<input name="button" onclick="ajaxFunction(document.getElementById('email').value" type="button" />
</form>
I wanna be able once the button get clicked, the email text input will be passed to the javascript function.
You're almost perfect, just a few things:
You missed a ) in your onclick event. Just add it to the end and it should work.
You don't need all that try..catch stuff, unless you need to support Internet Explorer 6, so you can just get rid of it and leave ajaxRequest = new XMLHttpRequest().
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