0

I am trying to write ajax inside a function and return its value and depending on value do something

check_email_present = (email) ->
  $.ajax({
    type: "GET",
    url: "/donor/check_email_present",
    data: { email: email },
    success:(data) ->
      return data
    error:(data) ->
      return false
  })

I call this function like

  return_value = check_email_present(email)
  console.log(return_value)

I can see the object in log, when it try to print return_value.responseText i get undefined.

I also tried console.log(JSON.parse(return_value))

Within success function i'm able to do it(check data with if condition), but i want to return data back to a variable and then check it

Anbazhagan p
  • 943
  • 1
  • 14
  • 27

1 Answers1

0

Don't try to return stuff from asynchronous functions. Rather use a callback:

check_email_present = (email, done) ->
  $.ajax({
    type: "GET",
    url: "/donor/check_email_present",
    data: { email: email },
    success:(data) ->
      done(data)
    error:(data) ->
      done(null)
  })

and then:

check_email_present(email, return_value -> console.log(return_value))
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928