0

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()));
    }



}




?>
1
  • it is important to note that the php file works fine by itself. If I add the prevent default for the button and not the form then it still resubmits. Commented Mar 6, 2017 at 22:06

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I do not believe i ever had that error in my console log. And good point on the value, i did change it to place holder.
I just noticed your url attribute in your call has quotes around quotes, e.g. '"../php/geolocation.php"'. If you change it to url: '../php/geolocation.php' does it work?
changed it after i posted the question, still refuses to work. Ajax certainly is a strange creature.
See my edit. I think it's just the structure of your $.get(); call.
@SomeStudent, have you been able to try it after editing your $.get() call as outline in my answer?
|
1

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;
    }
});

8 Comments

hmm, i tried this and I do not see it working at all. Could the possible issue be with the url? I know in my previous project all the files were located in the same directory whilst with this one i have a directory structure.
Please use Developper Console to debug what's going wrong with your javascript. You will find some informations in the "Console" tab. If you cannot figure out what's going wrong, show us your directory structure
Indeed I am, only thing I see is a deprecation warning about shadow root. Dir struc is: project3 --> [html],[php],[javascript],[css] where everything in [] is a directory. I know it is pinging the php file as if i just write geolocations.php without ../php/ it throws an error that it cannot find it.
What's the result of your Ajax geolocations.php request?
according to my alert that is supposed to show the data returned it is empty. Which is odd since i am now trying to echo out the $videos which is how i did it with the previous project. if I just take the query produced and set the parameters on the php file itself it works on its own.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.