-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.

J.vee
  • 623
  • 1
  • 7
  • 26

1 Answers1

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);
    }

})};
Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • 1
    "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 Dec 06 '18 at 08:39
  • @Quentin I edited my answer. However JSON.strigify() will output string representation of a real JSON object. It will not make it JSON. – Ahmad Dec 06 '18 at 08:56
  • 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 Dec 06 '18 at 08:59
  • @Quentin I think you might be confusing JSON.stringy() with JSON.parse() – Ahmad Dec 06 '18 at 09:05
  • 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). – Quentin Dec 06 '18 at 09:06
  • @Quentin [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) also [w3schols](https://www.w3schools.com/js/js_json_stringify.asp) – Ahmad Dec 06 '18 at 09:14
  • @Ahman - They agree with me. MDN says "a JSON string" not "A string representation of JSON that is not JSON" – Quentin Dec 06 '18 at 09:16