okay so I am trying to make my html/javascript communicate with my nodes.js server.
what I am trying to do is post data to my nodes.js server then echo the result back into my html/javascript.
the communication is working as in node I have console.log for the postdata and I can see it via the running node console .
problem is I need javascript to wait for the node.js function to complete and then echo me the text produced by node back to the html page.
I just cannot get this to work heres my html/javascript
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html><head><title>Welcome To ....</title>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(msg){
for(i = 0; i < msg.length; i++) {
// something per item
var data = {}; //your own data
$.post("http://192.168.2.109:8111" + "?" + $.param({name: msg[i]}), data);
}
// the old code
document.getElementById("message").innerHTML = msg.join("
");
}
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body></html>
and here is my node script
var url = require('url')
var http = require('http')
var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});
if (queryData.name) {
// user told us their name in the GET request, ex: http://host:8000/?name=Tom
var basevalue = queryData.name;
var value = basevalue.split (":");
console.log(value[0]);
console.log(value[1]);
var exec = require('child_process').exec;
exec ("casperjs test.js " + value[0] + " " + value[1] + '\n',function(err, stdout, stderr) {
response.end(stdout);
});
} else {
response.end("Contact Admin - Not Working\n");
}
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8111);
can someone please show me and help me fix this thanks
IT is simple.
you need to call the alert in callback. so it will be executed when post request completed.
change your few lines as following
$.post("http://192.168.2.109:8111" + "?" + $.param({name: msg[i]}), function(data){
// data contains your response from server. now you can handle it as you want
});
Related
I have a site in javascript where I get information from a Rest API (JSON)
I would like to make this information available to my server (A node.js that I have created that connects to the database)
It is my first time working with web development; I would like to know how I make the connection between the two?
front end
<!DOCTYPE html>
<head>
<style>
.bodyFrame {
margin: 40px;
}
.headerLabel {
font-weight: bold;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="bodyFrame">
<h2 style="text-align:center;">WIDS JSON Retrieval Example</h2>
<button type="button" onclick="makeServiceCall()">Retrieve JSON Data</button>
<br /><br />
<label class="headerLabel">Programs</label>
<ul id="programUL"></ul>
<div>
<script>
function makeServiceCall() {
var url = "http://widsservicedev.yaharasoftware.com/WidsService/JSON/GetPortagePrograms/?apikey=104043F0-9C24-4957-879D-046868973CC4&callback";
$.getJSON(url, function (data) {
//var myArray = [];
//myArray[0] = data;
parseProgramData(data, url);
});
}
function parseProgramData(jsonData, url) {
$("#dataHeader").empty();
$("#dataHeader").append('<b>' + url + '</b>');
var programUL = document.getElementById("programUL");
for (var pgmIndex = 0; pgmIndex < jsonData.Programs.length; pgmIndex++) {
var pgmLi = document.createElement("li");
var program = jsonData.Programs[pgmIndex];
var programInfoRevision = program.ProgramInfoRevisions[0];
var numberTitle = programInfoRevision.ProgramNumber + " " + programInfoRevision.ProgramTitle;
pgmLi.appendChild(document.createTextNode(numberTitle));
programUL.appendChild(pgmLi);
var linebreak = document.createElement("br");
pgmLi.appendChild(linebreak);
var poLabel = document.createElement("label");
poLabel.appendChild(document.createTextNode("Program Outcomes"));
poLabel.classList.add("headerLabel");
pgmLi.appendChild(poLabel);
var pgmOutcomeUL = document.createElement("UL");
pgmLi.appendChild(pgmOutcomeUL);
for (var poIndex = 0; poIndex < program.ProgramOutcomes.length; poIndex++) {
var poLi = document.createElement("li");
poLi.appendChild(document.createTextNode(program.ProgramOutcomes[poIndex].Description));
pgmOutcomeUL.appendChild(poLi);
}
}
}
</script>
</body>
<footer>
</footer>
node.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
/* var config = { user: 'papercut', password: 'Portage.2018', server: 'devsqlcl2:1433', database: 'AgrM6', port: "1433", dialect:",ssql", dialectOptiond:"SQLEXPRESS" };*/
// connect to your database
sql.connect('mssql://xxx:xxxx#xxxx:1433/xxx', function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from dbo.balance_papercut', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () { console.log('Server is running..'); });
Thank you.
Well to make those data available to the server you basically have to sent a request to the server containing those data. Since you want to sent data to the server you most likely need to use a POST request. There are more informations here about how to send such a request.
On the server side you need to an endpoint listening for a post request. You can find a lot of information about how to do this on the server on google.
A simple way to accomplish connection between frontend and backend is to create api-endpoints. You have already done so with your app.get('/', function (req, res).
You can do a similar one for sending data to the server. The http method used to send data to the server is generally POST. You can read more about the http methods here:
https://restfulapi.net/http-methods/
A good guide I stumbled upon a few weeks ago are this one:
https://codeforgeek.com/2014/09/handle-get-post-request-express-4/
In this example it does exactly what you're trying to accomplish, by sending data from a script in a static html-file to an Express server.
Client code:
<body>
<input type=text id="input">
</body>
<script>
var connection = new WebSocket('ws://chat-mmnnww123.c9users.io');
/*AFTER CONNECTION*/
$('#input').change(function(){
connection.send(this.value);
$('#input').val("");
alert("DONE");
});
connection.onmessage = function(e){
alert(e.data);
};
</script>
This code just send message write in the input to the server website.
Server code:
var ws = require("nodejs-websocket");
var server = ws.createServer(function(conn){
console.log("New Connection");
//on text function
conn.on("text", function(str){
/*
I want to send this str to agent.html page
*/
conn.sendText("Message send : " + str.toUpperCase());
});
//closing the connection
conn.on("close", function(){
console.log("connection closed");
});
}).listen(process.env.PORT, process.env.IP);
This is the server code which SHOULD take the value in str and pass it to the agent.html page.
Now all I want is to take that str value and pass it to page agent.html that I haven't created yet. This page will help the agent to see the client message.
It should be instant and without refreshing the page.
Node.js - Javascript - HTML - XMLHttpRequest cannot load
Basically i have 2 scripts posted below one node.js and 1 javascript/html
i am posting data to my node.js file but i recieve this error and cannot see the result of the nodes.js on my html page.
XMLHttpRequest cannot load http://192.168.2.109:8111/?name=nknk. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.2.109:8111' is therefore not allowed access
Here is my Node.js file:
var url = require('url');
var http = require('http');
var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});
if (queryData.name) {
var basevalue = queryData.name;
var value = basevalue.split (":");
var exec = require('child_process').exec;
console.log(value[0]);
console.log(value[1]);
exec ("casperjs test.js " + value[0] + " " + value[1] + '\n',function(err, stdout, stderr) {
response.end(stdout);
});
} else {
response.end("Contact Admin - Not Working\n");
}
});
server.listen(1234);
here is my html/javascript:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html><head><title>Welcome To ....</title>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(msg){
for(i = 0; i < msg.length; i++) {
// something per item
var data = {}; //your own data
$.post("http://192.168.2.109:8111" + "?" + $.param({name: msg[i]}), data);
}
// the old code
document.getElementById("message").innerHTML = msg.join("
");
}
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body></html>
Can someone help me fix this so that i can get the result back to my html without this error
----edit
this is code i am trying i can still not see the response data from the node.js server
i need to see the response from the exec command that my node server runs i know this takes about 40 seconds to complete but i still do not see anything outputted to html
node.js
var url = require('url')
var http = require('http')
var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});
if (queryData.name) {
// user told us their name in the GET request, ex: http://host:8000/?name=Tom
var basevalue = queryData.name;
var value = basevalue.split (":");
console.log(value[0]);
console.log(value[1]);
var exec = require('child_process').exec;
exec ("casperjs test.js " + value[0] + " " + value[1] + '\n',function(err, stdout, stderr) {
response.end('_stdout(\'{"content": "blablabla"}\')');
});
} else {
response.end("Contact Admin - Not Working\n");
}
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8999);
~
javascript html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<html><head><title>Welcome To ....</title>
<script type="text/javascript">
function textareaToArray(t){
return t.value.split(/[\n\r]+/);
}
function showArray(msg){
for(i = 0; i < msg.length; i++) {
// something per item
// var data = {}; //your own data
//$.post("http://192.168.2.109:8121" + "?" + $.param({name: msg[i]}), data);
$.ajax({
url: 'http://192.168.2.109:8999' + '?' + $.param({name: msg[i]}),
dataType: "jsonp",
jsonpCallback: "_stdout",
cache: false,
timeout: 5000,
success: function(data) {
function doSomethingWithData(data) { $('#message').val(data.content); }
},
error: function(jqXHR, textStatus, errorThrown) {
handleError(data);
}
});
}
// the old code
document.getElementById("message").innerHTML = msg.join("
");
}
</script>
</head>
<body>
<h1> WELCOME TO .... </h1>
<form>
<textarea rows="10" cols="60" name="alpha"></textarea>
<br>
<input type="button" value="show array" onclick="showArray(textareaToArray(this.form.alpha ))">
</form>
<br>
<textarea id="message" rows="6" cols="60" name="message"></textarea>
</body></html>
Apparently, your web application is not hosted on the same host as your nodejs server, thus, you are violating the same origin policy.
You can use JSONP:
var http = require('http');
http.createServer(function (req, res) {
console.log('request received');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('_stdout(\'{"content": "blablabla"}\')');
}).listen(1234);
And your call:
$.ajax({
url: 'http://192.168.2.109:8111' + '?' + $.param({name: msg[i]}),
dataType: "jsonp",
jsonpCallback: "_stdout",
cache: false,
timeout: 5000,
success: function(data) {
doSomethingWithData(data);
},
error: function(jqXHR, textStatus, errorThrown) {
handleError(data);
}
});
This is Same Origin Policy (http://en.wikipedia.org/wiki/Same-origin_policy). Modify your response at the following way:
response.writeHead(200, {
"Content-Type": "text/plain",
"Access-Control-Allow-Origin":"*"
});
My solution is simple.Just require cors module inside the server script side.
Due to CORS(Cross Origin Resource Sharing),which is disabled unless enabled otherwise in most of the modern browser.
In node require cors module in the application and use it accordingly.
Ex:
var cors=require(‘cors’);
var app=express();
app.use(cors());
I want to make a RuneScape(an MMORPG Game) Name Checker. For this i am using an IRC bot. The URL i am using to check names is this- http://rscript.org/lookup.php?type=namecheck&name=
I am using javascript to take input and go to this url for checking names. The code i am using is this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
}
</script>
</head>
<body>
<input class="textBox" id="uname" type="text" maxlength="15" required/>
<input type="button" onclick="nameCheck()" value="Submit">
</body>
</html>
To proceed with this i need a code that could check the output of the final url created ie.
curl. If the output page looks like this:
START
NAMECHECK: NOTAVALIBLE
SUGGESTIONS: blah blah blah
END
Then the code should run the function nameNotAva(). And if the output is like this:
START
NAMECHECK: AVALIBLE
END
Then the code should run the function nameAva().
The question:
I just want that using javascript the output be evalutaled to check that if NAMECHECK: NOTAVAILABLE is a part of the output page or not. If yes then a function nameNotAva() should be run. Otherwise a function nameAva() should be run.
Dont know what language u are using, with jQuery u can do following things
You can load the response inside a div.
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
var output = $('#someDiv').load( curl ).html() // .html() will give you the output or what the page
if( output.contains('NAMECHECK: NOTAVALIBLE'){ nameNotAva(); }
}
You can use simple AJAX and get the response text ( may be with async false)
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
$.ajax({
url : curl,
type : 'GET' //or 'POST',
success : function( urlOutput ){
if( urlOutput .contains('NAMECHECK: NOTAVALIBLE'){
nameNotAva();
}
}
});
}
So I have this HTML file that tests the user's screen resolution, and plugins installed using Javascript. So when the user accesses the page it sees: (e.g.) Your current screen resolution is 1024x768 and you have the following plugins installed: Plug-in No.2- Java Deployment Toolkit 7.0.10.8 [Location: npdeployJava1.dll], Plug-in No.3- Java(TM) Platform SE 7 U1 [Location: npjp2.dll], Plug-in No.4- Microsoft Office 2003 [Location: NPOFFICE.DLL]... I also need to save this information in a file on the server. All users are having firefox or chrome. How do I do this using AJAX?
<html>
<body>
<script language="JavaScript1.2">
document.write("Your current resolution is "+screen.width+"*"+screen.height+"")
</script>
<BR><BR>
<SCRIPT LANGUAGE="JavaScript">
var num_of_plugins = navigator.plugins.length;
for (var i=0; i < num_of_plugins; i++) {
var list_number=i+1;
document.write("<font color=red>Plug-in No." + list_number + "- </font>"+navigator.plugins[i].name+" <br>[Location: " + navigator.plugins[i].filename + "]<p>");
}
</script>
</body>
</html>
Thanks
Without jQuery (raw JavaScript):
var data = "...";// this is your data that you want to pass to the server (could be json)
//next you would initiate a XMLHTTPRequest as following (could be more advanced):
var url = "get_data.php";//your url to the server side file that will receive the data.
var http = new XMLHttpRequest();
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", data.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);//check if the data was received successfully.
}
}
http.send(data);
Using jQuery:
$.ajax({
type: 'POST',
url: url,//url of receiver file on server
data: data, //your data
success: success, //callback when ajax request finishes
dataType: dataType //text/json...
});
I hope this helps :)
More info:
https://www.google.co.il/search?q=js+ajax+post&oq=js+ajax+post
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Do you know jQuery? It will be much easier with jQuery.
var data = "";
for (var i=0; i < num_of_plugins; i++) {
var list_number=i+1;
document.write("<font color=red>Plug-in No." + list_number + "- </font>"+navigator.plugins[i].name+" <br>[Location: " + navigator.plugins[i].filename + "]<p>");
data += "<font color=red>Plug-in No." + list_number + "- </font>"+navigator.plugins[i].name+" <br>[Location: " + navigator.plugins[i].filename + "]<p>";
}
$.post('savedata.php', {data=data}, function(){//Save complete});
Then in savedata.php you can write something like the following:
$data = $_POST['data'];
$f = fopen('file', 'w+');
fwrite(f, $data);
fclose($f);
Do a request from javascript to a page which runs server side code.
Send post request with ajax http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml to for example an apsx page. From aspx you could save it to a text file or database.