kentor
kentor

Reputation: 18534

Ajax request sends numbers as string

I want to send different numbers as number and not as string via AJAX post. I am aware, that ajax requests / the http protocol is not type-safe and thus I created a JSON object, but on the serverside it's still received as string.

var node = $(this);
var id = parseInt(node.data("id"));
var isActive = node.is(':checked') ? 1 : 0;
var jsonParam = {Id: id, IsActive: isActive};

$.ajax({
  url: "/accounts/edit-account",
  type: "POST",
  data: jsonParam,
  dataType: "json",
  success: function (response)
  {

  },
  error: function (xhr) {
    alert("Error while updating the account");
  }
});

Returns:

{ Id: '102', IsActive: '1' }

Serversided code:

router.post('/edit-account', function(req, res) {
    console.log(req.body)
});

Upvotes: 0

Views: 933

Answers (2)

Patrick Roberts
Patrick Roberts

Reputation: 51916

Try specifying contentType: "application/json" in your AJAX. The dataType specifies what is expected from the response, not what's in the request.

Upvotes: 1

jmealy
jmealy

Reputation: 592

Just use parseInt on the returned string:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Upvotes: 0

Related Questions