Reputation: 1687
I am trying to consume a controller action from ajax by this :
var idDocumento = $(this).attr('id');
$.ajax({
type: "POST",
dataType: "json",
cache: false,
url: "%= document_download_create_company_company_document_path(company_id:params[:id], id: %>" + idDocumento + ""<%, :format => :js ) %>",
success: function(data){
alert(data);
}
});
});
To this controller :
def document_download_create
end
I need to get the parameters in the controller from the ajax call, and make an insert in MediaDownload. I already added the route `document_download_create_company_company_document_path. So my question is, how should I get the parameters int the controller action, and how to send it properly, because I am getting an error in :
"<%= document_download_create_company_company_document_path(company_id:params[:id], id: %>" + idDocumento + ""<%, :format => :js ) %>"
That says
syntax error, unexpected ')'
Thanks in advance.
Upvotes: 2
Views: 103
Reputation: 76774
Looks like your syntax is messed up a little too:
var idDocumento = $(this).attr('id');
$.ajax({
type: "POST",
dataType: "json",
cache: false,
url: "<%= document_download_create_company_company_document_path(company_id:params[:id], id: %>" + idDocumento + "<%, :format => :js ) %>",
success: function(data){
alert(data);
}
});
ERB
If you're calling this code in the assets (application.js
), it won't work. Reason being Rails doesn't run erb
code in the assets pipeline (because you can precompile it)
If you want to send params to a URL through ajax, you'll be better using either a link_to
with remote
option, or using a form:
<%= link_to "your_link", document_download_create_company_company_document_path(company_id:params[:id], id: #your_id_param), remote: :true %>
Considering your Ajax
has to be bound to an event anyway, I'd recommend using a link like this as the best way to keep your app to convention
PS - how did you build your link path? That thing is huge -- might be worth cutting it down?
Upvotes: 0
Reputation: 44675
Your problem is here:
<%= document_download_create_company_company_document_path(company_id:params[:id], id: %>
Erb is being parsed before the javascript is executed. What's more, it have absolutely no idea that idDocumento
represents anything - for erb it is just a text. In short - you can't pass javascript value to the erb block. THere is a way around though:
var idDocumento = $(this).attr('id');
var pathTemplate = "<%=document_download_create_company_company_document_path(company_id: params[:id], id: :idDocumento, format: js) %>"
var path = pathTemplate.replace('idDocumento', idDocumento)
Explanation:
Since you don't know idDocumento
at the time erb is executed, you stub it with a symbol :idDocumento
. This will make erb to render:
var pathTemplate = "path/to/document/with/id/idDocumento/download"
hence, all your js need to do is to replace this idDocumento
string with the known at this point value.
Upvotes: 1