0

So I'm trying to make a POST request using the jquery $.ajax. My problem is the data being sent is JSON. So i'm not sure exactly how to send it. I am using fiddler to record the HTTP request and this is what I got. {"code":200,"user":"34522","questions":[{"35":"139"},{"55":"215"},{"28":"110"},{"88":"349"},{"127":"500"},{"148":"578"},{"125":"492"},{"218":"859"},{"258":"1019"},{"219":"862"}],"time":60}. Under the webform of fiddler there is nothing there. enter image description here

Here is the code I came up with and the response back is Object {code: 500, error: "Invalid request"}

var request = $.ajax({
      url: "http://website/api/post/",
      type: "POST",
      data: { 
        code : 200,
        user : 34522,
        questions : '[{"35":"139"},{"55":"215"},{"28":"110"},{"88":"349"},{"127":"500"},{"148":"578"},{"125":"492"},{"218":"859"},{"258":"1019"},{"219":"862"}]',
        time : 60
      },
      dataType: "json"
    });

    request.done(function( msg ) {
      console.log(msg);
    });

    request.fail(function( jqXHR, textStatus ) {
      console.log( "Request failed: " + textStatus );
    });
1
  • 1
    It literally says in your image: "Content-Type is 'application/json'; this Inspector supports 'x-www-form-urlencoded' only." Commented Oct 14, 2013 at 1:24

2 Answers 2

1

Try using JSON.stringify on your post data like this:

var request = $.ajax({
  url: "http://website/api/post/",
  type: "POST",
  data: JSON.stringify({ 
    code : 200,
    user : 34522,
    questions : [{"35":"139"},{"55":"215"},{"28":"110"},{"88":"349"},{"127":"500"},{"148":"578"},{"125":"492"},{"218":"859"},{"258":"1019"},{"219":"862"}],
    time : 60
  }),
  dataType: "json"
});

JSON.stringify will convert the current javascript object into a JSON string for posting. Also note removing the apostrophes from around the questions array.

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

Comments

0

The dataType:json refers to the response I believe. So if the server response isn't valid json, you would see a 500 error.

Try to look at the 'network (chrome)' or 'net (firefoxl)' tab in firebug to inspect the response.

You could also try to change dataType:json to dataType:text

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.