SomeStudent
SomeStudent

Reputation: 3048

How to load a php file correctly using jquery

So allow me to first say I have looked at previous questions, and none of them have helped me out. My problem is as follows, I have an html file with a form which calls a javascript function to load a php file.

The form looks as following:

<form method="GET" id="submission" >
    <div class="form-group">
        <label for="q">Search Term:</label>
        <input type="text" class="form-control" id="q" name="q" placeholder="enter a keyword">
    </div>
    <div class="form-group">
        <label for="location">location</label>
        <input type="text" class="form-control" id="location" name="location" placeholder="lat,long">
    </div>
    <div class="form-group">
        <label for="locationRadius">Location Radius:</label>
        <input type="text" class="form-control" id="locationRadius" name="locationRadius" placeholder="25km">
    </div>
    <div class="form-group">
        <label for="maxResults">Max Results:</label>
        <input type="number" class="form-control" id="maxResults" name="maxResults" placeholder="0 to 50">
    </div>
    <button type="submit" id="submitButton" >Submit</button>
</form>

The JS function responsible for sending is the following:

function sendData() {
var keyword = document.getElementById("q").value;
var location = $('#location').value;
var locationRadius = $('#locationRadius').value;
var maxResult = $('#maxResults').value;

alert("keyword is: " + locationRadius);

$.get(
    {
        type: 'GET',
        url: '../php/geolocation.php',
        data : {q: keyword, location: location, locationRadius: locationRadius, maxResults: maxResult}
    },
    function (data) {
        //alert("Data loaded " + data);
        document.getElementById("geolocation-results").innerHTML = data;
    }
);

}

$(document).ready(function() {
    $("#submission").submit(function() {
    sendData();
    return false;
    });
});

SO my problem is two fold, how to call it in an ajax like manner as the above format worked for my old code, but for some reason refuses to function correctly for this one. And how should I fetch the php data? The php code is below:

It is a modified version of youtube's geolocation example code.

    <?php

/**
 * This sample lists videos that are associated with a particular keyword and are in the radius of
 *   particular geographic coordinates by:
 *
 * 1. Searching videos with "youtube.search.list" method and setting "type", "q", "location" and
 *   "locationRadius" parameters.
 * 2. Retrieving location details for each video with "youtube.videos.list" method and setting
 *   "id" parameter to comma separated list of video IDs in search result.
 *
 * @author Ibrahim Ulukaya
 */

/**
 * Library Requirements
 *
 * 1. Install composer (https://getcomposer.org)
 * 2. On the command line, change to this directory (api-samples/php)
 * 3. Require the google/apiclient library
 *    $ composer require google/apiclient:~2.0
 */
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
    throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}

require_once __DIR__ . '/vendor/autoload.php';

$htmlBody = null;
// This code executes if the user enters a search query in the form
// and submits the form. Otherwise, the page displays the form above.
if (isset($_GET['q'])
    && isset($_GET['maxResults'])
    && isset($_GET['locationRadius'])
    && isset($_GET['location'])) {

    /*
     * Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
    * {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
    * Please ensure that you have enabled the YouTube Data API for your project.
    */
    $DEVELOPER_KEY = 'AIzaSyC6q-84bJv9HWCUDT4_SQ5Bp9WFJW2Z-e4';

    $client = new Google_Client();
    $client->setDeveloperKey($DEVELOPER_KEY);

    // Define an object that will be used to make all API requests.
    $youtube = new Google_Service_YouTube($client);

    try {
        // Call the search.list method to retrieve results matching the specified
        // query term.
        $searchResponse = $youtube->search->listSearch('id,snippet', array(
            'type' => 'video',
            'q' => $_GET['q'],
            'location' =>  $_GET['location'],
            'locationRadius' =>  $_GET['locationRadius'],
            'maxResults' => $_GET['maxResults'],
        ));

        $videoResults = array();
        # Merge video ids
        foreach ($searchResponse['items'] as $searchResult) {
            array_push($videoResults, $searchResult['id']['videoId']);
        }
        $videoIds = join(',', $videoResults);

        # Call the videos.list method to retrieve location details for each video.
        $videosResponse = $youtube->videos->listVideos('snippet, recordingDetails', array(
            'id' => $videoIds,
        ));

        $videos = '';

        // Display the list of matching videos.
        foreach ($videosResponse['items'] as $videoResult) {
            $videos .= sprintf('<li>%s,%s (%s,%s)</li>',
                $videoResult['id'],
                $videoResult['snippet']['title'],
                $videoResult['recordingDetails']['location']['latitude'],
                $videoResult['recordingDetails']['location']['longitude']);
            echo $videos;
        }


//$htmlBody = <<<END
//    <h3>Videos</h3>
//    <ul>$videos</ul>
//END;


    } catch (Google_Service_Exception $e) {
        $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
            htmlspecialchars($e->getMessage()));
    } catch (Google_Exception $e) {
        $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
            htmlspecialchars($e->getMessage()));
    }



}




?>

Upvotes: 0

Views: 172

Answers (2)

Guillaume Sainthillier
Guillaume Sainthillier

Reputation: 1685

I think there are some mistakes in your code. You don't need to put async (and not asynch) as false because it's blocking the client browser for nothing. Be also careful to your url parameter which should not contains any quotes. Finally, you should put your trigger on the submit event more than on the onclick event because you can submit the form just by pressing Enter without clicking on your button.

You can try with this javascript :

function sendData() {
    var keyword = document.getElementById("q").value;
    var location = $('#location').value;
    var locationRadius = $('#locationRadius').value;
    var maxResult = $('#maxResults').value;

    alert("keyword is: " + keyword);

    $.get(
        '../php/geolocation.php',
        {q: keyword, location: location, locationRadius: locationRadius, maxResults: maxResult},
        function (data) {
            alert("Data loaded " + data);
            document.getElementById("geolocation-results").innerHTML = data;
        }
    );
}

$(document).ready(function() {
    $("#submission").submit(function() {
        sendData();
        return false;
    }
});

Upvotes: 1

Davis
Davis

Reputation: 846

It appears that the problem is your attempt to specify an non asynchronous request. I believe these are blocked by current/modern browsers. If you check your javascript console, you will probably see an error like this:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

If you remove that, I believe it will work as before (if it worked earlier, as you indicated). jQuery ajax requests are asynchronous by default, so if you remove that line, it will operate asynchronously.

(This wasn't part of your question, but you might consider leaving your input field's value="" blank, and put your helper text in placeholder="" attributes instead. These will provide the clue to your users without the risk of having that information passed in your request.)

As for displaying the result of the call, having your call return HTML and simply displaying that HTML on your calling page should work. Since you're using jQuery you could simplify your code like so: $('#geolocation-results').html(data); You may need/want to specify dataType: 'html' in your call as well. (https://api.jquery.com/jquery.get/)

Oh my. So obvious now. I believe your structure of the .get call is wrong. Should be like this:

$.get(
    "../php/geolocation.php",
    {
        q: keyword,
        location: location,
        locationRadius: r,
        maxResults: maxResult
    },
    function (data) {
        $('#geolocation-results').html(data);
    }
);

Checking that now... Okay, after rushing a bit too much I can confirm that the $.get() call was just structured wrong. Correct it as shown above and it will call the PHP file correctly and display the output in the geolocation-results element.

Upvotes: 2

Related Questions