-1

I am not able get the returned value after ajax call. I can see that values are being returned but when I do console.log() it shows undefined. Is there something wrong in my approach.

var base_path = "http://localhost/lab/theapp/api/"

$(function () {
  var url = base_path + "tasks"
  var type = "post"
  var data = ""
  var get = submit_me(type, data, url)
  console.log(get)
})

function submit_me(type, data, url) {
  try {
    $.ajax({
      url: url,
      type: type,
      data: data,
      dataType: "json",
      beforeSend: function (request) {
        request.setRequestHeader("X-CSRF-Token", $.cookie("token"))
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        //alert('page_login_submit - failed to login');
        console.log(JSON.stringify(XMLHttpRequest))
        console.log(JSON.stringify(textStatus))
        console.log(JSON.stringify(errorThrown))
      },
      success: function (r) {
        if (r.sessid) {
          var sessid = r.sessid
          var session_name = r.session_name
          var token = r.token
          jQuery.cookie("token", token)
          return r
        }
      },
    })
  } catch (error) {
    console.log(error)
  }
}
hgb123
  • 13,869
  • 3
  • 20
  • 38
esafwan
  • 17,311
  • 33
  • 107
  • 166
  • 1
    Where is the `console.log` that returns `undefined` in this? – christian314159 May 02 '14 at 05:17
  • 1
    Please set Async = 'false' and check it. – Jayesh Goyani May 02 '14 at 05:20
  • 1
    @JayeshGoyani this isn't a good answer to the question. Using `async=false` is bad programming practice – jasonscript May 02 '14 at 05:40
  • 1
    @jasonscript, it's always dangerous to make blanket statements like your comment above - yes, it's probably bad practice _in this instance_, but it exists [_for a reason_](https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings). – Simon MᶜKenzie May 02 '14 at 06:17
  • 1
    @SimonMᶜKenzie agreed, which is why this isn't a good answer. The OP didn't state why this would fix the problem, nor did they state any caveats or links to the api. jQuery defaults `async` to true for a reason too – jasonscript May 02 '14 at 06:21
  • console.log is in the above function, where I am calling this function. Here in success function I have returned it. – esafwan May 02 '14 at 06:26

1 Answers1

-1

Your ajax call will take some time to retrieve that values. You cannot pass the value directly to the variable. Write the code in ajax success function. ie console.log() in ajax request function. That would follow the delay caused by the ajax call. Try this link https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings Check the async attribute here and experiment.

SSS
  • 1,025
  • 7
  • 17