2017-03-06 5 views
0

これまで私は以前の質問を見ていて、どれも私を助けてくれたとは言えません。私の問題は次のとおりです、私はphpファイルを読み込むためにjavascript関数を呼び出すフォームとhtmlファイルがあります。jqueryを使ってPHPファイルを正しくロードするには

フォームは、次のようになります。

<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> 

以下れるの送信を担当JS機能:

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私の問題は、どのように、2倍です上記のフォーマットが私の古いコードのために働いたのと同じようにajaxで呼び出すことができますが、何らかの理由でfuncを拒否していますこれを正しく理解してください。そして、私はどのようにPHPデータを取得する必要がありますか? PHPコードは以下の通りです:

これはYouTubeの地理位置図のコードの変更版です。

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



} 




?> 
+0

phpファイル自体は正常に動作することに注意することが重要です。私がフォームの代わりにボタンのデフォルトを禁止した場合、それはまだ再送信されます。 – SomeStudent

答えて

2

問題が非非同期要求を指定するために、あなたの試みであることが表示されます。私はこれらが現行/現代のブラウザによってブロックされていると信じています。あなたのjavascriptコンソールを確認すると、次のようなエラーが表示されます。

メインスレッドの同期XMLHttpRequestは、エンドユーザーの経験に悪影響を与えるため、推奨されていません。詳細については、https://xhr.spec.whatwg.org/を確認してください。

これを削除すると、以前と同じように動作すると思います(指定したとおりに動作した場合)。 jQueryのajaxリクエストはデフォルトでは非同期であるため、その行を削除すると非同期に動作します。

(これは、あなたの質問の一部ではありませんでしたが、あなたは、入力フィールドのvalue=""空白を残して検討し、代わりにplaceholder=""属性であなたのヘルパーテキストを配置することがあります。これらは、その情報を持っていることのリスクなしにユーザーに手掛かりを提供します

呼び出しの結果を表示するために、呼び出しをHTMLに戻して呼び出しページにそのHTMLを表示するだけでになるはずです。あなたはjQueryを使用しているので、コードを次のように単純化することができます:$('#geolocation-results').html(data);あなたの呼び出しでdataType: 'html'を指定する必要があるかもしれません。 (https://api.jquery.com/jquery.get/

Oh my。今明らかです。 .get呼び出しの構造が間違っていると思います。このようにする必要があります:

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

は今...さて、少しあまりにも多くを急いでした後、私は$.get()コールは単に間違って構成されたことを確認できることを確認します。上記のように修正すると、PHPファイルが正しく呼び出され、出力がgeolocation-results要素に表示されます。

+0

私は私のコンソールログにそのエラーがあったとは思わない。そして価値の良い点は、私はそれをホルダーに変更しました。 – SomeStudent

+0

あなたの呼び出しのurl属性に引用符の前後に引用符があることに気付きました。 '"../php/geolocation.php"'。あなたが 'url: '../ php/geolocation.php'に変更した場合、それは機能しますか? – Davis

+0

私は質問を投稿した後にそれを変更し、まだ動作を拒否します。 Ajaxは確かに奇妙な生き物です。 – SomeStudent

1

コードに間違いがあると思います。 asyncasynchではなく)をfalseとする必要はありません。なぜなら、クライアントブラウザを何も妨げているからです。 urlパラメータには引用符を含めないように注意してください。最後に、ボタンをクリックせずにEnterを押すだけで、フォームを送信できるので、送信イベントのトリガーをonclickイベントより多くする必要があります。

あなたはこの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; 
    } 
}); 
+0

うーん、私はこれを試して、私はそれがまったく働いていないと思う。 URLに問題がある可能性がありますか?以前のプロジェクトでは、すべてのファイルが同じディレクトリに置かれていましたが、ディレクトリ構造があります。 – SomeStudent

+0

Developper Consoleを使用して、javascriptで何がうまくいかないのかをデバッグしてください。 「コンソール」タブにいくつかの情報があります。あなたが何がうまくいかないのか分からないなら、私たちにあなたのディレクトリ構造を教えてください。 –

+0

実際、私はシャドールートに関する非推奨の警告しか表示されません。ディレクトリ構造は次のとおりです:project3 - > [html]、[php]、[javascript]、[css] []内のすべてがディレクトリです。私はそれがそれを見つけることができないエラーをスローする../php/なしでgeolocations.phpを書き込むかのようにPHPファイルをpingしていることを知っています。 – SomeStudent

関連する問題