1

I have a requirement to accept JSON String as input in one of the textfield such as input will be like ::

{"order":1}

On form submission i am trying to create request and send this input to http request

var body = ({"key" : input});

var request = {
                    method : 'POST',
                    url : '/xxx',
                    data : body,
                    headers : {
                        'Content-Type' : "application/json"
                    }
                };
                $http(request).success(function(response) {

                }).error(function(response) {

                });

but server responds with 400 Bad Request as the body input is formed such as

"key": "{"order":"1"}"

whether as the server expects the input such as
"key": {"order":"1"}

you can see that the " " at start and end of the json are extra appended as the type of the input is text, how can achieve the expected format as mentioned above or any better approach.
Please suggest.

2
  • I don't see key anywhere in your code. Your expected string is also malformed. Commented Mar 13, 2016 at 13:42
  • @MinusFour: Yes the key is representation for the actual key:value pair to be used, thanks i have updated the question. Commented Mar 13, 2016 at 13:58

2 Answers 2

2

I don't know where you get the variable 'input' but I'm assuming you are selecting it with jQuery somehow and then trying to get it's value by using val(). If that is the case, then what you are getting is a String and what you should be sending in the 'data' key in your ajax request should be a parsed JSON.

This should fix your problem:

data : JSON.parse(input)
Sign up to request clarification or add additional context in comments.

1 Comment

The input from user in text box is JSON, i think parse() would again try to parse the Json back to Json. Anyways, i will try this.
1

I don't know why input is a sting, but to overcome this, change data : input, to data : JSON.parse(input),

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.