2013-06-07 7 views
0

У меня возникает ошибка при попытке получить доступ к другой переменной. В search_server.php я пытаюсь получить $pilihdomain переменную, определенную в index.php Я стараюсь, как это:PHP - проблема при доступе к другой переменной

//index.php  
    <head> 
      <title>Twitter Search</title> 
      <link href="search_client.css" type="text/css" rel="stylesheet" /> 
      <link href="tweet.css" type="text/css" rel="stylesheet" /> 
      <script src="jquery.min.js"></script> 
      <script src="search_client.js"></script> 
     </head> 
     <body> 
      <div id="search_box"> 
      <h1>Twitter Search</h1> 
      <input name="search_terms" autofocus="autofocus"/>  
     <?php 
     $dbHost = "localhost"; 
     $dbUser = "root"; 
     $dbPass = ""; 
     $dbname = "skripsi"; 
     $db = mysql_connect($dbHost,$dbUser,$dbPass); 
     mysql_select_db($dbname,$db); 
     $sql = mysql_query("SELECT * FROM namaklasifier"); 
     while($row = mysql_fetch_array($sql)) { 
      $clsfr = $row['username']; 
      $sql = mysql_query("SELECT * FROM namaklasifier"); 
       echo '<select name="cmake" autofocus width="10">'; 
       echo '<option value="0">-Pilih Domain Klasifikasi-</option>'; 
       while($row = mysql_fetch_array($sql)) { 
        echo '<option ' . ($clsfr==$row['username']) . ' value="'.$row['username'].'">'.$row['username'].'</option>'; 
      } 
      echo '</select>'; 
     } 
     ?> 
      <?php 
     global $pilihdomain; 
     $pilihdomain=$_POST['cmake']; 
      ?> 
      <button id="search_button">Search</button> 
      </div> 

      <div id="search_results_loader"></div> 
      <table border="1"> 
      <tr> 
      <th>Positif</th> 
      <th>Negatif</th> 
      </tr> 
      <tr> 
      <td><div id="search_results_pos"></div></td> 
      <td><div id="search_results_neg"></div></td> 
      </tr> 
     </table> 
     </body> 

//search_server.php

<?php 
    require 'index.php'; 
global $pilihdomain; 
    // The search terms are passed in the q parameter 
    // search_server.php?q=[search terms] 
    if (!empty($_GET['q'])) { 

     // Remove any hack attempts from input data 
     $search_terms = htmlspecialchars($_GET['q']).' -smartfrencare -siapkan -klaim'; 

     // Get the application OAuth tokens 
     require 'app_tokens.php'; 

     require_once("uClassify.php"); 

     $uclassify = new uClassify(); 
     // Set these values here 
     $uclassify->setReadApiKey('8DvvfxwKPdvjgRSrtsTSOawmQ0'); 
     $uclassify->setWriteApiKey('v4Us59yQFhf9Z0nGrQsrTtzBI5k');   

     // Create an OAuth connection 
     require 'tmhOAuth.php'; 

     $connection = new tmhOAuth(array(
      'consumer_key' => $consumer_key, 
      'consumer_secret' => $consumer_secret, 
      'user_token'  => $user_token, 
      'user_secret'  => $user_secret 
     )); 

     // Request the most recent 100 matching tweets 
     $http_code = $connection->request('GET',$connection->url('1.1/search/tweets'), 
       array('q' => $search_terms, 
        'count' => 5, 
        'lang' => 'in', 
        'locale' => 'jakarta', 
        'type' => 'recent')); 

     // Search was successful 
     if ($http_code == 200) { 

      // Extract the tweets from the API response 
      $response = json_decode($connection->response['response'],true); 
      $tweet_data = $response['statuses']; 

      // Load the template for tweet display 
      $tweet_template= file_get_contents('tweet_template.html'); 

      // Load the library of tweet display functions 
      require 'display_lib.php'; 

      // Create a stream of formatted tweets as HTML 
      $tweet_stream = ''; 
      foreach($tweet_data as $tweet) { 

       // Ignore any retweets 
       if (isset($tweet['retweeted_status'])) { 
        continue; 
       } 
       // Get a fresh copy of the tweet template 
       $tweet_html = $tweet_template; 

      // global $pilihdomain; 
       $resp = $uclassify->classify($tweet['text'],$pilihdomain, 'herlambangp');    
       $value = print_r($resp,true) ;   
       // Insert this tweet into the html 
       $tweet_html = str_replace('[screen_name]',$tweet['user']['screen_name'],$tweet_html); 
       $tweet_html = str_replace('[name]', $tweet['user']['name'],$tweet_html);   
       $tweet_html = str_replace('[profile_image_url]',$tweet['user']['profile_image_url'],$tweet_html); 
       $tweet_html = str_replace('[tweet_id]', $tweet['id'],$tweet_html); 
       $tweet_html = str_replace('[tweet_text]',linkify($tweet['text']),$tweet_html); 
       $tweet_html = str_replace('[tweet_class]',$value,$tweet_html); 
       $tweet_html = str_replace('[created_at]',twitter_time($tweet['created_at']),$tweet_html); 
       $tweet_html = str_replace('[retweet_count]',$tweet['retweet_count'],$tweet_html);   

       // Add the HTML for this tweet to the stream 
       $tweet_stream .= $tweet_html; 
      } 

      // Pass the tweets HTML back to the Ajax request 
      print $tweet_stream; 

     // Handle errors from API request 
     } else { 
      if ($http_code == 429) { 
       print 'Error: Twitter API rate limit reached'; 
      } else { 
       print 'Error: Twitter was not able to process that search'; 
      } 
     } 

    } else { 
     //not implement anything 
    } 

    ?> 

search_client.js

// jQuery script for search request with server 
jQuery(document).ready(function($) { 

    // Run when Search button is clicked 
    $('#search_button').click(function(){ 

     // Display a progress indicator 
     $('#search_results_loader').html('<img src="ajax_loader.gif"> Searching Twitter...'); 

     // Get the value of the input field 
     // Encode it for use in a URL 
     var search_value = encodeURIComponent($('input[name=search_terms]').val()); 

     // Send the search terms to the server in an Ajax request 
     // This URL is for illustration only 
     // You MUST change it to your server 
     $.ajax({ 
      url: 'http://localhost/kejar/code/search_server.php?q=' + search_value, 
      success: function(data){ 

       // Display the results 
       $('#search_results_loader').html(''); 
       $('#search_results_pos').html(data); 
       $('#search_results_neg').html(data); 
      } 
     }) 
    }) 
}); 

Можете ли вы объяснить, где мой фальшивый ?.

Любая помощь будет оценена по достоинству. Спасибо :)

+1

Какая ошибка, можете ли вы опубликовать ее? –

+0

мой код не поймал $ pilihdomain, который я определил в $ index.php – user2413763

ответ

1

Прежде всего Don't use GLOBAL

Удалить глобальное предложение из обоих сценариев и использовать ниже кода, а также проверить, является ли эта переменная не используется в других сценариях.

index.php

<?php 
//global $pilihdomain; 
$pilihdomain=$_POST['cmake']; 

search_server.php

<?php 
require 'index.php'; 
//global $pilihdomain; 
... 
$resp = $uclassify->classify($tweet['text'],$pilihdomain, 'herlambangp'); 

Редактировать

Здесь вы только отправка GET переменной q

url: 'http://localhost/kejar/code/search_server.php?q=' + search_value 

И из-за этого $_POST['cmake'] не доступен.

+0

Привет @Yogesh Я попробовал ваше предложение, но он терпит неудачу. можете ли вы снова проанализировать ситуацию? Я обновлю все свои коды (добавив .js). спасибо :) – user2413763

+0

@ user2413763 См. отредактированный ответ. –

+0

Я не слишком хорошо читаю строку js. можете ли вы предложить мне что-нибудь? спасибо – user2413763

1

Во-первых, избавиться от всех этих global $pilihdomain; заявлений.

Во-вторых, $_POST['cmake'] не заполняется при выполнении запроса GET здесь:

$.ajax({ 
    url: 'http://localhost/kejar/code/search_server.php?q=' + search_value, 
    ... 
}); 

В самом деле, только $_GET['q'] будет заселен.

+0

что я делаю? извините, я слишком беден, чтобы понять js :( – user2413763

+0

@ user2413763 Я не уверен, как бы я мог помочь вам, потому что неясно, чего вы пытаетесь достичь. –