Skip to content
Advertisement

curl API PHP using ajax

I am trying to get wikipedia api using curl PHP with geonames. But it seems to be something wrong in the connection between the php file and the script. I have tried the url with hard coded values in the PHP and it works however if I tried to concatenate using $_REQUEST the url doesnt work is like the parameter is missing. I hard coded the data in the ajax just to check if is working at the moment but once is working it should getting the information from the form. The code looks like this:

$("#wikiSearch").click(function(){
    $.ajax({
        url: "libs/php/requests.php",
        type: 'POST',
        dataType: 'json',
        data: {
            q: "london",
        },
        success: function(result) {

            console.log("success");
            console.log(result);

        
        },
        error: function(jqXHR, textStatus, errorThrown) {
            // alert( "Sorry, there was a problem!" );
            // console.log( "Error: " + errorThrown );
            // console.log( "Status: " + status );
            // console.dir( xhr );
        }
    }); 
});
<!doctype html>

<html lang="en">

    <head>

        <meta charset="utf-8">
        <title>APIS examples</title>
        <meta name="author" content="GeoNames APIs">
        <meta name="description" content="APIS example">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link href="favicon.ico" rel="icon">
        <!--<link href="vendors/bootstrap/bootstrap.min.css" rel="stylesheet">-->
        <!--<link href="css/style.css" rel="stylesheet"></link>-->


        
        

    </head>

    <body>
        <div>
            <form method="post">
                <input id="input" type="text" placeholder="Search in Wikipedia" name="input">
                <br>
                <button type="submit" id="wikiSearch">Search</button>
            </form>
        </div>
        <script type="application/javascript" src="libs/js/jquery-2.2.3.min.js"></script>
        <script type="application/javascript" src="libs/js/script.js"></script>
        
    </body>

</html>

<?php

    
    ini_set("display_errors", "On");
    error_reporting(E_ALL);
    
    $executionStartTime = microtime(true) / 1000;

    $url='http://api.geonames.org/wikipediaSearchJSON?q='. $_REQUEST["q"] . '&maxRows=10&username=xxxxx';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);

    $result=curl_exec($ch);

    //$q = $_REQUEST["q"];
    //print_r($result);
    //var_dump($_POST);

    
    curl_close($ch);

    $decode = json_decode($result,true);
    
    


    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "mission saved";
    $output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
    $output['data'] = $decode;
    
    header('Content-Type: application/json; charset=UTF-8');
    
    echo json_encode($output); 

?>

Advertisement

Answer

Based upon your original code but modified to a single page with a simple Fetch call and NO curl – it might be useful to help you diagnose your issue. This works “as-is”

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['q'] ) ){
        
        $st = microtime(true) / 1000;
        
        $username='geronimo';
        $rows=10;
        
        $url=sprintf(
            'http://api.geonames.org/wikipediaSearchJSON?q=%s&maxRows=%d&username=%s',
            $_POST['q'],
            $rows,
            $username
        );
        $json=file_get_contents( $url );
        $output=['status' => [
            'code'          =>  200,
            'name'          =>  'ok',
            'description'   =>  'mission_saved',
            'returnedIn'    =>  ( microtime(true) - $st ) / 1000 . " ms",
            'data'          =>  json_decode($json)
        ]];
        exit( json_encode($output) );
    }
?>
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>APIS examples</title>
    </head>

    <body>
        <div>
            <form method="post">
                <input id="input" type="text" placeholder="Search in Wikipedia" name="input">
                <br />
                <button type="submit" id="wikiSearch">Search</button>
            </form>
            <output></output>
            
            
            <script>
                document.getElementById('wikiSearch').addEventListener('click',(e)=>{
                    e.preventDefault();
                    
                    let fd=new FormData();
                        fd.append('q',e.target.parentNode.querySelector('input[type="text"][name="input"]').value);
                        
                        
                    fetch( location.href, { method:'post',body:fd })
                        .then( r=>r.json() )
                        .then( json=>{
                            console.log(json);
                            document.querySelector('output').textContent=JSON.stringify(json)
                        })                  
                    
                });
            </script>
        </div>
    </body>
</html>

You could tweak your PHP to include some of the same logic ( to test that the q is present )

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['q'] ) ){
    
        $executionStartTime = microtime(true) / 1000;

        $url='http://api.geonames.org/wikipediaSearchJSON?q='. $_POST['q'] . '&maxRows=10&username=geronimo';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL,$url);

        $result=curl_exec($ch);
        curl_close($ch);

        $decode = json_decode($result,true);
        
        $output['status']['code'] = "200";
        $output['status']['name'] = "ok";
        $output['status']['description'] = "mission saved";
        $output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
        $output['data'] = $decode;
        
        header('Content-Type: application/json; charset=UTF-8');
        exit( json_encode( $output ) ); 
    }
?>

But your AJAX function needs to be prevented from allowing the button to actually SUBMIT the form as it would try to do normally – hence using e.preventDefault()

$("#wikiSearch").click(function(e){
    e.preventDefault();
    
    $.ajax({
        url: "libs/php/requests.php",
        type: 'POST',
        dataType: 'json',
        data: {
            q: "london",
        },
        success: function(result) {

            console.log("success");
            console.log(result);

        
        },
        error: function(jqXHR, textStatus, errorThrown) {
            // alert( "Sorry, there was a problem!" );
            // console.log( "Error: " + errorThrown );
            // console.log( "Status: " + status );
            // console.dir( xhr );
        }
    }); 
});
Advertisement