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?
Related
I need to send a mail with jsp, but the page itself mustn't reload. The whole implementation is working fine when reloading on the POST-event, but adjusting the code to work with ajax breaks it. It seems that the jsp-Code within the index.jsp is not executed, when the ajax event is triggerd.
I am gonna show some snippets:
index.jsp
<%
String result = "=(";
String to = request.getParameter("rec_mail");
if(to != null) {
String from = request.getParameter("sendermail");
String host = "mailserver";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session mailSession = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Feedback");
message.setText(request.getParameter("feedbackinput"));
Transport.send(message);
result = "Sucess!";
}catch (MessagingException e) {
e.printStackTrace();
result = "failed!";
}
}
out.println(request.getParameter("sendermail"));
out.println(result);
%>
<input id="bsend" class="fbutton" type="submit" name="send" value="Send" onclick="loadContent()" style="float:right; width:18%; height:35%;" >
ajax.js
var xmlhttp
function loadContent() {
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support Ajax!");
return;
}
var url="./index.jsp";
xmlhttp.open("post",url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange=getOutput;
}
function getOutput()
{
if (xmlhttp.readyState==4)
{
alert("Message sent!");
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
(just showing the relevant parts, everywhere)
I get the alert-message, but no mail is sent ... I hope it is clear, what I am trying to do..
Thank you!
Best regards
Don't you also need to set a header for a HTTP Post
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
also, not sure if it will make a difference but I would make "post" to "POST".
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'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.
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.
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