简体   繁体   中英

After AJAX call I can't see the result in my view

I work with Rails 4 and basically I am searching a value on my html webpage traversing the DOM with jquery. I store the value in a variable named key and I want to use this value to then make a request that would look like this : Record.find(id: key).name

I have a User and a Record model. In the app/views/users directory I have the partial _form.html.erb in which I am doing some javascript.

 var key = $('input#record_id').val(); 

And I want this variable to be available in the method search of my user controller, so that I can make a request with the parameter key .

So I am doing an AJAX call that looks like this :

 $('#example tbody').on('click','tr', function(){ var key = $(this).val(); $.ajax({ url: "/search", type: "POST", data: { key: key }, complete: function(){ console.log('success'); } }); }); 

And in my config routes file I wrote this route :

post '/search' => 'users#search'

In my User controller I wrote the method like this :

 def search @record = Record.find(params[:key]) end 

I then created a search.js.erb file that has the same name than the method in my controller. In this file I wrote :

 $('div#result').html("<%= @record.name %>"); 

But when I click on one element of my table nothing appears in my div

I have made a lot of console.log() to see what was in my variable key and it is ok there is the right value in it. Also my Ajax call works as in my console log it returns 'success' and in the tab network I can see the task named search with a status of 'ok'.

I had error 500 but I fixed it adding render json: 'ok' in my method search

Now I am so close of printing the result of my request @record.name but I can't manage to find the solution.

Can anyone give me the solution ? Any help is welcomed.

The controller has a convention of returning html by default. In this case, it looks like you're want to return your .js.erb partial. To do so, you need to configure the controller to return a js response.

def search
    @record = Record.find(params[:key])
    respond_to do |format|
        format.js {}
    end
end 

The format.js in the respond_to block will point the controller to your .js.erb partial. If that fails, post the results of your server's output log, which I imagine is being written to whatever terminal/console you have the app running in locally.

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