1

I want to get the id of an element that I have created using a query-AJAX-POST-Request, but none of the approaches that I have found so far, had worked.

Currently I am stuck here

Controller:

def createuserlink
  @new_element = Link.new(element_params)
  @new_element.save
  respond_with @new_element  
end

Jquery:

  $.ajax({
    url: "links/createuserlink",
    type: "POST",
    data: my_data
  }).done(function( data, textStatus, request ) {
    alert(data);
  });

The Request works and the new_element gets created, but the alert-message shows me the HTML-code of the new_element/show page. I can see the id of the returned page in the browser dev-tools (like foo.com/element/42), but I don't know how to access it.

I tried to use getResponseHeader as suggested here, but it only works for parameters (like foo.com?element=42).

I also tried respond_with @new_element.id, but he didn't liked the syntax.

What is the easiest and recommended way to get back the id?

Community
  • 1
  • 1
  • 1
    Create createuserlink.js.erb or createuserlink.js.haml file to show your data. Please refer this answer. http://stackoverflow.com/a/18900799/2681997. – Ajay Barot Mar 07 '17 at 18:41

1 Answers1

2

looks like you want json, not a template, instead of respond_with, why not try:

def createuserlink
  @new_element = Link.new(element_params)
  @new_element.save
  render json: @new_element.to_json
end
jrabramson
  • 105
  • 1
  • 8