-1

In basic terms I am trying to make a cross domain AJAX call using JSONP. The JS and PHP files need to be on a different domain. I can't seem to get the returned data back to the original function.

To explain how the page works. A user will enter something into an input box. e.g. Surname.

Input and search.

After the user clicks search a the searchClick() function is called. This function takes the text the user has inserted into the input box and calls another function called getInfo().

function searchClick() {
    var jsonOfData = getInfo($('#searchInput').val());
    console.log(jsonOfData );
}

The getInfo() function has to be in a JS file on a different domain.

function getInfo(surname) {
$.ajax({
    url: "https://www.otherdomain.com/api/lookup.php",
    dataType: 'jsonp',
    crossDomain: true,
    data: {
        surname: surname
    },
    success: (data) => {
        console.log(data); // This works
        return data; // This doesn't
      }
  });
}

This ajax call goes off to my PHP page and does a search on the database. It then created a JSON array and sends it back. From my research instead of ending the file with the usual echo json_encode($array); I ended the file with:

echo $_GET['callback'] . "(" . json_encode($responseArr) . ")";

This is the point at which I have my problem. As you can see, in the AJAX success function, the data is successfully displayed and logged to the console but I can't return it back to the original jsonOfData variable.

I hope this makes sense and i'll be so thankful to anyone who can help me out.

Michael Scott
  • 23
  • 1
  • 3
  • "In basic terms I am trying to make a cross domain AJAX call using JSONP" — JSONP is a dirty, inflexible, hard-to-debug hack used in the bad old days before we had [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). Use CORS instead. (You still can't make asynchronous code not be asynchronous though) – Quentin Jul 03 '19 at 12:49
  • why not create a variable inside `getInfo()` method that saves the `jqXHR` object returned by `$.ajax()`, that is: `var jqXHR = $.ajax (...)` and get the response text from `return JSON.parse(jqXHR.responseText)` after your ajax call – Udo E. Jul 03 '19 at 13:29
  • Thank you @Quentin, I've managed to fix the problem by using CORS now. – Michael Scott Jul 03 '19 at 13:44
  • @UdoE. — Because that would have exactly the same problem. Read the duplicate. – Quentin Jul 03 '19 at 13:44

1 Answers1

-1

What you're trying to do won't work, because the $.ajax calls works asynchronously.

Instead of work with the return of the function call at this point:

var jsonOfData = getInfo($('#searchInput').val());

Try to build your logic inside the success function of your $.ajax call.