1

I am trying to create a "follow button" using jquery and node.js My front-end is like this:

<a id="author" href="#"><%= showPost.username %></a> //this displays a username
<p id="follower"><%= currentUser.username %></p> //this displays the current logged in username
<button style="width:100px;" type="button" id="fbtn">Follow</button>

jquery is like this:

$("#fbtn").click(function(){ 
    var fbtn = $('#fbtn');
    var follower_name=$('#follower').text();
    var followee_name = $('#author').text();
    fbtn.text('Unfollow');

        $.ajax({
            url: '/follow',
            method: 'POST',
            dataType: 'application/json',
            data:JSON.stringify({follower_name:follower_name,followee_name:followee_name}),
            success: function(data){ 
                console.log("success");
            console.log(data);
            }
        });
});

back-end is like this:

app.post("/follow", function(req, res){
    var followee = req.body.followee_name;

    console.log("Followed");
    console.log(followee);
    res.send("Worked!!!")
});

currently I am using console.log so that I can see if the data is passing or not. However, I am getting "undefined" in the console. I also got rid of req.body and I get the same log.

I am also getting this in the browser console:

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

After I get the data from jquery I will insert it to mySQL database. But I don't know how to pass the data to the back-end.

MG91
  • 193
  • 1
  • 11
  • https://stackoverflow.com/questions/5710358/how-to-retrieve-post-query-parameters – JJJ Feb 01 '18 at 01:01
  • @JJJ This is what I am currently doing, I am trying to use an ajax method here but it's still passing "undefined" for some reason. – MG91 Feb 01 '18 at 01:24
  • Did you use bodyparser package in your backend file?... – Rohit Kumar Feb 01 '18 at 01:45
  • Hi @RohitKumar I managed to pass the date, check my answer. I am currently getting a timeout error (504) for some reason even though the button is working fine. – MG91 Feb 01 '18 at 02:11

2 Answers2

1

I found my mistake I changed

data:JSON.stringify({follower_name:follower_name,followee_name:followee_name})

To:

data:{follower_name:follower_name,followee_name:followee_name}
MG91
  • 193
  • 1
  • 11
-1

Try to add quotation marks to the property keys of your JSON being passed to the backend.

alanfcm
  • 78
  • 3
  • I am not sure what you mean exactly? like this: data:JSON.stringify({,followee_name:"followee_name"}) isn't that going to pass it as a string? I tried it and it also shows as undefined? is there an npm package that I am missing? – MG91 Feb 01 '18 at 01:28