简体   繁体   中英

jquery .ajax post request to a ruby on rails server gives a JSON.parse error on the client

I have jquery code on the client side trying to communicate with the ruby on rails server. I am currently trying to make the login work via client.

Here is the jquery code that gets executed when the user clicks the submit button.

$.ajax({
        headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') },
        type:"POST",
        data: hash,
        url: 'http://0.0.0.0:3000/users/sign_in.json',
        success: function(data) { 
            alert('Success');
            alert(JSON.stringify(data));
        },
        error: function(data) { 
            alert('Failed!');
            alert(JSON.stringify(data));
        },
    });
});

I monitored the logs in the rails server and saw "Completed 200 OK in 387ms" which means that the server process went well and the response has been sent back to the client.

However, in the client instead of the success function, the error function runs and I get {"readyState":0,"responseText":"","status":0,"statusText":"error"}

Here is the code in the controller

def create
resource = User.find_by_email(params[:user][:email])
return invalid_login_attempt unless resource

if resource.valid_password?(params[:user][:password])
  sign_in(:user, resource)
  resource.ensure_authentication_token
  respond_to do |format|
    format.html { redirect_to user_courses_path(current_user), notice: 'You are logged in' }
    format.json { render :json=> { :auth_token=> current_user.authentication_token, :success=> true, :status=> :created }}
  end
  return
end
invalid_login_attempt

end

I tried using firebug and in the response tab of the POST request I saw

syntaxerror json.parse unexpected end of data

Which means the response sent from the server was not a proper hash. I tried doing the same post request using

curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d ' {"user":{"email":"asdf@jjpt.com","password":"password"}}'  http://0.0.0.0:3000/users/sign_in

to which I get the following response {"auth_token":"zk1dyduMAo283mxP5o1m","success":true,"status":"created"}

So, the curl request is working. But, the jquery request is returning the JSON.parse error. I don't know why. Could someone help me, it's getting a bit frustrating.

Ok, so without your controller code is hard to understand the origins of problem, but possible solutions:

In the end of your action put in something like:

respond_to do |format|
  format.json { render json: 'Your message', status: :ok } # Don't use here .to_json!
end

Also, you can add in your client-side: dataType: 'json' AND you don't need to perform JSON.stringify(data) , you can just work with data , because it's already correctly formatted.

This should do the trick, if not, provide us with action code.

I think this is because you are putting your http response code inside of a json string intended to be consumed by your success function. Since jquery doesn't see an http response code it assumes an error and returns to error.

You should include the status code outside of the message body - something like this:

render json: {authtoken: 'xyz', myotherstuff: 'abc'}, status: :created

I had the same problem and this is what worked for me.

I found this really helpful too: http://www.codyfauser.com/2008/7/4/rails-http-status-code-to-symbol-mapping

It tells me what :symbol to use to correspond to which http status code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM