How to make action on node.js server after button click using jQuery AJAX

35,394

Solution 1

Your problem is here, you have forgotten the # for targeting element by id, so click would never be invoke.

$('#like').click(function(){
    $.post('/test');
});

Solution 2

It looks like you aren't selecting the input tag correctly. If you want to select a DOM element by ID, you'll want to use '#IDname' as your selector.

For this example, that means changing it to

...
$('#like').click(function(){
...

This also might not fix the error entirely: using a an input field with a type of "submit", you will likely have to do something like this:

...
$('#like').click(function(e){
    e.preventDefault();
...

to keep the default submit event on the input from "bubbling up."

Share:
35,394
kuba12
Author by

kuba12

Updated on May 25, 2020

Comments

  • kuba12
    kuba12 almost 4 years

    I have a problem. I want to make server do something after clicking on button. This is my HTML code:

        <input name="like" id="like" value="Like" type="submit" />
        <script>
            $('like').click(function(){
                $.post('/test')
            });
        </script>
    

    and this is my server-side code:

    app.post('/test', function (req, res) {
        console.log('works');
    });
    

    And it doesn't work.

    • Mritunjay
      Mritunjay almost 10 years
      it should be saying something ?
    • morkro
      morkro almost 10 years
      Well, what do you expect?
    • prava
      prava almost 10 years
      can it be $('#like').click(function(){ instead of $('like').click(function(){
    • kuba12
      kuba12 almost 10 years
      Thanks prava I missed # :D