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

saad220Asked:
Who is Participating?
 
EgeCommented:
umm.
it is not easy to integrate my codes with yours.

create an ajax.js  and put the javascript codes into it.
create Object
doSearch, ....  etc...


in your test2_3.php include the .js

in your form  I see action=product.php?action=search and method=POST
so your doSearch should do  

CODES BELOW

Sorry have no time integrate all with your codes.
You should do them yourself.
In EE, we may show you the  way.



/* getParams will create the parameters to post automatically from your FORM. Even checkbox/radio/select boxes, input/textarea etc. all with name and values
*/
function getParams(obj) {
        params = 'debug=' + UniqueString();
  for (i=0; i<obj.length; i++) {
          if (obj.elements[i].type == 'checkbox') {
                        if (obj.elements[i].checked == true) {
                        params = params + '&' + obj.elements[i].name + '=' + encodeURIComponent(obj.elements[i].value);
 
                        }
          }
          else if (obj.elements[i].type == 'radio') {
                        if (obj.elements[i].checked == true) {
                        params = params + '&' + obj.elements[i].name + '=' + encodeURIComponent(obj.elements[i].value);
 
                        }
          }
          else if (obj.elements[i].type == 'select') {
                        params = params + '&' + obj.elements[i].name + '=' + encodeURIComponent(obj.elements[i].options[obj.elements[i].selec
tedIndex].value);
          }
          else {
                params = params + '&' + obj.elements[i].name + '=' + encodeURIComponent(obj.elements[i].value);
          }
  }
          return params;
}
function doSearch() {
params = getParams(document.getElementById('my_form_name'));
 
// activeAjax is your AJAX Object, I named as http1 in above comments.
                activeAjax.open('POST','test_2.3php?action=search',true);
                activeAjax.setRequestHeader("Pragma", "No-Cache");
                activeAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                activeAjax.setRequestHeader("Content-length", params.length);
                activeAjax.setRequestHeader("Connection", "close");
                activeAjax.onreadystatechange = handleResult;
                activeAjax.send(params);
}

Open in new window

0
 
JurgenvHCommented:
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.
0
 
saad220Author Commented:
that is for, java script code...is there some other tutorials how could call php function.?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
EgeCommented:
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

0
 
EgeCommented:
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

0
 
saad220Author Commented:
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.
0
 
EgeCommented:
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

0
 
EgeCommented:
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

0
 
EgeCommented:
sorry code has  errors.


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

Open in new window

0
 
saad220Author Commented:
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

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.