AJAX with JQuery and PHP script not working together to API data

673 Views Asked by At

I have to use PHP to get data from the geonames API and use JQuery ajax method to get the data from the php file to load into my html file. Right now I am confused to why my php file is doing nothing. I have tried to use XAMPP server to read the php script data but all I got is the file contents of the php file. Are there any useful keywords someone knows that I can search for to find answers to using php,JQuery AJAX and API together?

<?php
    //comprehensive error handling.
    ini_set('display_errors', 'On');
    //report all php errors.
    error_reporting(E_ALL);

    //calculate the execution time of the script.
    $executionStartTime = microtime(true);

    //set the url variable with the required requests as the values in the url search.
    $url='http://api.geonames.org/countryInfoJSON?formatted=true&lang='.$_REQUEST['lang'].'&country='.$_REQUEST['country'].'&username=**********';
    
    //Initialize a cURL session
    $ch = curl_init();

    //Set the options on the given cURL session handles.
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);

    //Execute the given cURL session.
    $result=curl_exec($ch);

    //Close the cURL session.
    curl_close($ch);

    //decode the json object result.
    $decode = json_decode($result,true);    

    //The outputs
    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
    $output['data'] = $decode['geonames'];
    
    //The header for our requests
    header('Content-Type: application/json; charset=UTF-8');

    //print the outputs
    echo json_encode($output); 

?>

This is my script.js file. It has jquery click events for different buttons in my html table which I am trying to use to trigger the ajax function. I want my ajax file to get the php file to get data from the geonames api.

    //Get country info
    $('#btnInfo').on('click', function(event) {

        //Prevent whole page reloading.
        event.preventDefault();

        //AJAX method with a settings object.
        $.ajax({
            type: "GET", //http method to send request.
            url: "library/php/getCountryInfo.php", //use php server script file as proxy for request.
            timeout: 2000,
            //dataType: "json", //type of data expected for response.
            data: {
                country: $('#selCountry').val(), //requested data.
                lang: $('#selLang').val()
            },

            //BeforeSend function
            beforeSend: function() {
                $("#txtContinent").append('<p id="LoadingContinent">Loading...</p>');
                $("#txtCapital").append('<p id="LoadingCapital">Loading...</p>');
                $("#txtLanguages").append('<p id="LoadingLanguages">Loading...</p>');  //Add loading messages to results.
                $("#txtPopulation").append('<p id="LoadingPopulation">Loading...</p>');
                $("#txtArea").append('<p id="LoadingArea">Loading...</p>');
            },

            //Complete function
            complete: function() {
                $("#LoadingContinent").remove();
                $("#LoadingCapital").remove();
                $("#LoadingLanguages").remove(); //Remove loading messages from results.
                $("#LoadingPopulation").remove();
                $("#LoadingArea").remove();
            },

            //success function
            success: function(result) {

                console.log(result);

                if (result.status == "ok") {

                    $('#txtContinent').html(result['data'][0]['continent']);
                    $('#txtCapital').html(result['data'][0]['capital']);
                    $('#txtLanguages').html(result['data'][0]['languages']);
                    $('#txtPopulation').html(result['data'][0]['population']);
                    $('#txtArea').html(result['data'][0]['areaInSqKm']);

                }
                
            },

            //error function
            error: function(request, errorThrown) {
                let message = "";
                if(request.status === 0) {
                    message = "You are not connected. \n Check your network connection.";
                    console.log(message);
                } else if(request.status == 404) {
                    message = "Requested content not found.";
                    console.log(message);
                } else if(request.status == 500) {
                    message = "Internal Server Error [500].";
                    console.log(message);
                } else if(errorThrown === 'parsererror') {
                    message = "Requested JSON parse failed.";
                    console.log(message);
                } else if(errorThrown === 'timeout') {
                    message = "Requested timed out.";
                    console.log(message);
                } else if(errorThrown === 'abort') {
                    message = "Ajax request aborted.";
                    console.log(message);
                }  else {
                    message = 'Uncaught Error.\n' + request.responseText;
                }
                $("#ajaxMessage").html(message); //add the message to the html page
            }
        }); 
    });

My index.html file. It has a table with buttons and should show the returned data in the paragraphs below.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="Author" content="Patrick Trollip">
    <title>TASK:AJAX/PHP/CURL/JSON/GeonamesAPI</title>
  </head>
  <body>
    <h1>Task:</h1>
    <div id="userInputs">
      <table>
        <tr>
          <th>API Name:</th>
          <th>API Description:</th>
          <th>Inputs:</th>
        </tr>
        <tr>
          <td>countryInfo</td>
          <td>
            <label for="selCountry">Country</label>
            <select id="selCountry">
              <option value="GB">Great Britain</option>
              <option value="FR">France</option>
              <option value="DE">Germany</option>
              <option value="BR">Brazil</option>
              <option value="PT">Portugal</option>
            </select>
            <label for="selLang">Language</label>
            <select id="selLang">
              <option value="en">English</option>
              <option value="fr">French</option>
              <option value="de">Deutsche</option>
              <option value="pt">Portuguese</option>
            </select>
          </td>
          <td>
            <button id="btnInfo">Get Info</button>
          </td>
        </tr>
        <tr>
          <td>timezone</td>
          <td>
            <input type="number" id="InputTZlatitude" placeholder="Latitude">
            <input type="number" id="InputTZlongitude" placeholder="Longitude">
            <input type="number" id="InputTZradius" placeholder="Radius">
            <label for="SelTZlanguage">Language</label>
            <select id="SelTZlanguage">
              <option value="en">English</option>
              <option value="fr">French</option>
              <option value="de">Deutsche</option>
              <option value="pt">Portuguese</option>
            </select>  
          </td>
          <td>
            <button id="btnTimeZone">Get Time</button>
          </td>
        </tr>
        <tr>
          <td>weather</td>
          <td>
            <input type="number" id="coordN" placeholder="North">
            <input type="number" id="coordS" placeholder="South">
            <input type="number" id="coordE" placeholder="East">
            <input type="number" id="coordW" placeholder="West">
            <input type="number" id="maxRows" placeholder="Minimum rows 10">
            <label for="SelWeatherlanguage">Language</label>
            <select id="SelWeatherlanguage">
              <option value="en">English</option>
              <option value="fr">French</option>
              <option value="de">Deutsche</option>
              <option value="pt">Portuguese</option>
            </select>  
          </td>
          <td>
            <button id="btnWeather">Get Weather</button>
          </td>
        </tr>
        <tr>
          <td>countryCode</td>
          <td>
            <input type="number" id="InputCClatitude" placeholder="Latitude">
            <input type="number" id="InputCClongitude" placeholder="Longitude">
            <input type="number" id="InputCCradius" placeholder="Radius">
            <label for="SelCCType">CountryCode Type</label>
            <select id="SelCCType">
              <option value="GB">Great Britain</option>
              <option value="FR">France</option>
              <option value="DE">Germany</option>
              <option value="BR">Brazil</option>
              <option value="PT">Portugal</option>
            </select>  
            <label for="SelCClanguage">Language</label>
            <select id="SelCClanguage">
              <option value="en">English</option>
              <option value="fr">French</option>
              <option value="de">Deutsche</option>
              <option value="pt">Portuguese</option>
            </select>  
          </td>
          <td>
            <button id="btnCtryCode">Get Code</button>
          </td>
        </tr>
      </table>
    </div>
    <div id="userResults">
      <div>
        <h2>Country information:</h2>
        <h3>Results:</h3> <!--Display Country information results-->
        <p>Continent:<span id="txtContinent"></span></p>
        <p>Capital:<span id="txtCapital"></span></p>
        <p>Languages:<span id="txtLanguages"></span></p>
        <p>Population:<span id="txtPopulation"></span></p>
        <p>Area:<span id="txtArea"></span></p>
      </div>
      <div>
        <h2>Timezone:</h2> <!--Display Timezone results-->
        <h3>Results:</h3>
        <p>TimeZone Latitude:<span id="TZlat"></span></p>
        <p>TimeZone Longitude:<span id="TZlng"></span></p>
        <p>TimeZone Radius:<span id="TZrad"></span></p>
        <p>TimeZone Language:<span id="TZlang"></span></p>
      </div>
      <div>
        <h2>Weather:</h2> <!--Display Weather results-->
        <h3>Results:</h3>
        <p>Weather South:<span id="WeatherSouth"></span></p>
        <p>Weather West:<span id="WeatherWest"></span></p>
        <p>Weather North:<span id="WeatherNorth"></span></p>
        <p>Weather East:<span id="WeatherEast"></span></p>
        <p>Languages:<span id="WeatherLanguages"></span></p>
      </div>
      <div>
        <h2>Country Code:</h2> <!--Display Country Code results-->
        <h3>Results:</h3>
        <p>Country Code Latitude:<span id="ResultCClat"></span></p>
        <p>Country Code Longitude:<span id="ResultCClng"></span></p>
        <p>Country Code Type:<span id="ResultCCtype"></span></p>
        <p>Country Code Language:<span id="ResultCClang"></span></p>
        <p>Country Code Radius:<span id="ResultCCRad"></span></p>
      </div>
      <div id="ajaxMessage"><!--Display AJAX message here--></div>
    </div>
    <script type="application/javascript" src="library/js/jquery-3.6.0.min.js"></script>
    <script type="application/javascript" src="library/js/script.js"></script>
  </body>
</html>
0

There are 0 best solutions below