ruby-on-railsjsonformatrespond-to

json request return html in rails


I'm currently trying to make a Ajax script to communicate with an Rails server on my localhost (for now). The problem is that I specify in my $.ajax request that I want the format in 'json' but rails returns a 'html' format:

$(document).ready(function(){

$('form').on("submit",function(){
    $.ajax({
        contentType: 'application/json; charset=utf-8',
        url : "http://192.168.0.36:3000/?value=10",
        type : "GET",
        dataType : 'JSON',
        success: function(data){
            alert(JSONParsedata(data));
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            alert(textStatus +", " +errorThrown);
        }
    });


    return false;
})

In the console log of the rails server, I can read:

Processing by WelcomeControllerindex as HTML ... Completed 200 OK in 34ms...

I actually receive a response from the server, but in a HTML format instead of JSON.

I precise that my rails controller for welcomeController code contains the:

 respond_to do |format|
  format.html
  format.json { render :json => @z }
end

z is a variable I want to send back to the Ajax request and is defined before (i lighted the code to make it understandable)

As a result, Jquery is trying to parse the result in a JSON format and then finish by a : parsererror syntaxerror unexpected token '<' Which correspond to the first character of the full page!

I searched for hours and I don't know how to resolve this.

Thank you very much for your help


Solution

  • Actually I solved this problem this morning:

    This method worked in a basic browser such as Chrome but wasn't enough for "Rhomobile", an app IDE I'm using (even using the same Ajax request!). To solve this, I added a parameter "format" to the request and a value "json" (&format=json) and I added a condition to my controller: If the variable 'format' exists && format == 'json' then render the result to JSON. Else it renders in HTML. This works on both Rhomobile and Browser.

    I am not sure why this worked on a basic browser and not on Rhomobile but I think it's due to the 'Cross-domain' request. (I used 'rack-cors' server-side). Now it works on both.

    Thanks to all of you for your help.