Amit Tiwary Amit Tiwary - 1 year ago 133
React JSX Question

Error in posting JSON form data to REST api using AJAX in React

I have made a simple SignUp page using React and want to send the form data to a rest api. I have included the react.min.js, react-dom.min.js and jquery.min.js .Here is my code:

<div id="container"></div>

<script type="text/babel">
var Signup = React.createClass({
render: function(){
return (<div>
<div><label>First Name</label><input type="text" ref="firstname" /></div>
<div><label>Middle Name</label><input type="text" ref="middlename" /></div>
<div><label>Last Name</label><input type="text" ref="lastname" /></div>
<div><label>Email ID</label><input type="email" ref="email" /></div>
<div><label>Email Type</label><input type="text" ref="emailtitle" /></div>

<div><label>Password</label><input type="password" ref="password" /></div>
<div><button onClick={this.submit}>Sign Up</button></div>
submit: function(e){
var formdata = {
"first_name" : this.refs.firstname.value,
"middle_name" : this.refs.middlename.value,
"last_name" : this.refs.lastname.value,
"email" :,
"email_title" : this.refs.emailtitle.value,
"password" : this.refs.password.value,

var jsondata = JSON.parse(formdata);
url: 'api-url',
type: 'POST',
dataType: 'JSON',
data: jsondata,

success: function(data){
error: function(xhr, resp, text) {
console.log(xhr, resp, text);


<Signup />,

When I try to execute this, the console throws this error:

react.min.js:14 Uncaught SyntaxError: Unexpected token o in JSON at
position 1
at JSON.parse ()
at t.submit (eval at (file:///media/amit/New%20Volume1/Project/js/browser.min.js:4:28103),
at Object.r (file:///media/amit/New%20Volume1/Project/js/react.min.js:14:18287)
at a (file:///media/amit/New%20Volume1/Project/js/react.min.js:12:23308)
at Object.u [as executeDispatchesInOrder] (file:///media/amit/New%20Volume1/Project/js/react.min.js:12:23523)
at p (file:///media/amit/New%20Volume1/Project/js/react.min.js:12:20011)
at f (file:///media/amit/New%20Volume1/Project/js/react.min.js:12:20137)
at Array.forEach (native)
at r (file:///media/amit/New%20Volume1/Project/js/react.min.js:16:3700)
at Object.processEventQueue (file:///media/amit/New%20Volume1/Project/js/react.min.js:12:21091)

I cant understand these errors. Also, for now I had used a "#" in place of the "api-url". Am I doing this the right way? Or is there some other approach? I am new to React, AJAX etc. Plaese help.

Answer Source

formdata is an object already, you shouldn't parse it. Try to remove this line:

var jsondata = JSON.parse(formdata);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download