-1

I have a PHP script that takes a query string returns and JSON object. I am trying to make an AJAX call that will return this JSON object so I can use it in jQuery autocomplete. Here is my AJAX call so far

$(document).ready(function(){

  $("#searchBox").keyup(function(){
   var search_result = $.ajax({
      url:"/mm5/service/product_lookup_json.php",
      type: "GET",
      dataType: "json",
      jsonp: false,
      data: "query=" + $("#searchBox").val(),
      success: function(data){
        return data;
      }
    });

    console.log(search_result);
   });
 });

This sends the result of the AJAX call to the console ( a javascript object). I can see a JSON in that object. I would think all I have to do to access the data I want is this

console.log(search_result.responseJSON);

But this just gives me undefined. What am I doing wrong here?

Doug Steinberg
  • 982
  • 11
  • 28

2 Answers2

0

That is not the way to do it because it is an async call so the data will not be returned by the ajax call. Try this

$(document).ready(function(){
    var search_result;
    $("#searchBox").keyup(function(){
        $.ajax({
            url:"/mm5/service/product_lookup_json.php",
            type: "GET",
            dataType: "json",
            jsonp: false,
            data: "query=" + $("#searchBox").val(),
            success: function(data){
                search_result =  data;
                console.log(search_result);
            }
        });
     });
 });
Pablo Matias Gomez
  • 5,612
  • 6
  • 34
  • 69
0

You need to wait for the AJAX call to complete in order to access the data it returns.

$(document).ready(function(){

  $("#searchBox").keyup(function(){
   $.ajax({
      url:"/mm5/service/product_lookup_json.php",
      type: "GET",
      dataType: "json",
      jsonp: false,
      data: "query=" + $("#searchBox").val(),
      success: function(data){

        //data is available at this points
        console.log(data);

      }
    });
   });
 });
Khan
  • 2,614
  • 3
  • 19
  • 21