-2

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");
        });
    });

1 Answers1

2

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.

papantonis
  • 115
  • 1
  • 6
  • Be wary; `return false;` and `event.preventDefault()` behave differently. See http://stackoverflow.com/questions/18971284/event-preventdefault-vs-return-false-no-jquery and http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false – Stephen P Oct 24 '16 at 22:55
  • Right @StephenP , `event.preventDefault()` would be more accurate in this case. – papantonis Oct 24 '16 at 22:59
  • Thanks, It helped :) – Egor Miloserdov Oct 24 '16 at 23:22