0

I'm sure I'm missing something very very simple here...

JQUERY CODE

  $.ajax({
    type : "POST",
    url :  '/orders/create_or_update',
    dataType: 'json', 
    contentType: 'application/json',
    data : JSON.stringify(params)
  })
  .done(function(response){
    console.log(response.status)
    console.log(response)
  })

CONTROLLER CODE

  def create_or_update
    ...
    render json: {"name" => "test"}, status: 200
  end

OUTPUT OF CONSOLE.LOG

  undefined
  Object: {name: "test"}

Why is response.status in my jQuery not returning the status: 200?

james
  • 3,989
  • 8
  • 47
  • 102

1 Answers1

0

EDIT2:

Actually, for the .always function, if the response is a success, the arguments are (data, textStatus, jqXHR), but if it's a failure, it's (jqXHR, textStatus, errorThrown).

In the docs, it's stated like this:

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { })

jQuery Docs

So, you'd need an if/else to display jqXHR.status in the always for all responses.

EDIT:

Your response is just the object that you're getting back from the render call. It doesn't have any notion of status. That's why it's undefined when you .status on it. I think the .always is necessary b/c it will cover both .done and .fail responses from the controller. If you're only ever going to get the .done method, and you want that to take care of it, you can do this (note the extra textStatus argument):

  $.ajax({
    type : "POST",
    url :  '/orders/create_or_update',
    dataType: 'json', 
    contentType: 'application/json',
    data : JSON.stringify(params)
  })
  .done(function(response, textStatus, xhr){
    console.log(xhr.status)
    console.log(response)
  })

So, you should be able to do this:

  $.ajax({
    type : "POST",
    url :  '/orders/create_or_update',
    dataType: 'json', 
    contentType: 'application/json',
    data : JSON.stringify(params)
  })
  .done(function(response){
    console.log(response.status)
    console.log(response)
  }).always(function(a, textStatus, b){
    console.log(a.status); // One of these two will be `undefined`
    console.log(b.status);
  })

And that will print the status to the log.

James Milani
  • 1,921
  • 2
  • 16
  • 26
  • can you explain this to me a bit more? is the `always` necessary? i thought from reading the logs the `response` should be enough, that's why i'm confused as to why it's NOT working – james Feb 16 '17 at 22:21