How does my ajax call know where my json is in rails -


i have javascript file ajax in follows.

$.ajax({        type: "get",        contenttype: "application/json; charset=utf-8",        url: 'data',        datatype: 'json',        success: function (data) {            draw(data);        },        error: function (result) {            error();        }    }); 

i have created method in controller renders json.

class graphcontroller < applicationcontroller def index end

def data   render :json =>  user.select('value').map(&:value) end end 

so question is, how rails know json coming i'm not returning physical file controller. happens if have physical .json file in folder structure? there heirarchy of how view json file (eg physical file>jbuilder file>controller action)?

in ajax call.. contenttype: "application/json; charset=utf-8", defines type of request querying rails.what says is, "if client wants html in response action, respond have before, if client wants xml, return them list of people in xml format." (rails determines desired response format http accept header submitted client.).

take respond_to api how rails responds different types of request -js/xml/html/json

so can try in controller well..edit data action , try..any call data such js/html/xml/json work , rails understand type of response needs send.

def data        format.html { redirect_to(user_list_url) }       format.js       format.xml  { render :xml => @users.to_xml(:include => @accounts) }       format.json {render :json =>  user.select('value').map(&:value) } end 

to render error controller view..can done this:-

   if @user.present?        format.json {render :json =>  user.select('value').map(&:value) }      else       format.js { render :json => @user.errors.full_messages.join(' '),  :status => 400 }     end 

use in view in ajax.error function this

.error(function(data) {                    $("#show_error").html("an error occurred,please try again.");                   }); 

hope helps


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -