0

How do I send a variable from ajax call to mysql using node.js, so that query can be done using that variable and data send back to client

/* javascript code in .ejs file*/

<script type="text/javascript">
    $(document).ready(function(req, res){
        $('#empName').keyup(function(event){
            if (event.keyCode === 13){
                var empname = document.getElementById('empName').value;
                alert(empname);

                $.ajax({
                    url: "/autoFill",
                dataType: "json",
                type: "get",
              data: {empname: empname},
                success:  function(data){              
                    console.log(data);
                }
                }) 
            }
            });
        });

</script>

/* route code in index.js at server */

const autoFill = require('../controller/autocomplete1');
router.get('/autoFill', autoFill.autoFill);

/* mysql code in autocomplete1.js file */

module.exports.autoFill = function(req, res){

  var a = req.body.empname;
  var qa = `select lastName, gender, designation, emailID from empMasterData where firstName = "${a}"`;
      database.query(qa, function (err, results) {              
         if(err) throw err;
         var r = JSON.parse(JSON.stringify(results)); 
         console.log(results); 
         console.log(r);
            }
        )   
     };
6
  • Use type as a post for ajax request if you are going to read data from body in nodejs Commented Jun 10, 2020 at 9:52
  • used 'post' in place of 'get', but still variable (empname) is not being passed in mysql query Commented Jun 10, 2020 at 10:01
  • got it @NitinBhapkar thanks a lot Commented Jun 10, 2020 at 10:06
  • @NitinBhapkar Dear Nitin can you please suggest some tutorial for ajax calls for node.js Commented Jun 10, 2020 at 10:12
  • You can refer to JQuery documentation at api.jquery.com.For get method api.jquery.com/jQuery.get and for post api.jquery.com/jQuery.post. You can search other methods as from search options Commented Jun 10, 2020 at 11:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.