Ajax request to server from html page doesn't work - javascript

I made a server on NodeJs using module Express. Now I want to implement a request from html page with $.ajax by clicking a button. I want to get data from server in json format or in text format, it doesnt matter, but it doesn't work. Why?
And plus why does ajax request reload the html page while it shouldn't?
Server part:
var express = require('express');
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var app = express();
var url = require("url");
app.get('/scrape', function (req, res) {
console.log("Someone made request");
url = 'http://spun.fkpkzs.ru/Level/Gorny';
request(url, function (error, response, html) {
if (!error) {
console.log("Inside request");
var $ = cheerio.load(html);
var date, waterlevel;
var json = {
time: "",
waterlevel: ""
};
json.time = $("#waterleveltable td.timestampvalue").first().text()
json.waterlevel = $("#waterleveltable td.value").first().text()
res.send(json);
console.log(json);
}
})
})
app.listen('8081')
console.log('Server started on port 8081');
exports = module.exports = app;
This is my hmlt request:
<form>
<!-- button for sending a request to server-->
<button id="button12">Scrape water height</button>
</form>
<div id="response21">
Print
<!-- div for displaying the response from server -->
</div>
<p id="p1">___!</p>
<script>
$(document).ready(function () {
$("#button12").click(function () {
console.log("Get sent.")
// Json request
$.get("http://localhost:8081/scrape", function (data)
{
console.log("Data recieved" + data);
$("#response21")
.append("Time: " + data.time)
.append("Waterlevel: " + data.waterlevel);
}, "json");
});
});

Because of the fact that your button is inside a form, the default action of clicking the button will be to load a new page. This is what causes the reload of your page.
The simplest thing you can do is a return false at the end of the click handler callback so that to prevent the reload of the page.

Related

Is there way to have Node redirect to a new page with JSON?

I'm trying to allow users to type a search query into a box on an index.html page and have it send them to a results.html page with results displayed.
Currently I have this working only on an index.html page where the old HTML is removed and replaced with the search results.
//Pertinent Node code:
app.get('/', function(req, res){
res.header("Access-Control-Allow-Origin", "*");
res.redirect('index.html');
});
// A search box in index.html calls the /search below
app.get('/search', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
const item_id = req.query.item_id;
var json = {};
var sql_query = "a SQL query";
var result = connection.query(sql_query, function(err, result, fields) {
if (err) throw err;
json["result"] = result;
console.log("Sent JSON to client");
res.send(JSON.stringify(json));
});
})
//Client-side:
function get() {
var search = document.getElementById("search").value;
// Validate input to prevent injections
var new_search = search.replace("<", "");
var validated = new_search.replace(">", "");
var url = host + "/search?search=" + validated;
fetch(url, {method : 'GET'})
.then(checkStatus)
.then(function(responseText) {
var json = JSON.parse(responseText);
displaySearchResults(json, search);
})
.catch(function(error) {
});
}
What I'm trying to do is similar to what you might see on Google where clicking search send you to a new page with a url like: "https://www.google.com/searchresults?query=bicycles" that displays a different HTML page from index.html (such as results.html) with the JSON from index.html being moved to and processed in results.html.
How can I make this happen?
Adding some details to what Brad kindly mentioned in comments.. The full solution is:
<form action="search.html" method="GET" name="search">
Then in the Javascript file for search.html, access the form data with:
var search = window.location.search;
If you need to get the "?search=" out of the data, instead use:
var search = window.location.search.replace("?search=", "");

jQuery get method not working properly with two parameters passed to request

I am trying to send firstname and lastname to an api request using jQuery get method. It works fine with only one parameter ie with only first name but does when I add lastname to the request.
It works fine if url ="http://localhost:5000/name?firstname="+h1;
but does not work if url = "http://localhost:5000/name?firstname="+h1+"&lastname="+h2; In later case, the desired output is displayed for a sec and then disappears and url changes to "http://localhost:5000/?", the function is called from "http://localhost:5000/"
Here is my javascript code:
<script type="text/javascript">
$(document).ready(function(){
$("#submitButton").click(function(e){
var h1 = $("#handle1").val();
var h2 = $("#handle2").val();
var u = "http://localhost:5000/name?firstname="+h1+"&lastname="+h2;
//works fine if u = var u = "http://localhost:5000/name?firstname="+h1; though lastname is displayed undefined in the output
alert(u);
$.get(u, function(data){
$('.result').html(data);
})
});
});
</script>
and here is my Express API code:
var express = require('express');
var app = express();
var path = require("path");
const PORT = process.env.PORT || 5000
app.listen(PORT, function(){
console.log('server running on port ' + PORT);
})
app.get('/name', function(req, res){
res.send("Full Name: "+ req.query.firstname + " " + req.query.lastname);
});
Your Ajax $.get request should look like the code snippet below. If the served HTML is also running via http://localhost:5000/ then you can completely omit the relative URL.
$.get('name', {'firstname': h1, 'lastname': h2}).done(function(data) {
$('.result').html(data);
});
The name in $.get corresponds to the route /name

Request Aborted | Stop ajax request

Server - node.js I send the file to the server with ajax request, the progress of the download is displayed. There is a button that stops this ajax request (xhr.abort ()). After pressing the "stop" button, the server crashes with request aborted. What to do?
app.post("/blog/add", function (req, res, next) {
//Проанализируем загрузку файла
var form = new multiparty.Form();
var wayImage = "/files/";
form.on('part', function (part) {
var path = './public/files/' + part.filename;
wayImage += part.filename;
var out = fs.createWriteStream(path);
part.pipe(out);
});
form.on('close', function () {
//Отправка ссылки на картинку
res.send(wayImage);
});
form.on('error', function () {
console.log('error');
});
form.parse(req);
});

Ajax with node.js

i know some persons asked this question before but i don't understand answers :/
I'm using node.js, and i realy want to use Ajax in it.
My code is :
var $ = require('jquery');
var http = require("http");
var ws = require("nodejs-websocket");
var fs = require("fs");
var colors = require('colors');
http.createServer(function (req, res) {
fs.createReadStream("index.php").pipe(res)
}).listen(8080)
// ###################################################################################################################################
// ########################################################## CLASSE SERVER ##########################################################
// ###################################################################################################################################
var tableauDeJoueur = new Array();
var server = ws.createServer(function (connection){
connection.nickname = null
connection.on("text", function (str){
if (connection.nickname === null){
connection.nickname = str;
console.log((connection.nickname+" arrive sur PixelWorld !").green);
}
else{
var code = str.substring(0,2);
var reste = str.substring(2,str.length);
switch(code){
case "01":
var coupe = reste.split("4H[m~Ft7");
var mail = coupe[0];
var mdp = coupe[1];
$.ajax({
url: "fonctionPHP/connection.php",
type: "POST",
data: {'mail': mail,'mdp': mdp},
async:false,
success: function(html){
if(html == "OK"){
console.log("oui");
}
else{
console.log("non");
}
}
});
break;
case "02":
break;
}
}
})
connection.on("close", function (){
console.log((connection.nickname+" a quitté PixelWorld !").red);
})
})
server.listen(8081)
function broadcast(str) {
server.connections.forEach(function (connection) {
connection.sendText(str)
})
}
My problem is at the line "$.ajax({".
The server notice me when a user is coming, it's ok. But when he send a message with a 01 code, node crash and say me :
$.ajax({
^
TypeError: Object function ( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
} has no method 'ajax'
at Connection.<anonymous> (/var/www/dhkuhnuhbnkiuh/app.js:46:8)
at Connection.EventEmitter.emit (events.js:95:17)
at Connection.processFrame (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:516:9)
at Connection.extractFrame (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:458:14)
at Connection.doRead (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:209:23)
at Socket.<anonymous> (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:52:8)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
Sorry if my English isn't good, I'm French and bad at English. :/
Thank you for your help :D
Doing a request from nodejs is fairly easy, dont have to use $.ajax at all. You can use the npm request module. $.ajax is built for firing requests from the browser. But if you 'really' want to use $.ajax on node, I think you can read through this question
First,we begin with understanding AJAX and Node.Ajax is a client-side xml-based technology that automatically updates contents of a web page, without the page having to reload. Node.js is a server-side scripting language.
To illustrate this clearly, we will create a client client.html file and a server server.js
Aside from having npm installed, we will install express middleware and some of it's dependencies that we are going to use.
npm install --save express body-parser body-parser-xml
Let's begin by writing our server.js file. This file is going to parse xml requests sent AJAX. After processing request body, server should then send response back to client.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
require('body-parser-xml')(bodyParser);
app.use(bodyParser.xml({
limit: '1MB',
XmlParseOptions: {
normalize: true,
normalizeTags: true,
explicitArray: false
}
}));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/" + "client.html");
});
app.post('/library', bodyParser.urlencoded({ extended: false }), function(req, res) {
console.log(req.body);
var title = req.body.book.title;
var author = req.body.book.author;
var year = req.body.book.year;
console.log(title + " " + author + " " + year);
//optional operations like database can be performed here
// we are sending a response mimicking a successfull search query
res.end("Book Found in library");
});
var server = app.listen(8080, function() {
var host = '127.0.0.1';
var port = server.address().port;
console.log("Server running at http://%s:%s\n", host, port);
});
Next, create client.html file. This file will have simple form that when submitted call on an AJAX function that in turn sends xml data to server.js then waits and process response
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function Search() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.getAllResponseHeaders();
xmlhttp.open('POST', 'http://127.0.0.1:8080/library', true);
console.log(document.getElementById('title').value);
console.log(document.getElementById('author').value);
var text = "<book>" +
"<title>" + document.getElementById('title').value + "</title>" +
"<author>" + document.getElementById('author').value + "</author>" +
"<year>" + document.getElementById('year').value + "</year>" +
"</book>";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
console.log("All ok. You hit the server");
}
}
};
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send(text);
}
</script>
</head>
<body>
<form name="" method="POST" action="">
Title:<input type="text" name="title" id="title">
Author:<input type="text" name="author" id="author">
Year:<input type="text" name="year" id="year"><br>
<br>
<input type="button" value="Search" onclick="Search()" />
</form>
</body>
</html>
Hope this guide helps in future. Thanks

How to get asp.net hidden fields values with node js?

I am trying to login in to a site with nodejs.
The site's asp.net login form has hidden fields:
__EVENTTARGET, __EVENTVALILDATION, __VIEWSTATE, __EVENTARGUMENT
I am trying the following code:
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0'; // Ignore 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' authorization error
var request = require('request');
var cheerio = require('cheerio');
function postback(url, callback) {
request.get(url, function onResponse(err, res, body) {
$ = cheerio.load(body);
var button = callback(err, $);
if (button) {
var form = {
//__EVENTTARGET: button.attr('form1').match(/['"]([^"^']+)/)[0], // TODO image buttons
__EVENTTARGET: button.attr('Button1'),
__VIEWSTATE: $('#__VIEWSTATE').val(),
__EVENTVALIDATION: $('#__EVENTVALIDATION').val(),
__EVENTARGUMENT: $('__EVENTARGUMENT').val(),
};
}
});
}
postback('https://example.com', function(err, $) {
var button=$('input[type="image"]');
return button
//console.log(err)
//console.log($)
})
It's not getting the values of __EVENTTARGET and __EVENTARGUMENT.
These fields may needs a button click.
How to click it with cheerio?

Categories

Resources