Tan Ya
Tan Ya

Reputation: 29

How to return value from ajax post()?

I created a simple button that would call a javascript function.

<button type="submit" id="likebtn" onclick="likedpost(this)" data-postid="<%=blog._id%>" data-author="<%=user.username%>">Like</button>
                
<span id="likescounter"><%=blog.likes%></span>  

This is the javascript function below.

function likedpost(el){
var id = el.dataset.postid;
var author = el.dataset.author;
var request = $.ajax({
type: "POST",
url: "api/index/like",
data: {id: id, author:author},
async:false,
dataType:"html",
success: function(){
  findingnumberoflikes(data)//here I want to use the return data after post.
  console.log("action performed successfully")
}

});
}
function findingnumberoflikes(data)
 {
  console.log("the data returned is "+ data);
 }

on the server-side

 app.post('/api/index/like', (req,res)=>{
 // After updating the database , How can I return some value from here.
 });

Thanks!

Upvotes: 0

Views: 52

Answers (2)

Hamza Iftikhar
Hamza Iftikhar

Reputation: 582

The above solution is good for the client side. I assume you also want to know how you can send a response from the server.

Client-side:

success: function(data) {
    findingnumberoflikes(data);
    console.log("action performed successfully");
}

Server-side:

app.post('/api/index/like', (req,res)=>{
    // After updating the database , How can I return some value from here.
    // here is how you can send
    res.json({ data: "test data", success: true });
});

Upvotes: 1

Shiz
Shiz

Reputation: 693

your code:

    success: function(){
        findingnumberoflikes(data)//here I want to use the return data after post.
        console.log("action performed successfully")
    }

working solution:

    success: function(data){
        findingnumberoflikes(data);
        console.log("action performed successfully");
    }

additionally, I would recommend you to add this:

    error: function(e){
        console.log("Error occured: " + e);
    }

so your code would be look like this:

    success: function(data){
        findingnumberoflikes(data);
        console.log("action performed successfully");
    },
    error: function(e){
        console.log("Error occured: " + e);
    }

Upvotes: 0

Related Questions