Home > Software design >  react undefined response from function ajax request
react undefined response from function ajax request

Time:11-19

Hello why its response "callback is not defined"

component 1:

console.log(getUserGps());

component 2:

import $ from 'jquery'
export const getUserGps = () => {
    $.ajax({
        url: "https://geolocation-db.com/jsonp",
        jsonpCallback: "callback",
        dataType: "jsonp",
        success: function(location:any) {
            let city = location.city
            console.log('Pobrano z gps '   location.city)
            return city
        }
      })
}

CodePudding user response:

jsonpCallback: "callback",

You explicitly told jQuery to tell the server to generate a JSONP program that calls a function named callback.

You didn't define that function.


Remove that line. Let jQuery generate the function from the success property with an automatic name instead.

CodePudding user response:

The Problem you have here is, that your aync function has no return-value. What you could do is the following:

const getUserGps = () => {
  return $.ajax({
    url: "https://geolocation-db.com/jsonp",
    jsonpCallback: "callback",
    dataType: "jsonp",
  }).then((location) => {
    return location.city
  })
}

Here you return the request as a promise then you can to the following in your second component:

getUserGps().then(data => {
   console.log(data);
})

Here you have some more information in how async functions and promises work: https://www.w3schools.com/Js/js_promise.asp

  • Related