Need help passing variable from php to javascript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jerrysc
    New Member
    • May 2014
    • 2

    #1

    Need help passing variable from php to javascript

    I have a problem I've been trying to work through, to which I think there is a probably a simple solution I am missing. I am trying to pass a variable from php to javascript. Seems like it should be easy. The php variable will echo all I want it to; it will echo to the php file where the code is written, and it will echo into the jquery window where my results are listed (from a google books search). But the value of the variable will not propagate to a javascript variable.

    Right now I am just trying to pass the value of $book_title to the javascript variable title. I have been placing $book_title in different places hoping it will work. Please note that book-meta.php is the file I am using to pass variables from javascript to php, which is working just fine. Thanks for any help you can give me.

    Code:
    <?php
    /* 
    		Plugin Name: Book Search Using Google API
    		Plugin URI: http://whosgotbooks.com/wp-content/plugins
    		Description: A plugin to get book information and display it in the bbpress topic meta. Find a book by entering the title.
    		Version: 1.0.0
    		Author: Jerry Caldwell
    		Author URI: http://whosgotbooks.com
    		License: Open Source 
          	*/ 
      //turn on full error reports for development purposes - should be turned off for production environment
    //error_reporting(E_ALL);
      // shortcode for use in posts/pages
    //function book_search_google_shortcode() {                  
    //  book_search_google(); }
    //  add_shortcode( 'book-search-google', 'book_search_google_shortcode' );
    global $book_title;
    
    function book_search_google () {    
      //set API version for Google Book Search API
      $v = isset($_POST['v']) ? $_POST['v'] : '1';
      //set user API key for Google Book Search API
      $key = isset($_POST['key']) ? $_POST['key'] : '';
      //set user IP for Google Book Search API
      //$ip = isset($_POST['ip']) ? $_POST['ip'] : $_SERVER['REMOTE_ADDR'];
      //set default value for query to Google Book Search API 0307387941
      $query = isset($_POST['q']) ? $_POST['q'] : '0307387941';
      //set default value for search type to Google Book Search API
      $type = isset($_POST['type']) ? $_POST['type'] : 'all';
      //check and assign page of search results - are we on the first page?
      $start = isset($_POST['start']) ? $_POST['start'] : 1;
      //set default value for number of results
      $limit = isset($_POST['limit']) ? $_POST['limit'] : '10';
          
      switch ($type) {
            
        case 'all':
          $params = 'q='.urlencode($query).'&startIndex='.$start.'&maxResults='.$limit;
        break;
            
        case 'isbn':
    			$params = 'q=isbn:'.urlencode($query).'';
        break;
            
        case 'lccn':
    			$params ='q=lccn:'.urlencode($query).'';
        break;
            
        case 'oclc':
    			$params = 'q=oclc:'.urlencode($query).'';
        break;
            
        default:
          echo '<p>You must specify a search type such as "all" or "book". Check the url to make sure "type=" has a value.</p>';
          exit;
          }
      //set URL for the Google Book Search API
      $url = 'https://www.googleapis.com/books/v'.$v.'/volumes?key='.$key.'&'.$params.''; 
    
      if(isset($_POST['q'])):
      //build request and send to Google Ajax Search API
      $request = file_get_contents($url);
      //decode json object(s) out of response from Google Ajax Search API
      $data = json_decode($request,true);
      $totalItems = $data['totalItems']; 
    
      //Notes for changing popup header background color, title font, etc:
      //header background in "jquery-ui-1.10.4.custom.css", line 813 - also for header font
      //UI button is from line 196 to line 299, and line 827 to 841 - I think
      //on line 803 added a red border around the total popup window
      //make sure some results were returned, show results as html with result numbering and pagination  mainHeading
    	if ($totalItems > 0) {  ?>
          <!doctype html>
          <html lang="en">
          <head>
          <meta charset="utf-8">
          <title>jQuery UI Dialog - Default functionality</title>
          <link rel="stylesheet" href="//whosgotbooks.com/jquery/jquery-ui-1.10.4.custom.css">
          <script src="//whosgotbooks.com/jquery/jquery-1.10.2.js"></script>
          <script src="//whosgotbooks.com/jquery/jquery-ui-1.10.4.custom.js"></script>
          </head>
          <body>
          <div id="dialog" title="Google Books Search Results" style="display:none;">
          <?php   
                  $book_title = $item['volumeInfo']['title'];
          /* if(isset($_POST['book_title']))
            {
              $book_title = $_POST['book_title'];
             //loop through dataset in you case
              for($i=1;$i<=10;$i++)
              {
                    echo "Result Set $i<input type='submit' class='btn' value='Select'  id='select_$i'/><br/>";
              }
            } */ ?>
            <script>
          $(function() {
          $( "#dialog" ).dialog({
            height: 550, width: 450});
            $( ".btn" ).click(function(){
            //assign values to each variable from results on the server
            var title = <?php echo json_encode($book_title) ?>;
            var author = "<?php echo json_encode($book_author); ?>";
            var published = $("#returnvalues").val();
            var description = $("#returnvalues").val();
            var pages = $("#returnvalues").val();
            var publisher = $("#returnvalues").val();
            var ISBN = $("#returnvalues").val();
           //book_title = $item['volumeInfo']['title'];
           $.ajax({
             type: "POST",
             url: '/wp-content/plugins/book-search-google/book-meta.php',
             async:false,
             dataType: 'json',
             //assign values to the variables to be passed to the server via data
             data: { title : title, author : author, published : published, 
             description : description, pages : pages, publisher : publisher, ISBN : ISBN},
             success: function(data)
                 {
                 //alert(data);
                 alert(title);
                 //identify the variables for unique handing on the server side
                 $("input[name='bbp_topic_title']").val(data.title);
                 $("input[name='bbp_extra_field1']").val(data.author);
                 $("input[name='bbp_extra_field2']").val(data.published);
                 $("input[name='bbp_extra_field3']").val(data.description);
                 $("input[name='bbp_extra_field4']").val(data.pages);
                 $("input[name='bbp_extra_field5']").val(data.publisher);
                 $("input[name='bbp_extra_field6']").val(data.ISBN);
                 //$("#displayResults").html(data);
                 },
                 error: function(errorThrown){
                 alert('error');
                 }
                 });
          $( "#dialog" ).dialog( "close" );  
          });
          });
          </script>  
    		    <strong><p style="font-size: 16px; text-align: center";>Top 10 Results for &quot;<?php echo @$_POST['q']; ?>&quot;</p></strong>	
            <strong><p style="font-size: 14px; text-align: center";>choose a book to select as your topic</p></strong>&nbsp;
            <table style="width:400px">
            <col width="325">
            <col width="75">
    		    <?php $i=0; foreach ($data['items'] as $item) { $i++; ?>     
    		    	  <tr>
                <td>
    				       <strong><u><div style="font-size: 14px";><?php printf($item['volumeInfo']['title'])?></u></div></strong>
    					     <strong>Author: </strong><?php printf( $item['volumeInfo']['authors'][0])?><br />
    					     <strong>Published: </strong><?php printf( $item['volumeInfo']['publishedDate']); ?><br />					     
                   <strong>Page(s): </strong><?php printf( $item['volumeInfo']['pageCount']); ?><br />
    					     <strong>Publisher: </strong><?php printf( $item['volumeInfo']['publisher']); ?><br />
    					     <strong>Category: </strong><?php printf( strtolower($item['volumeInfo']['printType']).', '.strtolower($item['volumeInfo']['categories'][0])); ?>&nbsp;&nbsp;
                   <strong>ISBN: </strong><?php printf( $item['volumeInfo']['industryIdentifiers'][0]['identifier']); ?></td>
                <td><p><input type="submit" method="post" name="selectbook" value="Select" class="btn" id="returnvalues" /></p>
                <img src="<?php printf( rawurldecode($item['volumeInfo']['imageLinks']['smallThumbnail'])); ?>" />
    				    </td>
                <tr><td style="width:420px"><p><strong>Description: </strong><?php printf( $item['volumeInfo']['description']); ?><br /></p></td>
                <?php
                  //$book_title = $item['volumeInfo']['title'];      
                 ?>
    <script>
    var title = <?php echo json_encode($book_title); ?>;
    </script>       
                </tr>
                </tr>
    		        <?php } }
                else {
    		        ?>
    			       <p><strong>Sorry, there were no results</strong></p>
    		        <?php  }         ?>
            </table>
          </div>
          </body>
          </html>
              <?php
              else: //show form and allow the user to check for Google Book search results
              ?>
    
          <p><form id="searchForm" name="searchForm" method="post"> 
            <fieldset id="searchBox">
                <label>Search for a Book:</label>
                <input class="text" id="q" name="q" type="text" value="Powered by Google" onfocus="this.value=''; this.onfocus=null;" />
                <select id="type" name="type" size="1">
                    <option selected value="all">Book Title</option>
                    <option value="isbn">Books by ISBN</option>
                    <option value="lccn">Books by LCCN #</option>
                    <option value="oclc">Books by OCLC #</option>                
                </select>
                <input class="submit" id="searchForm" name="submit" type="submit" value="Search"  />
            </fieldset>
          </form></p>
          <?php
          //end submit isset if statement on line 73
          endif;
    
          echo $book_title;
    //}                   
    }
    Last edited by jerrysc; May 16 '14, 04:46 PM. Reason: Showing how to solve the issue I had - figured it out...
  • jerrysc
    New Member
    • May 2014
    • 2

    #2
    I figured this out! Anyone who is curious, I placed the javascript variable in a different script, which resides within the loop where the php results are displayed.

    Code:
    <script>
    var title = <?php echo json_encode($book_title); ?>;
    </script>
    I have also edited my answer above to show specifically where I placed this.

    Comment

    Working...