A jquery.ajax request for ruby ​​on a rails server gives a JSON.parse error on the client

I have a client side jquery code that is trying to contact ruby ​​on a rails server. I am currently trying to do a login job through a client.

Here is the jquery code that runs 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 tracked the logs on the rails server and saw "Completed 200 OK in 387ms", which means that the server process went well and the response was 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 to use firebug and on the POST request response tab I saw

syntaxerror json.parse unexpected end of data

, , , . -,

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

{"auth_token":"zk1dyduMAo283mxP5o1m","success":true,"status":"created"}

, . jquery JSON.parse. . - , .

+4
2

, , :

- :

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

, : dataType: 'json' JSON.stringify(), , .

, , .

0

, , HTTP json, . jquery HTTP, .

- :

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

, , .

: http://www.codyfauser.com/2008/7/4/rails-http-status-code-to-symbol-mapping

, : , http- .

0

All Articles