-1

I was trying to put variable into JSON. I want to post it using Ajax.

My code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var user_Details = "1528205024";

    function checkUserForDashboard(){
    $.ajax({
        url: "api comes here",
        type: "POST",
        data: {"user_id": user_details },
        dataType: "json",
        crossDomain : true,
        success: function (data) {
          console.log(data);
        }

    })};
</script>

The post request gives: bad request error.

1
  • I think the variable name is user_Details and not 'user_details'. Commented Dec 6, 2018 at 8:52

1 Answer 1

1

Enclose your JSON object into JSON.stringify() to ensure your json object is serialized in a safe string.

Also, set the content-type property.

$.ajax({
    url: "api comes here",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({"user_id": user_details }),
    dataType: "json",
    crossDomain : true,
    success: function (data) {
      console.log(data);
    }

})};
Sign up to request clarification or add additional context in comments.

7 Comments

"to avoid malicious code" — That won't help you avoid malicious code at all. It will make it JSON which is what the question is asking for.
@Quentin I edited my answer. However JSON.strigify() will output string representation of a real JSON object. It will not make it JSON.
It will make it JSON. The object you pass to JSON.stringify will be JavaScript, not JSON. The only JSON you can have in a programming language is a string representation because JSON is a text-based data format. Your last comment is akin to saying "get_name_from_database() will output a string representation of a real human name. It will not be a name.".
@Quentin I think you might be confusing JSON.stringy() with JSON.parse()
No, I'm not. JSON.parse takes JSON and outputs a JavaScript object (or array, or null, or number, or whatever the top level data type of the JSON is).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.