0

I have a HTML page through which I need to pass two variables through post method to a PHP page which accept those two variables and call an API to fetch the result from those two variables. Now, my requirement is to get the API result back to first page. I am not able to get it.

From index.html, I am calling another page with -

$.ajax({
    url: "data.php",
    type: 'POST',
    data: {
        difficulty: term,
        cr : country
    },
    success: function (res) {
        console.log(res);
    }

In data.php, I am taking parameters through POST method and calling API,

$(document).ready(function(){
        var data;

        $.ajax({
            url: "https://key***.co*/api?key="+api_key,
            dataType: "json",
            data: {
                difficulty: <?php echo $diff; ?>,
                cr : <?php echo $cr; ?>
            },
            success: function (res) {
                data =  difficulty;

            }
        });

    }

Here the api_key is defined above. How to fetch the data back to index.html?

Bernhard
  • 4,855
  • 5
  • 39
  • 70
  • I suggest to use PHP methods to access API, but AJAX. In this case you will get final response at correct callback in `index.html`. – dganenco Jan 25 '19 at 09:12
  • 4
    _"How to fetch the data back to index.html?"_ - you cannot (the way you're doing it right now). Make a (php) curl request instead of the ajax in data.php; then you can return the result to index.html – Jeff Jan 25 '19 at 09:12
  • 2
    the ajax in data.php won't be executed anyway, because it never sees a browser that could execute the javascript. (unless you're doing some fancy thing via phantom.js or a jsonp return) – Jeff Jan 25 '19 at 09:13
  • 1
    This might be useful for you - https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming what you are doing is confusing server side and client side programming in your php file – Second2None Jan 25 '19 at 09:15
  • i don't get why you can't just do the call to the api directly in the first page. you are not adding anything while moving between index and data page – Lelio Faieta Jan 25 '19 at 09:20
  • Thanks, It worked with CURL, but one of my key contain asterisk (*) and dollar sign ($) in value, it is getting escaped during the call. Is there any solution for this? – Sachin Artani Jan 25 '19 at 09:23
  • @LelioFaieta , I need to pass API key during the call which is visible in developer tools, that's why I am doing this. – Sachin Artani Jan 25 '19 at 09:29
  • in index you can do so: 1. ajax call to get the api_key back to index from data, 2. ajax call to the API gateway – Lelio Faieta Jan 25 '19 at 10:57

1 Answers1

1

You should remove the Javascript from the data.php page, and use php to make the request.

You can refer this: PHP cURL GET request and request's body

Yash Kumar Verma
  • 9,427
  • 2
  • 17
  • 28