2

i am trying to pass a variable from jQuery to nodejs, but i am not getting the right results, nodejs returns [object Object]. how can it return a string variable on nodejs side.

  $('.test').click(function(){
      var tsId = "Hello World";
      alert(tsId);
      console.log(tsId);
      $.ajax({
        'type': 'post',
        'data':tsId,
        'url': '/test/testing',
        'success': function (data) {
            alert(data);
        }
      })
    });


 router.post('/testing', function(req, res) {

   var tsID = req.body;
   console.log("stsID "+tsID );\\ outputs [object Object]

 });

2 Answers 2

1

I recommend you to use this way:

You should pass an object in ajax data, which contains your Hello World string.

$.ajax({
    type: 'post',
    data:{str:tsId},
    url: '/test/testing',
    success: function (data) {
        alert(data);
    }
 });

In node.js file use this:

 router.post('/testing', function(req, res) {
    var tsID = req.body;
    console.log("stsID "+tsID.str );
 });
Sign up to request clarification or add additional context in comments.

5 Comments

outputs: {"Hello World":""} its key value
What do you receive in console when you try console.log("stsID "+tsID ); ?
[object Object]
@KarishKarish, I updated my answer. Please take a look.
Do you need express server to be running? @Mihai Alexandru-Ionut
0

Try console logging tsID.data or tsID.tsId. What do you get? What do you get if you throw a debugger before your console log and write "tsID" in the console?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.