473,396 Members | 1,886 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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.

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. /* 
  3.         Plugin Name: Book Search Using Google API
  4.         Plugin URI: http://whosgotbooks.com/wp-content/plugins
  5.         Description: A plugin to get book information and display it in the bbpress topic meta. Find a book by entering the title.
  6.         Version: 1.0.0
  7.         Author: Jerry Caldwell
  8.         Author URI: http://whosgotbooks.com
  9.         License: Open Source 
  10.           */ 
  11.   //turn on full error reports for development purposes - should be turned off for production environment
  12. //error_reporting(E_ALL);
  13.   // shortcode for use in posts/pages
  14. //function book_search_google_shortcode() {                  
  15. //  book_search_google(); }
  16. //  add_shortcode( 'book-search-google', 'book_search_google_shortcode' );
  17. global $book_title;
  18.  
  19. function book_search_google () {    
  20.   //set API version for Google Book Search API
  21.   $v = isset($_POST['v']) ? $_POST['v'] : '1';
  22.   //set user API key for Google Book Search API
  23.   $key = isset($_POST['key']) ? $_POST['key'] : '';
  24.   //set user IP for Google Book Search API
  25.   //$ip = isset($_POST['ip']) ? $_POST['ip'] : $_SERVER['REMOTE_ADDR'];
  26.   //set default value for query to Google Book Search API 0307387941
  27.   $query = isset($_POST['q']) ? $_POST['q'] : '0307387941';
  28.   //set default value for search type to Google Book Search API
  29.   $type = isset($_POST['type']) ? $_POST['type'] : 'all';
  30.   //check and assign page of search results - are we on the first page?
  31.   $start = isset($_POST['start']) ? $_POST['start'] : 1;
  32.   //set default value for number of results
  33.   $limit = isset($_POST['limit']) ? $_POST['limit'] : '10';
  34.  
  35.   switch ($type) {
  36.  
  37.     case 'all':
  38.       $params = 'q='.urlencode($query).'&startIndex='.$start.'&maxResults='.$limit;
  39.     break;
  40.  
  41.     case 'isbn':
  42.             $params = 'q=isbn:'.urlencode($query).'';
  43.     break;
  44.  
  45.     case 'lccn':
  46.             $params ='q=lccn:'.urlencode($query).'';
  47.     break;
  48.  
  49.     case 'oclc':
  50.             $params = 'q=oclc:'.urlencode($query).'';
  51.     break;
  52.  
  53.     default:
  54.       echo '<p>You must specify a search type such as "all" or "book". Check the url to make sure "type=" has a value.</p>';
  55.       exit;
  56.       }
  57.   //set URL for the Google Book Search API
  58.   $url = 'https://www.googleapis.com/books/v'.$v.'/volumes?key='.$key.'&'.$params.''; 
  59.  
  60.   if(isset($_POST['q'])):
  61.   //build request and send to Google Ajax Search API
  62.   $request = file_get_contents($url);
  63.   //decode json object(s) out of response from Google Ajax Search API
  64.   $data = json_decode($request,true);
  65.   $totalItems = $data['totalItems']; 
  66.  
  67.   //Notes for changing popup header background color, title font, etc:
  68.   //header background in "jquery-ui-1.10.4.custom.css", line 813 - also for header font
  69.   //UI button is from line 196 to line 299, and line 827 to 841 - I think
  70.   //on line 803 added a red border around the total popup window
  71.   //make sure some results were returned, show results as html with result numbering and pagination  mainHeading
  72.     if ($totalItems > 0) {  ?>
  73.       <!doctype html>
  74.       <html lang="en">
  75.       <head>
  76.       <meta charset="utf-8">
  77.       <title>jQuery UI Dialog - Default functionality</title>
  78.       <link rel="stylesheet" href="//whosgotbooks.com/jquery/jquery-ui-1.10.4.custom.css">
  79.       <script src="//whosgotbooks.com/jquery/jquery-1.10.2.js"></script>
  80.       <script src="//whosgotbooks.com/jquery/jquery-ui-1.10.4.custom.js"></script>
  81.       </head>
  82.       <body>
  83.       <div id="dialog" title="Google Books Search Results" style="display:none;">
  84.       <?php   
  85.               $book_title = $item['volumeInfo']['title'];
  86.       /* if(isset($_POST['book_title']))
  87.         {
  88.           $book_title = $_POST['book_title'];
  89.          //loop through dataset in you case
  90.           for($i=1;$i<=10;$i++)
  91.           {
  92.                 echo "Result Set $i<input type='submit' class='btn' value='Select'  id='select_$i'/><br/>";
  93.           }
  94.         } */ ?>
  95.         <script>
  96.       $(function() {
  97.       $( "#dialog" ).dialog({
  98.         height: 550, width: 450});
  99.         $( ".btn" ).click(function(){
  100.         //assign values to each variable from results on the server
  101.         var title = <?php echo json_encode($book_title) ?>;
  102.         var author = "<?php echo json_encode($book_author); ?>";
  103.         var published = $("#returnvalues").val();
  104.         var description = $("#returnvalues").val();
  105.         var pages = $("#returnvalues").val();
  106.         var publisher = $("#returnvalues").val();
  107.         var ISBN = $("#returnvalues").val();
  108.        //book_title = $item['volumeInfo']['title'];
  109.        $.ajax({
  110.          type: "POST",
  111.          url: '/wp-content/plugins/book-search-google/book-meta.php',
  112.          async:false,
  113.          dataType: 'json',
  114.          //assign values to the variables to be passed to the server via data
  115.          data: { title : title, author : author, published : published, 
  116.          description : description, pages : pages, publisher : publisher, ISBN : ISBN},
  117.          success: function(data)
  118.              {
  119.              //alert(data);
  120.              alert(title);
  121.              //identify the variables for unique handing on the server side
  122.              $("input[name='bbp_topic_title']").val(data.title);
  123.              $("input[name='bbp_extra_field1']").val(data.author);
  124.              $("input[name='bbp_extra_field2']").val(data.published);
  125.              $("input[name='bbp_extra_field3']").val(data.description);
  126.              $("input[name='bbp_extra_field4']").val(data.pages);
  127.              $("input[name='bbp_extra_field5']").val(data.publisher);
  128.              $("input[name='bbp_extra_field6']").val(data.ISBN);
  129.              //$("#displayResults").html(data);
  130.              },
  131.              error: function(errorThrown){
  132.              alert('error');
  133.              }
  134.              });
  135.       $( "#dialog" ).dialog( "close" );  
  136.       });
  137.       });
  138.       </script>  
  139.             <strong><p style="font-size: 16px; text-align: center";>Top 10 Results for &quot;<?php echo @$_POST['q']; ?>&quot;</p></strong>    
  140.         <strong><p style="font-size: 14px; text-align: center";>choose a book to select as your topic</p></strong>&nbsp;
  141.         <table style="width:400px">
  142.         <col width="325">
  143.         <col width="75">
  144.             <?php $i=0; foreach ($data['items'] as $item) { $i++; ?>     
  145.                   <tr>
  146.             <td>
  147.                        <strong><u><div style="font-size: 14px";><?php printf($item['volumeInfo']['title'])?></u></div></strong>
  148.                          <strong>Author: </strong><?php printf( $item['volumeInfo']['authors'][0])?><br />
  149.                          <strong>Published: </strong><?php printf( $item['volumeInfo']['publishedDate']); ?><br />                         
  150.                <strong>Page(s): </strong><?php printf( $item['volumeInfo']['pageCount']); ?><br />
  151.                          <strong>Publisher: </strong><?php printf( $item['volumeInfo']['publisher']); ?><br />
  152.                          <strong>Category: </strong><?php printf( strtolower($item['volumeInfo']['printType']).', '.strtolower($item['volumeInfo']['categories'][0])); ?>&nbsp;&nbsp;
  153.                <strong>ISBN: </strong><?php printf( $item['volumeInfo']['industryIdentifiers'][0]['identifier']); ?></td>
  154.             <td><p><input type="submit" method="post" name="selectbook" value="Select" class="btn" id="returnvalues" /></p>
  155.             <img src="<?php printf( rawurldecode($item['volumeInfo']['imageLinks']['smallThumbnail'])); ?>" />
  156.                     </td>
  157.             <tr><td style="width:420px"><p><strong>Description: </strong><?php printf( $item['volumeInfo']['description']); ?><br /></p></td>
  158.             <?php
  159.               //$book_title = $item['volumeInfo']['title'];      
  160.              ?>
  161. <script>
  162. var title = <?php echo json_encode($book_title); ?>;
  163. </script>       
  164.             </tr>
  165.             </tr>
  166.                 <?php } }
  167.             else {
  168.                 ?>
  169.                    <p><strong>Sorry, there were no results</strong></p>
  170.                 <?php  }         ?>
  171.         </table>
  172.       </div>
  173.       </body>
  174.       </html>
  175.           <?php
  176.           else: //show form and allow the user to check for Google Book search results
  177.           ?>
  178.  
  179.       <p><form id="searchForm" name="searchForm" method="post"> 
  180.         <fieldset id="searchBox">
  181.             <label>Search for a Book:</label>
  182.             <input class="text" id="q" name="q" type="text" value="Powered by Google" onfocus="this.value=''; this.onfocus=null;" />
  183.             <select id="type" name="type" size="1">
  184.                 <option selected value="all">Book Title</option>
  185.                 <option value="isbn">Books by ISBN</option>
  186.                 <option value="lccn">Books by LCCN #</option>
  187.                 <option value="oclc">Books by OCLC #</option>                
  188.             </select>
  189.             <input class="submit" id="searchForm" name="submit" type="submit" value="Search"  />
  190.         </fieldset>
  191.       </form></p>
  192.       <?php
  193.       //end submit isset if statement on line 73
  194.       endif;
  195.  
  196.       echo $book_title;
  197. //}                   
  198. }
  199.  
May 16 '14 #1
1 1864
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.

Expand|Select|Wrap|Line Numbers
  1. <script>
  2. var title = <?php echo json_encode($book_title); ?>;
  3. </script>
  4.  
I have also edited my answer above to show specifically where I placed this.
May 16 '14 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: OM | last post by:
I need a simple Javascript shopping cart. I did a few searches on Yahoo... And got a few results of free Javascript shopping carts. The problem is there tooo complicated and very hard to...
1
by: Stefano | last post by:
Posted: Fri Jan 23, 2004 3:59 pm Post subject: Variable Javascript -------------------------------------------------------------------------------- Hi all, i have a problem with...
9
by: Max | last post by:
I'm new with Javascript and can't seem to figure out what I'm doing wrong here as I'm not able to pass a simple variable to a function. In the head of doc I have: <script...
5
by: Paul | last post by:
Just wondering if someone could provide an example of passing a variable from the code behind to javascript in vb. I want to have one control have focus with the page loading with one condition...
8
by: JJ | last post by:
Whats the best way to pass a variable from a popup to the current page (without a postback on the current page). I have a form on 'page1' with various text input boxes. One box contains an image...
2
by: sorobor | last post by:
dear sir .. i am using cakephp freamwork ..By the way i m begener in php and javascript .. My probs r bellow I made a javascript calender ..there is a close button ..when i press close button...
2
polymorphic
by: polymorphic | last post by:
I am no longer good at Javascript and need help. I'm trying to embed pdf files in html then build some sort of navigation between the pdfs via the pdf numbered file name. I can generate the...
1
by: madhusudangosula | last post by:
I need onchange in javascript for two dropdown list.. I have two dropdown list 1.Activity Type 2.Category At present both are independent to each other... Now the thing is i need to map...
3
by: JJ | last post by:
I am using a handler (processImage.ashx) to display an image. The image is displayed according to parameters passed in the querystring. The handerl is called via some clientside javascript. I...
5
by: aelred | last post by:
I have a web page where a member can open up a chat window (child window) with another member. - From there the member can also navigate to other web pages. - From other pages in the site, they...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.