BKSpurgeon BKSpurgeon - 2 months ago 14x
Ajax Question

Displaying link_to using Jquery, on the return of JSON data

I've searched through SO and nada, so have resorted to a question. I hope it will help somebody in the future.

What am I trying to do?

I'm trying to display an edit_job_path link to display on the page via JQuery.

What am I doing?

I've made an ajax request which returns JASON data from the controller. @jobs is the collection which is contained in the JSON data. I want to display all these jobs in my current view using Jquery.

Here is what my controller returns:


#…......irrelevant detils skipped
format.json { render :json => @jobs.to_json(include: [:job_type, :level => {:include => :building}] ) }

Here is my Jquery function:

function fill_out_jobs_table(data){
$.each(data, function(i, job){
var infoTableRow = "";
infoTableRow += '<tr> ';
infoTableRow += '<td>' + job.level.building.name + '</td>';
infoTableRow += '<td>' + job.level.name + '</td>';
infoTableRow += '<td>' + job.hours + '</td>';
infoTableRow += '<td>' + job.panels_created + '</td>';
infoTableRow += '<td>' + job.job_type.name + '</td>';
infoTableRow += '<td>' + <%= link_to("Edit Job", edit_job_path(job.id))%> + '</td>';
infoTableRow += '</tr> '

Upon an event, the fill_out_jobs_table function runs, and the data returned from JSON is then displayed. It is currently displaying successfully. The only thing that does not display is the link_to. I want to also display a link_to the edit_job_path for each particular job instance.

Does anyone have any idea how to make the link display?

Any assistance very much appreciated


Ok so i tried to create an attribute. The link is showing but the job id is not being added to the link. I've added the following lines and the path that is showing is: /jobs/edit ----> without the job.id being added to the end as well. any clues?:

var edit_job_link = "<a href='/jobs/edit'" + job.id + " > Edit Job </a>";
infoTableRow += "<td>" + edit_job_link + " </td>";


you are very close, try my suggestion below. Notice single quotes (') are included. The job edit path was incorrect too, it should be /jobs/:id/edit, just be mindful about that.

var edit_job_link = "<a href='/jobs/" + job.id + "/edit' > Edit Job </a>";