Jeremy Thomas Jeremy Thomas - 2 months ago 11
jQuery Question

Rails 4: Ajax request calls function and returns value without redirect

I have a rails controller function that calls out to a model function to fetch data and return that data. I am trying to use ajax to make the function call and don't want any redirect as all I care about are the values being returned. How can I accomplish this without reloading the page / getting a missing template error?

Controller

def update_sales
@data = ControllerName.function_name()
return @data # What I want
redirect_to path_name # what I don't want
end


Model

def self.function_name
...
...
return data
end


Ajax

$.get("/update_sales").done(function(data){
console.log(data);
// I would set html attribute to data but I get missing template error
})

Answer

could try something like this in controller action?

 if @data.save
   // send the object back to interface
   render json: @data.serialize.to_json, status: :ok
 else
   // send the errors back to interface
   render json: @data.errors.full_messages, status: :internal_server_error
 end

ajax call:

 $.ajax({
    url:"/update_sales",
    type: "PATCH",
    data: data_to_send
  }).done(function(data, textStatus, jqXHR) {
    // do stuff when it is done
  }).fail(function(jqXHR, textStatus, errorThrown){
    // do stuff if it errors out
  });
Comments