简体   繁体   中英

AJAX call how to retrieve my javascript variable

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 perform an AJAX call and it works well (I checked it rendering status json ok). But now how can I use/retrieve the parameter key in my controller ?

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 :

 $.ajax({ url: "/search", type: "POST", data: { value: 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 

Is @record available in my partial ? How can I print in my view the result of my request ?

Can anyone tell me if I am doing right or wrong for my AJAX call ? Thanks for any help. If I forgot to mention any information you might need tell me and I'll edit my post.

I added a complete function in my AJAX call, that is supposed to show success if the AJAX call had been done and in my console log I have this message 'success' that appears

For 404 not found the url must be wrong.

And to get the param key in your controller you must change data to data: {key: key} or if you use data: {value: key} then your action must change the name of the param like @record = Record.find(params[:level])

Basically, you are not using the right param name in your controller which is why the issue arises. Hope it helps.

To answer your second question: @GDMN, you need to get your basics right! Every ajax has a success and failure callback.You could return json from your action which will be used by success callback and you could do whatever you want from there. Essentially in rails you might want to render a js file like this

Create a file named search.js.erb and use your javascript code in it like below

$('.some_id_or_class').html("<%= @record.name %>")

that will simply replace the element of that class with the value that is returned by @record.name

放置完整的URL URL:“ http://yoursite.domain/search ”,

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