Link to home
Start Free TrialLog in
Avatar of saad220
saad220Flag for Germany

asked on

java script onChange

i have some php counter..

what i want is when dropdown list select...how could i display the search result on the page using ajax and onChange event???

i have the search function, count function...the only problem i faced is that...how could i manage to put them together with ajax to get the result live.

see example here if u want..

http://en.comparis.ch/Carfinder/marktplatz/result.aspx?marcode=0&origin=headline#AdjustSearch

please select price or car model u will see the count result update instantlly..how could i achieve that???...

some has idea please??
search function..
 
function searchAll()
{
 
//base sql
  $sql = "select * from produkt_finder_table where 1 ";
 
//get the values from the form
//NOTE: You should do way more valdation on the values before you attempt to process anything
 
 
  if ((!empty($_POST['Bauform_d']))&&($_POST['Bauform_d'] != 'all'))
  {
    $sql .= " and Bauform_d like '". addslashes($_POST['Bauform_d'])."%' ";
  }
 
 
 
  //run query
  $result = conn($sql);
 
  if (!$result){ die("No results due to database error.<br>".mysql_error());  }
 
  if (mysql_num_rows($result)==0)
  {
    echo "No Results found!";
  }else{
 
    echo "<table border='1'><th>Cuenta</th><th>idclase</th><th>Enumber</th></tr>";
   
    while ($rows= mysql_fetch_array($result))
    {
      echo "<tr>";
	  echo "<td>";
	   echo "<ul>";
echo "<li class='addResult'><img src='{imag}' alt='' /><span class='red'>".$rows['Bauform_d']."<br /><span class='black'>".$rows['ArtikelName']."</span></span> <a href='#'>More Info</a> </li>";
echo "</ul>";
"</td>";
      /*echo "<td>". $rows['Bauform_d']  ."</td>";
      echo "<td>". $rows['Beschreibung_d'] ."</td>";
	  echo "<td>". $rows['ArtikelE_NO'] ."</td>";
      echo "</tr>";
      */
    } 
    echo "</table>";
  }//end if
 
 
 
}//end func
 
 
dropdown create function
 
function dropdown($field, $table)
{ 
  //initialize variables
  $oHTML  = '';
  $result = '';
 
  //check to see if the field is passed correctly
  if (($field == "")||($table == ""))
  {
    die("No column or table specified to create drop down from!");
  }
 
  $sql = "select distinct($field) from $table";
 
  //call the db function and run the query
  $result = conn($sql);
 
  //if no results are found to create a drop down return a textbox
  if ((!$result) ||(mysql_num_rows($result)==0))
  {
    $oHTML .= "<input type='text' name='$field' value='' size='15'>";
  }elseif (($result)&&(mysql_num_rows($result)>0)){
   
    //build the select box out of the results
    $oHTML .= "<select name='$field'>\n<option value='all' onChange='updateCount();'>All</option>\n";
    while ($rows = mysql_fetch_array($result))
    {
      $oHTML .= "<option value='".$rows[$field]."'>".$rows[$field]."</option>\n";
    }
    $oHTML .= "</select>\n";
  }
 
  //send the value back to the calling code
  return $oHTML;
}//end function
 
 
count function..
 
function countResult(){
 
 $sql2 = "select * from produkt_finder_table where 1 ";
 
  
 
  if ((!empty($_POST['Bauform_d']))&&($_POST['Bauform_d'] != 'all'))
  {
    $sql2 .= " and Bauform_d like '". addslashes($_POST['Bauform_d'])."%' ";
  }
  
  
 
  if ((!empty($_POST['Beschreibung_d']))&&($_POST['Beschreibung_d'] != 'all'))
  {
    $sql2 .= " and Beschreibung_d like '". addslashes($_POST['Beschreibung_d'])."%' ";
  }
 
$result = conn($sql2);
  //run query
 
  if (!$result){ die("No results due to database error.<br>".mysql_error());  }
 
  if (mysql_num_rows($result)==0)
  {
    echo "0";
  }else{
 
    echo mysql_num_rows($result);
}
}

Open in new window

Avatar of JurgenvH
JurgenvH
Flag of Netherlands image

http://java.sun.com/developer/technicalArticles/J2EE/AJAX/

This explains how Ajax works. Once you get the idea, it shouldn't be hard to integrate with your site.
Avatar of saad220

ASKER

that is for, java script code...is there some other tutorials how could call php function.?
here some functions.
create ajax function
unique string function  (for no caching)
onChange run the code  doSearch
  (params are parameters  like 'a=1&b=2&c=3'

handleResult to wrote result into DIV such that you got from PHP...



function createRequestObject() {
/*
var xmlHttp;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      try
        {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
        alert("browser not supported!");
        return false;
        }
      }
    }
        return xmlHttp;
        */
var xmlHttp;
try {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
}
  catch (e) {
  // Internet Explorer
  try {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
    catch (e) {
      try {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {
        alert(browser not support ajax");
        return false;
      }
   }
  }
  return xmlHttp;
}
var http1 = createRequestObject();
function UniqueString(){
     var mydate = new Date;
     var myday = mydate.getDate();
     var mymonth = mydate.getMonth()+1;
     var myyear = ((mydate.getYear() < 100) ? "19" : "") + mydate.getYear();
     var myyear = myyear.substring(2,4);
     var myhour = mydate.getHours();
     var myminutes = mydate.getMinutes();
     var myseconds = mydate.getSeconds();
     if(myday < 10) myday = "0" + myday;
     if(mymonth < 10) mymonth = "0" + mymonth;
     if(myhour < 10) myhour = "0" + myhour;
     if(myminutes < 10) myminutes = "0" + myminutes;
     if(myseconds < 10) myseconds = "0" + myseconds;
     var datearray = new Array(mymonth,myday,myyear,myhour,myminutes,myseconds);
     var uniq = "";
     for(i=0;i<datearray.length;i++){
          for(z=0;z<2;z++){
               var which = Math.round(Math.random()*1);
                    x = String.fromCharCode(64 + (Math.round(Math.random()*25)+1));
               }
               else{
                    x = String.fromCharCode(47 + (Math.round(Math.random()*9)+1));
               }
               uniq += x;
          }
          uniq += datearray[i];
     }
return uniq;
}
 
function doSearch(params) {
var d = UniqueString();
 
                http1.open(httpMethod,myPHPfile.php+'?ut='+d+'&'+params);
                http1.onreadystatechange = handleResult;
                http1.send(null);
}
function handleResult() {
        var Obj = document.getElementById('MY_DIV_OBJECT');
        if (http1.readyState == 4) { //Finished loading the response
                if (http1.status == 200) {
                        var response = http1.responseText;
Obj.innerHTML = response;
                }
        }
}
 
<body>
........
<DIV id="MY_DOV_OBJECT"></DIV>

Open in new window

or if you don't want to use ajax/js calls.

try old style. (not recommended)

you should change the result of your DIV again by ising
top.document.getElementById('MY_DIV_NAME').innerHTML = '';

this is by using iframe,  but you may have several  special chars problems.

<IFRAME ID="my_iframe" name="my_iframe" SRC="myHiddenPHP.php"  FRAMEBORDER=0 WIDTH=0 height=0></IFRAME>
 
<form action="myHiddenPHP.php" target="my_iframe">
--------
</form>

Open in new window

Avatar of saad220

ASKER

thanks boss, i am on way..but still abit of confusion here..

function doSearch(params) {
var d = UniqueString();
 
                http1.open(httpMethod,test2_3.php+'countResult()='+d+'&'+params);
                http1.onreadystatechange = handleResult;
                http1.send(null);
}
function handleResult() {
        var Obj = document.getElementById('countR');
        if (http1.readyState == 4) { //Finished loading the response
                if (http1.status == 200) {
                        var response = http1.responseText;
Obj.innerHTML = response;
                }
        }

is thi correct..

i mean i have countResult() function in side file called test2_3.php...how could i manage it here..
this file is from other index.php file not from the same file countResult reside.

by the way i will put the point to 500, if helped me much.
thanks.
what you want is something like this:

http://extjs.com/deploy/dev/examples/form/forum-search.html

I think.

let me unserstand correctly.

You have a SELECT BOX and DIV to show results.
DIV content will be changed with respect to selected Item and results will be shown, i.e. 10 per page

Note that be carefull about your count function. You don't really need to call it.
you may use it inside test_2.3.php

I mean,  in your PHP. First find the total result (count it)
Then show first 10,20,30 whatever you want.

Then for next pages call the function
doSearch('s=+$GET[s]&p=$pageNumber');

$pageNumber is  $_POST[p]+1 if == your total then 0




js functions you need:
 
createRequestObject() 
 
UniqueString()  // mentioned above.
 
 
function doSearch(params) {
var d = UniqueString();
              http1.open('GET',test2_3.php+'?ut='+d+'&'+params);
               http1.onreadystatechange = handleResult;
               http1.send(null);
}
function handleResult() {
       var Obj = document.getElementById('countR');
       if (http1.readyState == 4) { //Finished loading the response
               if (http1.status == 200) {
                       var response = http1.responseText;
                       Obj.innerHTML = response;
               }
       }
}
 
<BODY>
<form method="GET" action="" onSubmit="return false">
<select name="selectItem" onChange="doSearch('s='+this.options[this.selectedIndex].value+'p=0');">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
</form>
<div id="myResults"></div>

Open in new window

and in fact,

you can write several functions to do several things like doSearch



function doCount(params) {  // params is  itemID=1521 for example.
var d = UniqueString();
              http1.open('GET','test2_3.php+'?ut='+d+'&'+params,true);
               http1.onreadystatechange = handleResult2;
               http1.send(null);
}
function handleResult2() {
       var Obj = document.getElementById('countR');
       if (http1.readyState == 4) { //Finished loading the response
               if (http1.status == 200) {
                       var response = http1.responseText;
                       Obj.innerHTML = response;
                       // or if you return JS code  try   eval(response);    to run it.
               }
       }
}

Open in new window

sorry code has  errors.


http1.open('GET','test2_3.php?ut='+d+'&'+params,true);

Open in new window

Avatar of saad220

ASKER

hi EGE, sorry for the delayed answer..

i am really confused, how could i put this context in to mine in working format.

i mean i have the following two code
Application.php  this is class which creates dropdown menu select and search functionality..
test2_3.php is the file to show to user...

but i got problem how could i get ur code integerate to thi.

please see the code snippet for more.
thanks again.

Application.php
 
<?
class Application {
	
	function conn($sql)
{   
      $host        = "localhost";
	 $username  = "root";
     $pwd      = "";
     $dbname      = "example";
 
    //echo "commnecing connection to local db<br>"
    if (!($conn=mysql_connect($host, $username, $pwd)))  {
        printf("error connecting to DB by user = $username and pwd=$pwd");
        exit;
    }
    $db3=mysql_select_db($dbname,$conn) or die("Unable to connect to local database");
	
   
    $result = mysql_query($sql) or die ("Can't connect because ". mysql_error());
   
    return $result;
   
}//end function  
 
 
function dropdown($field, $table)
{ 
  //initialize variables
  $oHTML  = '';
  $result = '';
 
  //check to see if the field is passed correctly
  if (($field == "")||($table == ""))
  {
    die("No column or table specified to create drop down from!");
  }
 
  $sql = "select distinct($field) from $table";
 
  //call the db function and run the query
  $result = $this->conn($sql);
 
  //if no results are found to create a drop down return a textbox
  if ((!$result) ||(mysql_num_rows($result)==0))
  {
    $oHTML .= "<input type='text' name='$field' value='' size='15'>";
  }elseif (($result)&&(mysql_num_rows($result)>0)){
   
    //build the select box out of the results
    $oHTML .= "<select name='$field'>\n<option value='all'>All</option>\n";
    while ($rows = mysql_fetch_array($result))
    {
      $oHTML .= "<option value='".$rows[$field]."'>".$rows[$field]."</option>\n";
    }
    $oHTML .= "</select>\n";
  }
 
  //send the value back to the calling code
  return $oHTML;
}//end function
 
 
function search()
{
 
//base sql
  $sql = "select * from produkt_finder_table where 1 ";
 
//get the values from the form
//NOTE: You should do way more valdation on the values before you attempt to process anything
 
 
  if ((!empty($_POST['Bauform_d']))&&($_POST['Bauform_d'] != 'all'))
  {
    $sql .= " and Bauform_d like '". addslashes($_POST['Bauform_d'])."%' ";
  }
 
  if ((!empty($_POST['Beschreibung_d']))&&($_POST['Beschreibung_d'] != 'all'))
  {
    $sql .= " and Beschreibung_d like '". addslashes($_POST['Beschreibung_d'])."%' ";
  }
 
 
  //run query
  $result = $this->conn($sql);
 
  if (!$result){ die("No results due to database error.<br>".mysql_error());  }
  
 
  if (mysql_num_rows($result)==0)
  {
    echo "No Results found!";
  }else{
 
    echo "<table border='1' class='corner'><th>Product Result <div style='float:right; font-size:16px'>"; 
	$this->countResult();
	echo "</div></th>"; 
	       
    while ($rows= mysql_fetch_array($result))
    {
      echo "<tr>";
	  echo "<td>";
	  echo "<ul>";
echo "<li class='addResult'><img src='{imag}' alt='' /><span class='red'>".$rows['Bauform_d']."<br /><span class='black'>".$rows['ArtikelName']."</span></span> <a href='#'>More Info</a> </li>";
echo "</ul>";
	  echo "</td>";
	  echo "</tr>";
    } 
	 echo "<tr>";
	echo "<td align='right'><a href='product.php'>back</a></td>";
	echo "</tr>";
    echo "</table>";
  }//end if
}
 
 
function show_form()
{
  
  $Bauform   = $this->dropdown('Bauform_d','produkt_finder_table');
  $Beschreibung  = $this->dropdown('ArtikelGruppe_d','produkt_finder_table');
   $SelectSchutzart  = $this->dropdown('SelectSchutzart_Cust_Bereich_d','produkt_finder_table');
    $SelectErfassungswinkel  = $this->dropdown('SelectErfassungswinkel_Cust_Bereich_d','produkt_finder_table');
	 $ArtikelProduktgruppe  = $this->dropdown('ArtikelProduktgruppe_d','produkt_finder_table');
 
  echo "<form name='search' action='product.php?action=search' method='post'>
        <table width='50%' align='center' valign='center' class='corner'>
        <tr>
          <td colspan='2' align='center'> Search Form  <div id='countR' style='float:right; font-size:16px'>Count</div></td>
        </tr>
        <tr>
          <td align='right'>Montageart:</td><td>$Bauform</td>
        </tr>
		 <tr>
          <td align='right'>ProduktGruppe:</td><td>$Beschreibung</td>
        </tr>
		 <tr>
          <td align='right'>Speisung:</td><td>$SelectSchutzart</td>
        </tr>
        <tr>
          <td align='right'>Reichweite:</td><td> $SelectErfassungswinkel </td>
        </tr>
        <tr>
          <td align='right'>Erfwinkel:</td><td>$ArtikelProduktgruppe </td>
        </tr>
		
        <tr>
           <td colspan='2' align='center'><input type='submit' name='submit' value='Go!'></td>
        </tr>
        </table>
        </form>";
 
}//end function
 
function show_formIndex()
{
  
  $Bauform   = $this->dropdown('Bauform_d','produkt_finder_table');
  $Beschreibung  = $this->dropdown('ArtikelGruppe_d','produkt_finder_table');
   $SelectSchutzart  = $this->dropdown('SelectSchutzart_Cust_Bereich_d','produkt_finder_table');
    $SelectErfassungswinkel  = $this->dropdown('SelectErfassungswinkel_Cust_Bereich_d','produkt_finder_table');
	 $ArtikelProduktgruppe  = $this->dropdown('ArtikelProduktgruppe_d','produkt_finder_table');
 
  echo "<form name='search' action='product.php?action=search' method='post'>
        <table width='50%' align='center' valign='center' class='corner'>
        <tr>
        <td>$Bauform</td>
        </tr>
		 <tr>
         <td>$Beschreibung</td>
        </tr>
		 <tr>
         <td>$SelectSchutzart</td>
        </tr>
        <tr>
        <td> $SelectErfassungswinkel </td>
        </tr>
        <tr>
         <td>$ArtikelProduktgruppe </td>
        </tr>
		
        <tr>
           <td align='center'><input type='submit' name='submit' value='Go!'></td>
        </tr>
        </table>
        </form>";
 
}//end function
 
 
 
 
function countResult(){
 
 $sql2 = "select * from produkt_finder_table where 1 ";
 
  
 
  if ((!empty($_POST['Bauform_d']))&&($_POST['Bauform_d'] != 'all'))
  {
    $sql2 .= " and Bauform_d like '". addslashes($_POST['Bauform_d'])."%' ";
  }
  
  
 
  if ((!empty($_POST['Beschreibung_d']))&&($_POST['Beschreibung_d'] != 'all'))
  {
    $sql2 .= " and Beschreibung_d like '". addslashes($_POST['Beschreibung_d'])."%' ";
  }
 
$result = $this->conn($sql2);
  //run query
 
  if (!$result){ die("No results due to database error.<br>".mysql_error());  }
 
  if (mysql_num_rows($result)==0)
  {
    echo "0";
  }else{
 
    echo mysql_num_rows($result);
}
}
 
 
function searchAll()
{
 
//base sql
  $sql = "select * from produkt_finder_table where 1 ";
 
//get the values from the form
//NOTE: You should do way more valdation on the values before you attempt to process anything
 
 
  if ((!empty($_POST['Bauform_d']))&&($_POST['Bauform_d'] != 'all'))
  {
    $sql .= " and Bauform_d like '". addslashes($_POST['Bauform_d'])."%' ";
  }
 
 
 
  //run query
  $result = conn($sql);
 
  if (!$result){ die("No results due to database error.<br>".mysql_error());  }
 
  if (mysql_num_rows($result)==0)
  {
    echo "No Results found!";
  }else{
 
    echo "<table border='1'><th>Cuenta</th><th>idclase</th><th>Enumber</th></tr>";
   
    while ($rows= mysql_fetch_array($result))
    {
      echo "<tr>";
	  echo "<td>";
	   echo "<ul>";
echo "<li class='addResult'><img src='{imag}' alt='' /><span class='red'>".$rows['Bauform_d']."<br /><span class='black'>".$rows['ArtikelName']."</span></span> <a href='#'>More Info</a> </li>";
echo "</ul>";
"</td>";
    } 
    echo "</table>";
  }//end if
 
 
 
}
 
}
 
$proFin = new Application();
 
switch($_GET['action']) {
      case 'index':
            $proFin->show_formIndex();
          break;
		
		case 'show':
            
            $proFin->show_form();
 
            break;
        case 'search':
            
            $proFin->search();
 
            break;  
        }
?>
 
test2_3.php
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:spry="http://ns.adobe.com/spry">
<head>
<link href="styleProductFinder.css" rel="stylesheet" type="text/css" />
 
<?php include('phpApplication.php'); ?>
 
 
 
</head>
<body>
   <?php
   if (isset($_POST['submit']))
{
 
  $proFin = new Application();
	 $proFin->search();     //call the search function
 
}else{
 
  $proFin = new Application();
	 $proFin->show_form();
 
}//end if
  
   ?>
   
</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ege
Ege
Flag of Türkiye image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial