Sascuash
Sascuash

Reputation: 3831

coffeescript $.post get string from return object

I have a little problem. When I call

myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json')

in 'myVar' I have an object, so, when I do console.log myVar, I get something like:

Object {readyState: 1, setRequestHeader: function, getAllResponseHeaders: function,getResponseHeader: function, overrideMimeType: function…}
abort: function (a){a=a||"abort",p&&p.abort(a),w(0,a);return this}
always: function (){i.done.apply(i,arguments).fail.apply(i,arguments);return this}
complete: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
[...]

If I make console.log myVar.success (for example), It prints what it's shown in success, but, if I make console.log myVar.responseText (where the result of the call is), I keep getting undefined, so I can never really access the data I'm interested in.

Any ideas how can I access that data??

I know that I'm misunderstanding something about post calls, but as I have the misunderstanding, I don't know what I'm doing wrong.

I used post instead of get because I really need to send data to the backend, so I can make some checks in DB

EDIT: Where I make console.log:

check2: (callback) ->
  console.log "Starting..."
  myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json')
  console.log myVar
  console.log "success example"
  console.log myVar.success
  console.log "responseText"
  console.log myVar.responseText

EDIT 2 Here's a photo of the object being showed by console.log myVar Image explaining returned object

Upvotes: 0

Views: 263

Answers (1)

mu is too short
mu is too short

Reputation: 434685

$.post is an AJAX call, it doesn't return the server's response, it returns a jqXHR promise:

jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
Returns: jqXHR

Description: Load data from the server using a HTTP POST request.

If you want the data from an AJAX call, then you have to get it from the callback:

fn = (data, status, jqxhr) ->
    # Your data is in `data` so do what you
    # need to do with `data` around here
    ...
    # And then call the other `callback` function
    # by hand.
    callback(data, status, jqxhr)

$.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), fn, 'json')

Upvotes: 2

Related Questions