Jump to content

[SOLVED] need help with AJAX script


Alith7

Recommended Posts

I think i solved it, a bug with the reg in in the JS,

 

change

           var re = /^(.*?)::.*?)$/i;

to

           var re = /^([\s\S]*?)::[\s\S]*?)$/i;

 

Full Code

<?php 
require_once('Connections/geQuote.php');
mysql_select_db($database_geQuote, $geQuote);

/*
$database_geQuote = "test";
$geQuote = mysql_connect("localhost","root","");
$selected=mysql_select_db($database_geQuote, $geQuote);
*/
?>

<?php

$query_listCustomer = "SELECT customer.cust_id, customer.name FROM customer ORDER BY customer.name";
$listCustomer = mysql_query($query_listCustomer, $geQuote) or die(mysql_error());
$row_listCustomer = mysql_fetch_assoc($listCustomer);
$totalRows_listCustomer = mysql_num_rows($listCustomer);

if( isset($_GET['cust_id']) )
{
  $query_custData = sprintf("SELECT contact, cust_email FROM customer WHERE cust_id=%d LIMIT 0,1",$_GET['cust_id']);
  $result_custData = mysql_query($query_custData, $geQuote) or die(mysql_error());
  $row_custData = mysql_fetch_assoc($result_custData);
  echo $row_custData['contact'].":::".$row_custData['cust_email'];
  exit; //we're finished so exit..
}

?>


<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Untitled Document</title>

<script language="javascript">
  function ajaxFunction(cust_id)
  {
     //link to the PHP file your getting the data from
     //var loaderphp = "quote.php";
     //i have link to this file
     var loaderphp = "<?php echo $_SERVER['PHP_SELF'] ?>";
    
     //we don't need to change anymore of this script
     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("Your browser does not support AJAX!");
              return false;
           }
        }
     }
    
     xmlHttp.onreadystatechange=function()
     {
        if(xmlHttp.readyState==4)
          {
           var re = /^([\s\S]*?)::[\s\S]*?)$/i;
           var match = re.exec(xmlHttp.responseText);
           if (match != null) {
              document.getElementById('quote_to').value= match[1];
              document.getElementById('email_to').value= match[2];
           }
          }
	}
     	xmlHttp.open("GET", loaderphp+"?cust_id="+cust_id,true);
	xmlHttp.send(null);
  }
</script>

</head>

<body>



<select name="cust_id" id="cust_id" onchange="ajaxFunction(this.value);">

  
<?php do { ?>
  <option value="<?php echo $row_listCustomer['cust_id']?>"><?php echo $row_listCustomer['name']?></option>
  <?php } while ($row_listCustomer = mysql_fetch_assoc($listCustomer));
          $rows = mysql_num_rows($listCustomer);
          if($rows > 0) {
              mysql_data_seek($listCustomer, 0);
             $row_listCustomer = mysql_fetch_assoc($listCustomer);
             }
?>

       </select>
         <h2>Quoted to:</h2>
     <input name="quote_to" type="text" class="widebox" id="quote_to" maxlength="50" />
         <h2>Email to:</h2>
    <input name="email_to" type="text" class="widebox" id="email_to" />

</body>
</html>

 

Example Database table

CREATE TABLE IF NOT EXISTS `customer` (
 `cust_id` mediumint( NOT NULL auto_increment,
 `name` varchar(50) NOT NULL,
 `contact` varchar(50) NOT NULL,
 `cust_email` varchar(50) NOT NULL,
 PRIMARY KEY  (`cust_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

-- data for table `customer`
INSERT INTO `customer` (`cust_id`, `name`, `contact`, `cust_email`) VALUES
(1, 'MadTechie', 'Richard', 'richard@blar.com'),
(2, 'Alith7', 'PHPFreaks', 'Alith7@Alith7.com');

Link to comment
Share on other sites

YAY!

it works!! OMG I could kiss you!

 

thank you so much for all your help!

I NEVER would have figured it out otherwise!

 

as I'm just starting to learn AJAX, can I ask what all the symbols in that line of code mean?  I can usually pick apart basic java to figure out what it's doing and why, but I have to say I'm a big confused by some of those.

Link to comment
Share on other sites

Okay the

var re = /^(.*?)::.*?)$/i;

and

var re = /^([\s\S]*?)::[\s\S]*?)$/i;

do the exact same thing (just JS doesn't like the first one)..

they are regular expressions you could probably use JS .split() but it was quicker for me to write a RegEx..

 

it basically means

get the string from the start up until ::: then from their to the end

Match[1] = first half

Match[2] = second half

 

i hope that makes sense

 

regular expressions is a large topic so don't worry too much if it doesn't make sense.. it took me awhile..

Link to comment
Share on other sites

you're right! RegEx is going to make my head hurt for a while.

 

but, ok, I want to make sure I understand how this works and why, asking for the code is great but I haven't learned anything if I don't understand it, or worse, have it wrong.

 

so we have the two chunks of code this one sets the data for the code to pick-up:

$query_custData = sprintf("SELECT contact, cust_email FROM customer WHERE cust_id=%d LIMIT 0,1",$_GET['cust_id']);
   $result_custData = mysql_query($query_custData, $geQuote) or die(mysql_error());
   $row_custData = mysql_fetch_assoc($result_custData);
   echo $row_custData['contact'].":::".$row_custData['cust_email'];

 

 

This one tells what to do with it:

xmlHttp.onreadystatechange=function()
      {
         if(xmlHttp.readyState==4)
           {
            var re = /^([\s\S]*?)::[\s\S]*?)$/i;
            var match = re.exec(xmlHttp.responseText);
            if (match != null) {
               document.getElementById('quote_to').value= match[1];
               document.getElementById('email_to').value= match[2];
            }
           }
      }
         xmlHttp.open("GET", loaderphp+"?cust_id="+cust_id,true);
      xmlHttp.send(null);
   }

 

So, if I'm understanding this right, the echo of the query results sets the variables in a form that the JS is looking for in the format of "text:::text" but hidden in the background.  the ::: being the key part. "[\s\S]*?" tells it that the data could be anything and could contain cases, but it is unknown.

 

the "re" sets the search parameters so that when the function is run, it looks for the items separated by ::: and "/i" counts the results and puts them in an array.  the variable "match" sets off the execution of the search "re.exec".

 

the IF statement then checks to make sure that the script returned something, if it did, find the elements and replace the value with the items from the match[] array.

 

the xmlHttp.open reopens the page in the background with the cust_id values to pass to the GET script and reloads the backside without reloading the whole page.

 

the xmlHttp.send(null) tells it not to send the form or process any other data in the reopening.

 

Ok, that was a bit garbled, but I think it makes sense.  the only part I don't get is what the "xmlHttp.responseText" does/comes from.

Link to comment
Share on other sites

Theirs Quick summary at the bottom but i think it will make more sense reading the whole thing then the summary..

 

 

"[\s\S]*?" tells it that the data could be anything and could contain cases, but it is unknown.

 

the "re" sets the search parameters so that when the function is run, it looks for the items separated by ::: and "/i" counts the results and puts them in an array.  the variable "match" sets off the execution of the search "re.exec".

Okay the /i means ignore case (case insensitive) which was kinda pointless..

Let me break down this code first

var re = /^(.*?)::.*?)$/i;

/^(.*?):::(.*?)$/i

 

/ = Start and End of the RegEx

^ = From the Start

$ =  To The End

::: = this String = :::

 

(.*?) =

the () mean Capture whats in side

. = anything

* = None or more

? = lazzy (AKA until)

So basically Capture until

 

So to sum that up

from the start ^ Capture anything until ::: then capture anything until the End $

 

Now thats 2 Captures

First becomes Match[1] Second becomes Match[2]

 

Now [\s\S] mean characters that are or are not whitespaces (which means anything aka .)

 

 

Ok, that was a bit garbled, but I think it makes sense.  the only part I don't get is what the "xmlHttp.responseText" does/comes from.

Okay thats the reply

So

xmlHttp.open("GET", loaderphp+"?cust_id="+cust_id,true);

Makes a call to the url with that call a listener is also started.. So XMLHttpRequest listens for a responce (readyState) when the called page has finished (DONE) loading, the readyState is set to 4 (4 = done).. this mean xmlHttp.responseText is also ready, (contains the page)

 

 

So..

Quick summary

Javascript passes the value of a drop down to a script that uses AJAX to open a url and that page uses GET to find check the database for entries and echos them out then exits. as this page was loaded via a AJAX request the contenst of the page is picked up by the listener, which waits for the readystate to be set to 4 (page finished loading), then check to see if contents contains something1:::something2 if it does then sets the value of element id 'quote_to' to something1 and the value of element id 'email_to' to something2.

 

 

I hope that makes sense..

:o

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.