0

I am trying to post some data via ajax to our backend API, but the arrays within the json data get turned into weird things by jquery...for example, the backend (python) sees the jquery ajax data as a dict of two lists

{'subject': ['something'], 'members[]': ['joe','bob']} 

when it should be

{'subject':'something','members':['joe','bob']}

The HTML Form extracted from a react component:

  <div class="the_form">
    <form onSubmit={this.handleSubmit}>
      <input type="textarea" ref="members" placeholder="spongebob, patrick" />
      <input type="submit" value="Add Thread" />
    </form>
  </div>

The jquery ajax code:

$.ajax({
        beforeSend: function(xhr, settings) {
            // csrf validation
        },
        url: this.props.url,
        dataType: 'json',
        type: 'POST',
        data: {subject: "something", members: ["joe","bob"]},
        success: function(data) {
          this.setState({data: data});
        }.bind(this),
        error: function(xhr, status, err) {
          console.log(this.props.url, status, err.toString());
        }.bind(this)
});

I am able, however, to make such a request appropriately with httpie (simple http command line client):

echo '{"subject":"something", "members":["joe","bob"]}' | http  --auth test:test POST localhost:8000/api/some_page/ --verbose

What might I be doing wrong in the javascript request such that the inputs come into the server differently than expected?

5
  • "What might I be doing wrong" I don't know, why don't you show us your code instead of making us guess? Commented Oct 26, 2015 at 7:25
  • Post HTML structure for the form and how you make AJAX request. Commented Oct 26, 2015 at 7:27
  • Show your complete code which you are processing to get this output. Commented Oct 26, 2015 at 7:27
  • Make sure your content type header is application/json and you are not doing form post Commented Oct 26, 2015 at 7:31
  • hat tip @mecek: I needed contentType: 'application/json' Commented Oct 26, 2015 at 7:38

2 Answers 2

1

Try to stringify your object before calling your ajax function

JSON.stringify({subject: "something", members: ["joe","bob"]})

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

1 Comment

this was also needed, but I needed to add contentType: 'application/json' as well
1

Try this

data: {subject: "something", members: ["joe","bob"]},

Then in backend

request.POST.getlist('members[]')

IF you want to use application/json as contentType.Then try this

data: JSON.stringify({subject: "something", members: ["joe","bob"]}),
contentType: 'application/json; charset=utf-8',

In backend,

json.loads(request.body)['members']

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.