Allow click on the link after the script is completed

I am trying to find a way to allow the user to click on the link only after the completion of a specific function. So, here, in my case, I have an ejs template where there are two links in the paragraphs. Clicking on the first ("Running python") activates a script that takes some time to complete. Then, only after it finishes (which means "completed" - which comes from the line:) console.log('finished'printed on the console), the next link ("See Table") will be available for interactive viewing (or unhid or something in this kind).

<h1>Search for a movie</h1>

<form action="results" method="GET">
    <input type="text" placeholder="search term" name="search">
    <input type="submit">
</form>

<p><a href="/run"> Run python </a></p>
<p><a href="/data"> See the table </a></p>

Here is the app.js code

var express = require("express")
var app = express()
var request = require("request")
var PythonShell = require('python-shell');
app.set("view engine", "ejs")
app.engine('html', require('ejs').renderFile);

var thelist =[]

app.get("/", function(req, res){
    res.render("search")
})

var jsondata = ""


app.get("/results", function(req, res){
    var query = req.query.search
    var url = "http://www.omdbapi.com/?s=" + query + "&type=series&apikey=thewdb"

    request(url, function(error, response, body){
        if(!error && response.statusCode == 200){
            var data = JSON.parse(body)
            res.render("results", {data: data})
        }    
    })
})

app.get('/data', function(req, res) {
    //viewname can include or omit the filename extension
    res.render(__dirname + '/well.html'); 
});


app.get("/show/:id", function (req, res) {
    var id = req.params.id;
    thelist.push(id)
    console.log(thelist);
    res.redirect('/')
});

app.get("/run", function(req, res) {
            var pyshell = new PythonShell('script2.py');
            pyshell.send(JSON.stringify(thelist))
            pyshell.on('message', function (message) {
    // received a message sent from the Python script (a simple "print" statement)
            jsondata += message
            });

// end the input stream and allow the process to exit
            pyshell.end(function (err) {
             if (err){
               throw err;
                };

            console.log('finished');
            });
            res.redirect('/')
            thelist = []
});

app.listen(process.env.PORT, process.env.IP, function(){
    console.log("Movie App has started!!!");
})
+4
source share
5 answers

, ajax, , ejs, ?
( .html .ejs).

, , - res.redirect.
res.render , false.

:

server.js

// ...
app.get("/", function (req, res) {
  res.render("search", { active: false });
})

// ...
app.get("/run", function (req, res) {
  // ...
  pyshell.end(function (err) {
    if (err) throw err;
    console.log('finished');
    res.render("search", { active: true });
  });
});

search.ejs

<p><a href="/run">Run python</a></p>
<p>
  <%if (active) { %>
    <a href="/data">See the table</a>
  <% } else { %>
    See the table
  <% } %>
</p>

See the table , python script.

+3

, AJAX. , /run, JSON, / .

Run python AJAX /.

on OnSuccess AJAX, .

HTML

<p><a id="run" href="/run"> Run python </a></p>
<p><a id="show-data" href="/data" style="pointer-events:none;"> See the table </a></p>

Frontend Javascript

$(function() {
  $('#run').click(function(event) {
     event.preventDefault();
     $.get('/run', function() {
       $('#show-data').css('pointer-events', 'all');
     });
  });
});

NodeJs

app.get("/run", function(req, res) {
  ...
  // res.redirect('/');
  res.json({ success: true });
});
+3

U JQuery

 $("a").click(function() {
        if (status == "1") {
           return true;

        } else {
           return false;
           e.preventDefault();
        }
     });

, , .

I status = 0

, .

, 0, URL- , 1 , , true. , , e.preventDefault()

+1

socket.io? , ...

(Note: "msg" object, for example, for future reference only)

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Title</title>
</head>

<body>
  <h1>Search for a movie</h1>
  <p><a href="#" onclick="runPython()"> Run python </a></p>
  <p><a id="table-data"> See the table </a></p>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var msg = {
      msg: "TestMsgSend",
      iParam: 100,
      sParam: "Test Param 1",
      aParam: [1, 2, 3]
    }
    var socket = io();

    socket.on("server:finished", function (msg) {
      // msg = "TestMsgReceived", for further usage
      console.log("\nId: " + socket.id + "\nmsg: " + msg.msg + "\niParam: " + msg.iParam + "\nsParam: " + msg.sParam + "\naParam: " + msg.aParam);

      document.getElementById("table-data").setAttribute("href", "/data");
    });

    function runPython() {
      socket.emit("client:run", msg);
    }
  </script>
</body>
</html>

app.js

var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);

app.use("/", express.static(__dirname + "/"));

// ***************************************************************************
// ***************************************************************************
// ***** Your code
// ***************************************************************************
// ***************************************************************************

io.on("connection", function (socket) {
  console.log("New connection with id: " + socket.id);

  socket.on("client:run", function (msg) {
    // msg = "TestMsgSend", for further usage
    console.log("\nId: " + socket.id + "\nmsg: " + msg.msg + "\niParam: " + msg.iParam + "\nsParam: " + msg.sParam + "\naParam: " + msg.aParam);

    // ***************************************************************************
    // ***************************************************************************
    // ***** Your code
    // ***************************************************************************
    // ***************************************************************************

    msg.msg = "TestMsgReceived";
    msg.iParam++;
    msg.sParam = "Test Param 2";
    msg.aParam.push(4, 5, 6)
    io.emit("server:finished", msg);
  });
});

// ***************************************************************************
// ***************************************************************************
// ***** Your code
// ***************************************************************************
// ***************************************************************************

http.listen(80, function () {
  console.log("listening on *:80");
});

package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.2",
    "socket.io": "^2.0.4"
  }
}

Start with node app.js and enjoy

-1
source

Why not something like a simple protective variable? In your code:

var ready = false; // 1) the guard

app.get('/data', function(req, res) {
    if (ready) { // 2) view execution blocked until guard is ready
        res.render(__dirname + '/well.html');
    }
});

app.get("/run", function(req, res) {
    var pyshell = new PythonShell('script2.py');
    pyshell.send(JSON.stringify(thelist))
    pyshell.on('message', function (message) {
        // received a message sent from the Python script (a simple "print" statement)
        jsondata += message
    });

    // end the input stream and allow the process to exit
    pyshell.end(function (err) {
        if (err) {
            throw err;
        };
        ready = true; // 3) if evetything is OK the guard is now ready
        console.log('finished');
    });
    res.redirect('/')
    thelist = []
});
-1
source

Source: https://habr.com/ru/post/1688061/


All Articles