From PHP to JSP for a search-responder.php

I have been asked to use the "search-as-you-type" solution offered up by Google at [http://code.google.com/p/search-as-you-type/|http://code.google.com/p/search-as-you-type/]. The documentation offered by Google is pretty much straight forward but of course the actual piece of code that gets the data is built in PHP and my client needs this to be used on a page serving up JSP.
I am learning JSP and moving from PHP and ASP and learning quickly but not quick enough to finish the project.
Would anyone be able and willing to help me convert the functions in the following PHP code into JSP?
Thanks in advance to anyone who takes the time to help me.
<?php
* Copyright (C) 2006 Google Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*      http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Search-as-you-type sample Ajax responder
  // Adding a cache control so that browsers won't cache Ajax requests
  header("Cache-Control: no-cache");
  header("Content-Type: text/html; charset=UTF-8");
   * Get the sample data from the text file.
   * @return array Loaded data
  function GetData() {
    $data = array();
    $file = file("test-data.txt");
    foreach($file as $record) {
      $record = explode("|", trim($record));
      if (count($record) == 4) { // Ignore invalid lines
        $data[] = $record;
    return $data;
   * Get the results based on user's query.
   * @param string $query Query
   * @param array $data Sample data
   * @return array Result array
  function GetResults($query, $data) {
    $results = array();
    $queryLength = strlen($query);
    foreach ($data as $record) {
      if (substr(strtolower($record[0]), 0, $queryLength) == $query) {
        $result = array();
        $result['name'] = $record[0];
        $result['type'] = $record[1];
        $result['content'] = $record[2];
        $result['moreDetailsUrl'] = $record[3];
        $result['style'] =
          ($query == strtolower($record[0])) ? 'expanded' : 'normal';
        $results[] = $result;
    return $results;
  // Get the data and the query
  $data = GetData();
  $query = strtolower(ltrim($_GET['query']));
  // Build response
  $response = array();
  $response['query'] = $query;
  $response['results'] = GetResults($query, $data);
  if (count($response['results']) == 1) {
    $response['autocompletedQuery'] = $response['results'][0]['name'];
  // Output response
  echo "searchAsYouType.handleAjaxResponse(";
  echo json_encode($response);
  echo ");";
?>

Thanks for your comment Gimbal2.
I have already been thoroughly surprised at how different JSP is from PHP. I am finding quite hard to wrap my head around the whole process to be honest.
I am beginning to see that JSP and PHP work in a totally different way than each other.
I am not technically trying to translate or convert the PHP file as much as I am trying to build a file in JSP that does the same functions. The main functions of the PHP script are commented by Google and should be easily enough re-written in JSP in order to produce similar results.
Since the output needs to be in a JSON format when passed to the .js file you'd think this would be better suited as a .jsp file as well or even a JAVA Applet, Servlet or even a bean. Since the whole site is already built in JSP for a multitude of other functions it seems likely that adding on more to read data from a source file and send it back to the .JS would be straight forward, but I could be wrong. But again I am not familiar enough with JAVA or JSP (yet) to make heads or tails of this.
1. // Adding a cache control so that browsers won't cache Ajax requests
2. * Get the sample data from the text file. @return array Loaded data
3. * Get the results based on user's query.
* @param string $query Query
* @param array $data Sample data
* @return array Result array
4. // Get the data and the query
5. // Build response
6. // Output response

Similar Messages

  • Flash Builder 4.5 for PHP - show variable from PHP in app

    I have searched for hours and I can't figure this out…
    Is there a way to somehow "echo" my PHP code in my MXML file ?
    I know you can't echo something from PHP to MXML, so here's what I have done :
    I get my informations from my database, I need to show an image and its title, so I put the following code in a variable :
    <mx:Image id="laniraBlanche" x="25" y="65" width="210" height="126" source="'.$row->image_mini.'" click="selectLaniraBlanche()" rollOver="seePicture()" rollOut="outPicture()" />                                              <s:Label x="25" y="155.85" text="'.$row->nom.'" width="210" textAlign="center" height="37" fontSize="19" backgroundColor="#676666" verticalAlign="middle" fontFamily="Georgia" color="#FFFFFF" click="selectLaniraBlanche()" rollOver="seePicture()"  id="laniraBlancheTxt" rollOut="outPicture()" />'
    Then, I return that variable.
    I find the function where my var created is returned from the "Data/Service" tab, I am on Design mode on Flash Builder, and I "drop" my function where I want my image and text to show on my app.
    I tryed dropping it in a "group", it doesn't show anything. I tryed several other options, and nothing worked.
    So my question is, how could I have this code created in PHP show on my application ?
    Thank you  for your help

    I also have Flash Builder 4.5 for PHP and the ANT view does not show when going to Window -> Show View --> Other.  I could not find it in any of the folders.
    However, I was able to add it by hitting Command 3 (CTRL 3 on PC) and typing Ant.

  • How to get values from a table(in jsp) for validation using javascript.

    hi,
    this is praveen,pls tell me the procedure to get values from a table(in jsp) for validation using javascript.
    thank you in advance.

    Yes i did try the same ..
    BEGIN
    select PROD_tYPE into :P185_OFF_CITY from
    magcrm_setup where atype = 'CITY' ;
    :p185_OFF_CITY := 'XXX';
    insert into mtest values ('inside foolter');
    END;
    When i checked the mtest table it shos me the row inserted...
    inside foolter .. Now this means everything did get execute properly
    But still the vallue of off_city is null or emtpy...
    i check the filed and still its empty..
    while mtest had those records..seems like some process is cleaining the values...but cant see such process...
    a bit confused..here..I tried on Load after footer...
    tried chaning the squence number of process ..but still it doesnt help
    some how the session variables gets changed...and it is changed to empty
    Edited by: pauljohny on Jan 3, 2012 2:01 AM
    Edited by: pauljohny on Jan 3, 2012 2:03 AM

  • When i want to go another from a tab,it shows firefox not responding, for a while then opens that tab!this is embarrassing me a lot by taking so much time!!why

    I have two inconviniences with fire fox..
    1)when i want to go another from a tab,it shows firefox not responding, for a while then opens that tab!this is embarrassing me a lot by taking so much time!!why it happens?
    2) every time when adobe flash player is updated, it shows flash player can't be installed and it crashes! it says 'disable real player' though i never installed real player!!
    plz Let me know why it happens to me????

    1. Update firefox to the latest version 2. and disable real player in menu->addons->plugins.
    Recent crashes of certain multimedia contents (this includes Youtube videos, certain flash games and other applications) in conjunction with Firefox 13 are most probably caused by a recent Flash 11.3 update and/or a malfunctioning Real Player browser plugin.
    In order to remedy the problem, please perform the steps mentioned in these Knowledge Base articles:
    [[Flash Plugin - Keep it up to date and troubleshoot problems]]
    [[Flash 11.3 crashes]]
    [[Flash 11.3 doesn't load video in Firefox]]
    Other, more technical information about these issues can be found under these Links:
    http://forums.adobe.com/thread/1018071?tstart=0
    http://blogs.adobe.com/asset/2012/06/inside-flash-player-protected-mode-for-firefox.html
    Please tell us if this helped!
    Please check if all your plugins are up-to-date. To do this, go to the [http://mozilla.com/plugincheck Mozilla Plugin Check site].
    Once you're there, the site will check if all your plugins have the latest versions.
    If you see plugins in the list that have a yellow ''Update'' button or a red ''Update now'' button, please update these immediately.
    To do so, please click each red or yellow button. Then you should see a site that allows you to download the latest version. Double-click the downloaded file to start the installation and follow the steps mentioned in the installation procedure.

  • How to construct table in jsp for the resultset from helper class

    Hi Dudes!!!
    Want to construct table in jsp for the resultset, but the resultset are retrieved at the helper class.I constructed Table in Helper class Using StringBuffer and return it as string from the helper class.Is their any other feasible and efficient way to construct table in Jsp for the resultset from Helper class.Solution will be highly appreciated.Thanx in Advance.

    no, we can't.
    Certainly noone can with such vague specifications even if they had the intent to do so.
    "the computer", which computer?
    "attach to our current page", what is meant by that?
    And noone should ever help you if you're planning to breach security anywhere.

  • When I am searching for any particular song or album from my shared ITUNES folder, the search is conducted  in the apple store and not on the shared library. How to search for the song in the shared library

    I am using IPAD Mini.When I am searching for any particular song or album from my shared ITUNES folder, the search is conducted  in the apple store and not on the shared library. How to search for the song in the shared library

    Search for shared library is impossible, as far as I know.  Searches supported - are local and internet.

  • Can we write query for fomatted search without from clause

    can we write query for fomatted search without from clause as below.
    SELECT (($(u_amt)*14)/100)
    here U_amt is a UDF .I want to assign this to another field .
    Rgds,
    Rajeev

    Hi Rajeev,
    You can write query for FMS without from.  That is because you can omit it when you get value from active form by default.  The grammar of it is:
    Select $[$38.u_amt.0\] * 14/100 in your case if you have item type marketing document @line level.
    From View-System Information, you can get the info you need for your FMS query at the left bottom of your screen.
    Thanks,
    Gordon

  • I have an icon thats appeared in finder ..i don't know where its come from and what its for. It doesn't  respond in any way when I click it.How do I get rid  of it?

    I have an icon thats appeared in finder ..i don't know where its come from and what its for. It doesn't  respond in any way when I click it.How do I get rid  of it?

    I can't select it .. I click on it and nothing happens. The only thing I seem to be able to do is a two fingered click which brings up a context menu for the side bar preferences..but unfortunately this icon does not appear in the list.

  • Ive gotten 3 responses from you guys. But still no help. Can't believe it's taken this long for apple to respond to this issue and I'm very disappointed that all I did was take precaution from left to my account info and my account has been disabled since

    Ive gotten 3 responses from you guys. But still no help. Can't believe it's taken this long for apple to respond to this issue and I'm very disappointed that all I did was take precaution from left to my account info and my account has been disabled since. Sad that we can't do any updates to equipment I've spent so much money in. Hope this is resolved real soon.

    Who exactly are you addressing this post to? And what exactly are you posting? We are just users like you, and have no idea what you are referring to. If there is something you would like to ask - user to user - please do so. Otherwise, you are wasting your time complaining about Apple, since we are not Apple.
    GB

  • How to change the browser used for Google search from context menu of selected text?

    How to change the browser used for Google search from context menu of selected text?
    It uses Safari. But I want to use Chrome (it's my default browser).

    How to change the browser used for Google search from context menu of selected text?
    It uses Safari. But I want to use Chrome (it's my default browser).

  • How can I use 1 JSP for edit/create functionality?

    Hi All,
    Does anybody have an example of using one JSP for both editing and creating an object? I am pretty sure I can handle most of it, but am not sure about how I can specify different messages from the resource bundle (i.e. modifying the screen title for the different uses, "New Campaign" vs. "Edit Campaign").
    My background is in PHP and DHTML (i.e. more front-end) and I'm just starting with Java and JSF. As such, I want to be sure that I'm using appropriate patterns for my programming.
    Thank you in advance for any help,
    Matt

    I make the difference between modifying an existing object and a new one by the ID in the object. Each object has a unique ID in my app assigned by the database. So if the ID is 0, the user is creating a new object, not stored in the DB yet. I store the object to be edited/modified in the session before displaying the page:
    For the title:
    <h:outputText value="Edit Material" rendered="#{sessionScope.selectedMaterial.materialId != 0}"/>
    <h:outputText value="New Material" rendered="#{sessionScope.selectedMaterial.materialId == 0}"/>For the action buttons:
    <h:commandButton value="Update Material" action="#{MaterialControllerBean.updateMaterial}" rendered="#{sessionScope.selectedMaterial.materialId != 0}"/>
    <h:commandButton value="Create Material" action="#{MaterialControllerBean.createMaterial}" rendered="#{sessionScope.selectedMaterial.materialId == 0}"/>

  • Webserver 7.0.9 make SOAP calls from PHP

    Hi,
    Making SOAP calls from PHP code uses opensll lib.
    On a windows server you should use : extension=php_openssl.dll in the php.ini file
    I tested it with a Ubuntu server using apache 2.2 , soap call is working from php code
    On Solaris 10 using iplanet 7.0.9 we have the following error : (see below)
    Does someone knows how to enable ?
    Thx , Ivan
    [27/Dec/2010:12:16:04] failure ( 7143): for host 10.66.10.46 trying to GET /ciscowebdialer/dialer.php?line=4012&destination=4014&deviceName=SEP002699EDDAE2, responder-fastcgi reports: FCGI1080: application error: PHP Notice: SoapClient::SoapClient() [function.SoapClient-SoapClient]: Unable to find the wrapper &quot;https&quot; - did you forget to enable it when you configured PHP? in /opt/oracle/webserver7/https-sol8/web-app/sol8/ciscowebdialer/dialer.php on line 6
    PHP Warning: SoapClient::SoapClient() [function.SoapClient-SoapClient]: I/O warning : failed to load external entity &quot;https://10.32.122.254:8443/webdialer/services/WebdialerSoapService?wsdl&quot; in /opt/oracle/webserver7/https-sol8/web-app/sol8/ciscowebdialer/dialer.php on line 6
    PHP Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://10.32.122.254:8443/webdialer/services/WebdialerSoapService?wsdl' in /opt/oracle/webserver7/https-sol8/web-app/sol8/ciscowebdialer/dialer.php on line 6
    PHP Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://10.32.122.254:8443/webdialer/services/WebdialerSoapService?wsdl' in /opt/oracle/webserver7/https-sol8/web-app/sol8/ciscowebdialer/dialer.php:6
    Stack trace:
    #0 /opt/oracle/webserver7/https-sol8/web-app/sol8/ciscowebdialer/dialer.php(6): SoapClient->SoapClient('https://10.32.1...', Array)
    #1 /opt/oracle/webserver7/https-sol8/web-app/sol8/ciscowebdialer/dialer.php(31): MakeCall('4012', '4014', 'SEP002699EDDAE2')
    #2 {main}
    thrown in /opt/oracle/webserver7/https-sol8/web-app/sol8/ciscowebdialer/dialer.php on line 6

    did you compile php by yourselves ? if yes, did you compile it with openssl support ? pl. make sure it is the case by running a simple script echoing phpinfo() .
    - sriram

  • After effects films automatic build from php databank

    hello,
    do everyone have a idea to make many films automaticly from an folder with many article-pictures and a text from php databank?!
    for example,
    i have many hundreds article and article-pictures and i would have for youtube for everyone of the article a single film in form of a diashow.
    one film have i build with after effects, but how can i now change the pictures and text automaticly to make films
    for the other articles?!
    thanks for your answers
    greets montihh

    You can write a script or search for one that automates slideshows from an image foler. You can also write a script or search for one that turns comma delimited text files into text layers. I use a script to create lower 1/3's .
    You can't directly go from a PHP page to text or image layers in After Effects, but you can go, very easily with the right script, from a file folder full of stills to and a text file with your copy to an animated slide show with titles. I'm not sure that it would be any more interesting than a slideshow made with iPhoto or any of the web based or Windows versions of auto slide show creation tools.

  • Returning ResultSet from servlet to jsp - java.lang.NullPointerException

    Hey all, i've been stuck on this for too long now...just trying to return a ResultSet from a servlet to jsp page.
    Had a bunch of problems earlier...which i think were fixed but...now i get a "java.lang.NullPointerException" in my jsp page when i try to get elements from the ResultSet object.
    Here is the latest version of my code:
    Servlet:
    String QueryStr="select ProdName from products";
    Statement stmt=conn.createStatement();
    rs=stmt.executeQuery(QueryStr); //get resultset
    sbean.setInventory(rs); //set ResultSet in bean
    req.getSession(true).setAttribute("s_resbean",sbean); //create session/request variable, set to bean
    Bean:
    package beans;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.sql.*;
    import javax.sql.*;
    public class SearchBean extends HttpServlet{
         private int searchFlag=0;
         private ResultSet inventory;
         public SearchBean(){
         public int getSearchFlag(){
         return searchFlag;
         public ResultSet getInventory(){
              return inventory;
         public void setInventory(ResultSet rs){
              this.inventory=rs;
         public void setSearchFlag(){
              this.searchFlag=1;
    jsp:
    <%@ page language="java" import="java.lang.*,java.sql.*,javax.sql.*,PopLists.PopInvLists,beans.SearchBean"%>
    <jsp:useBean scope="session" id="s_resbean" class="beans.SearchBean" />
    <% ResultSet categories=PopInvLists.getCat();
    ResultSet manuf=PopInvLists.getManuf();
    ResultSet supplier=PopInvLists.getSupplier();
    ResultSet cars=PopInvLists.getCars();
    ResultSet search=(ResultSet)request.getAttribute("s_resbean");
    %>
    <%     while(search.next()){
         String pname=search.getString("ProdName");
    %>
    It craps out when i try to loop through the "search" ResultSet.
    I can loop through the rest of the ResultSets no problem....just this one doesn't work because it's set in a servlet, not a simple java class.
    Just to clarify, i am populating some dropdown lists on entry to the screen, which the user will use to perform a search. Once the search btn is clicked, the servlet is called, gets the request info for the search, performs search, and returns the resultset to the original screen. I want to eventually display the result under the search criteria.
    Someone....Please Please please tell me how to get this working...it should be very simple, but i just can't get it to work.
    Thanks in advance,
    Aditya

    req.getSession(true).setAttribute("s_resbean",sbean); //create session/request variable, set to beanHere you add an attribute to the session.
    ResultSet search=(ResultSet)request.getAttribute("s_resbean");Here you try to get the attribute from the request. Naturally it isn't there because you added it to the session, not the request. Despite your comment in the first line of code, a session is not a request. And vice versa.

  • What incorrect syntax found in this query for dynamic search

    I make this stored procedure for dynamic search by date from date to employee no employee name
    but it give me error why
    Create proc CollectsearchData15
    @StartDate datetime,
    @EndDate datetime,
    @EmployeeID NVARCHAR(50),
    @EmployeeName nvarchar(50)
    as
    Begin
    DECLARE @SQLQuery as nvarchar(max)
    SET @SQLQuery = N'SELECT * from ViewEmployeeTest Where (1=1)'
    If @StartDate Is Not Null
    SET @SQLQuery = @SQLQuery + N' And (joindate >= @StartDate)'
    If @EndDate Is Not Null
    SET @SQLQuery = @SQLQuery + N' And (joindate <= @EndDate)'
    If @EmployeeID Is Not Null And @EmployeeID != ''
    SET @SQLQuery = @SQLQuery + N' And (EmployeeID = @EmployeeID)'
    If @EmployeeName Is Not Null And @EmployeeName != ''
    SET @SQLQuery = @SQLQuery + N' And (DriverName Like ''%'' + @EmployeeName + ''%'')'
    Print @SQLQuery;
    Exec sp_executesql @SQLQuery,
    N'@StartDate datetime, @EndDate datetime, @EmployeeID nvarchar(50), @EmployeeName nvarchar(50)',
    @StartDate, @EndDate, @EmployeeID, @EmployeeName;
    but it give me this error why
    Msg 102, Level 15, State 1, Procedure CollectsearchData15, Line 28
    Incorrect syntax near ';'.

    I think you are missing an END. Perhaps with no dynamic sql :
    SELECT * from ViewEmployeeTest
    WHERE
    (joindate >= @StartDate OR @StartDate IS NULL)
    AND
    (joindate <= @EndDate OR @EndDate IS NULL)
    AND
    (EmployeeID = @EmployeeID OR @EmployeeID IS NULL)
    AND
    (DriverName Like '%' + @EmployeeName + '%' OR @EmployeeName IS NULL)
    Thanks and regards, Rishabh K
    Please keep in mind that this might cause proc to generate bad plans
    http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Maybe you are looking for