0

this is my JS code below:

function getTopProductsApi(){

 var result;

    $.ajax({
        url: API_url,
        type: "get",
        data: ({}),
        async:false,
        dataType: "jsonp",
        jsonpCallback:"success_jsonpCallback",
        success: function(rs){
            result = rs;
        }
    });
    return result ;

}


var result = getTopProductsApi();
alert(result);

PHP

public function test(){

        echo $_GET['callback']. '(' . json_encode('213213') . ')';
}

I am sure that I get the return json data: The json data I get below:

success_jsonpCallback("213213")

But there have no data when I alert.

Can someone tell the reason? Thanks

  • 1
    Yet another duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Quentin Apr 11 '14 at 09:50

3 Answers3

0

My code: test page:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function getTopProductsApi(){

 var result;

    $.ajax({
        url: '/test/test1.php',
        type: "get",
        data: ({}),
        async:false,
        dataType: "jsonp",
        jsonpCallback:"success_jsonpCallback",
        success: function(rs){
            result = rs;
        }
    });
    //alert(result);
    return result;
}

var result = getTopProductsApi();
alert(result);
</script>
</head>
<body>
</body>
</html>

php page:

<?php
echo $_GET['callback']. '(' . json_encode('213213') . ')';

It works well. You can have a try.

Crazy Crab
  • 694
  • 6
  • 16
0

Thanks for everyone's answer. Finally, I find the problem. Maybe this is not the currect answer, but this information is useful for me. The jsonp data type is always Asynchronous. The code-"return result" will always run faster the ajax block. So the result variable is always NULL. So I change my code likes below:

function getTopProductsApi(function_name){

$.ajax({
    url: API_url,
    global: false,
    cache: false,
    type: "get",
    data: ({'current_date':current_date}),
    dataType: "jsonp",
    jsonpCallback:"success_jsonpCallback",
    success: function(rs){
        result = rs;
        window[function_name](result);
    }
});

}

getTopProductsApi('another function name');

This method can make sure that I can get the ajax json data first, and then run another function I need.

Maybe this is not the best answer, please tell me if you have other cool ideas.

Thanks

-1

try below code:

function getTopProductsApi(){

var result;

$.ajax({
    url: API_url,
    type: "get",
    data: ({}),
    async:false,
    dataType: "jsonp",
    jsonpCallback:"success_jsonpCallback",
    success: function(rs){
        result = rs;
    }
});


}
function success_jsonpCallback(result){
    alert(result)
}
Rahul Kaushik
  • 1,454
  • 8
  • 16