Go Back   CodingForums.com > :: Client side development > JavaScript programming > Ajax and Design

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 08-09-2009, 10:12 PM   PM User | #1
Rading
New Coder

 
Join Date: Oct 2008
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Rading is an unknown quantity at this point
Help with ajax/php

hi guys?

Im new to this so am having difficulties as i have not seen ajax in a working example with what i am trying to achieve here.

The code below contains a form with a number of fields. I am trying to query the database by entering a number in the first field (student id), then clicking the query button so the query results (student name, other names and class) can be displayed in a div section I have created below the query button.

I have been going through the tutorials at tizag.com and I've followed all instructions to the best of my knowledge but I cant get it to work.

Clicking the query button results in the following error:

Code:
Parse error: parse error, expecting `']'' in C:\xampp\htdocs\project\ajax-example.php on line 46
Can someone please fix this for me?? After the query works I want to make the results of the query to be inserted into the 3 form fields after the student id field. I'd appreciate some guidance with this as well.

I have attached the sql file of my database just in case someone requires it.

Below is my code. Thanks.

payment.php

PHP Code:
<!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>Payments</title>
</
head>

<
body>

<
script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
    var 
ajaxRequest;  // The variable that makes Ajax possible!
    
    
try{
        
// Opera 8.0+, Firefox, Safari
        
ajaxRequest = new XMLHttpRequest();
    } catch (
e){
        
// Internet Explorer Browsers
        
try{
            
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (
e) {
            try{
                
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (
e){
                
// Something went wrong
                
alert("Your browser broke!");
                return 
false;
            }
        }
    }
    
// Create a function that will receive data sent from the server
    
ajaxRequest.onreadystatechange = function(){
        if(
ajaxRequest.readyState == 4){
            var 
ajaxDisplay document.getElementById('ajaxDiv');
            
ajaxDisplay.innerHTML ajaxRequest.responseText;
        }
    }
    var 
stid document.getElementById('stid').value;
    var 
stfname document.getElementById('stfname').value;
    var 
stoname document.getElementById('stoname').value;
    var class = 
document.getElementById('class').value;
    var 
queryString "?stid=" stid "&stfname=" stfname "&stoname=" stoname "&class=" + class;
    
    
ajaxRequest.open("GET""ajax.php" queryStringtrue);
    
ajaxRequest.send(null); 

}
//-->
</script>

<form name="payment">
    <label class="cf_label" style="width: 150px;">Student Id</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
    <input class="cf_inputbox required validate-number" maxlength="150" size="30" title="" id="stid" name="student_id" type="text" /> 
<br /><br />
    <label class="cf_label" style="width: 150px;">Student First Name</label>
    &nbsp; &nbsp; &nbsp; 
    <input class="cf_inputbox required" maxlength="150" size="30" title="" id="stfname" name="student_name" type="text" />
  <br /><br />
    <label class="cf_label" style="width: 150px;">Student Other Names</label>
    &nbsp; &nbsp; &nbsp;
    <input class="cf_inputbox required" maxlength="150" size="30" title="" id="stoname" name="student_name" type="text" />
<br /><br />
    <label class="cf_label" style="width: 150px;">Class</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
    <input class="cf_inputbox required" maxlength="150" size="30" title="" id="class" name="class" type="text" />
  <br /><br />

    <label class="cf_label" style="width: 150px;">Payment Method</label>
    <select class="cf_inputbox validate-selection" id="payment" size="1" title=""  name="payment_type">
    <option value="">Choose Option</option>
      <option value="Banker's Cheque">Banker's Cheque</option>
<option value="Deposit Slip">Deposit Slip</option>
<option value="Cash">Cash</option>

    </select>
    <br /><br />
    <label class="cf_label" style="width: 150px;">Amount</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
    <input class="cf_inputbox required validate-number" maxlength="150" size="30" title="" id="amount" name="amount" type="text" />
  <br /><br />
  
      <label class="cf_label" style="width: 150px;">Enter and other additional details</label>
      &nbsp; &nbsp; &nbsp; &nbsp;
    <textarea name="amount" cols="30" class="cf_inputbox required validate-number" id="add" title=""></textarea>
    <br /><br />
    <label class="cf_label" style="width: 150px;">Names of Parent(s) or Legal Guardian</label>
    <input class="cf_inputbox required" maxlength="150" size="30" title="" id="pgname" name="guardian_parents_name" type="text" />
  <br /><br />
    <input value="Query" onclick='ajaxFunction()' name="button_6" type="button" />
</form>

<div id='ajaxDiv'>Your result will display here</div>

</body>
</html> 

ajax.php

PHP Code:
<?php
$dbhost 
"localhost";
$dbuser "root";
$dbpass "";
$dbname "school_database";

    
//Connect to MySQL Server
    
mysql_connect($dbhost$dbuser$dbpass);

    
//Select Database
    
mysql_select_db($dbname) or die(mysql_error());

    
// Retrieve data from Query String
    
    
$stid $_GET['stid'];
    
$stfname $_GET['stfname'];
    
$stoname $_GET['stoname'];
    
$class $_GET['class'];
    
    
// Escape User Input to help prevent SQL Injection

    
$stid mysql_real_escape_string($stid);
    
$stfname mysql_real_escape_string($stfname);
    
$stoname mysql_real_escape_string($stoname);
    
$class mysql_real_escape_string($class);
    
    
//build query
    
$query "SELECT `student_f.name`,`student_o.names`,`class` FROM `student_dat` WHERE `student_id` = '$stid'";
    
    
//Execute query
    
$qry_result mysql_query($query) or die(mysql_error());

    
//Build Result String
    
$display_string "<table>";
    
$display_string .= "<tr>";
    
$display_string .= "<th>Student Id</th>";
    
$display_string .= "<th>First Name</th>";
    
$display_string .= "<th>Other Names</th>";
    
$display_string .= "<th>Class</th>";
    
$display_string .= "</tr>";

    
// Insert a new row in the table for each person returned
    
while($row mysql_fetch_array($qry_result)){
    
$display_string .= "<tr>";
    
$display_string .= "<td>$row[student_id]</td>";
    
$display_string .= "<td>$row[student_f.name]</td>";
    
$display_string .= "<td>$row[student_o.names]</td>";
    
$display_string .= "<td>$row[class]</td>";
    
$display_string .= "</tr>";
    
}
echo 
"Query: " $query "<br />";
$display_string .= "</table>";
echo 
$display_string;
?>
Attached Files
File Type: zip school_database.zip (898 Bytes, 64 views)
Rading is offline   Reply With Quote
Old 08-09-2009, 10:43 PM   PM User | #2
tomws
Senior Coder

 
tomws's Avatar
 
Join Date: Nov 2007
Location: Arkansas
Posts: 2,644
Thanks: 29
Thanked 330 Times in 326 Posts
tomws will become famous soon enoughtomws will become famous soon enough
Fix the parse error in ajax.php. That line is around this
PHP Code:
    $display_string .= "<td>$row[student_f.name]</td>"
Switch to correct array syntax:
PHP Code:
    $display_string .= "<td>{$row['student_f.name']}</td>"
__________________
Are you a Help Vampire?
tomws is offline   Reply With Quote
Old 08-09-2009, 10:55 PM   PM User | #3
Rading
New Coder

 
Join Date: Oct 2008
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Rading is an unknown quantity at this point
Thank you for that. The query is now working properly.

I need to make the query results to be inserted into fields 2, 3 and 4 after a user enters the student id and either uses the tab key or the mouse to move to the next field without the page reloading. Any ideas??
Rading is offline   Reply With Quote
Old 08-09-2009, 11:00 PM   PM User | #4
tomws
Senior Coder

 
tomws's Avatar
 
Join Date: Nov 2007
Location: Arkansas
Posts: 2,644
Thanks: 29
Thanked 330 Times in 326 Posts
tomws will become famous soon enoughtomws will become famous soon enough
I think you're talking about an onblur event. Do you really want to insert data into your database like that? It seems like you could end up getting loads of junk data accidentally inserted.
__________________
Are you a Help Vampire?
tomws is offline   Reply With Quote
Old 08-09-2009, 11:12 PM   PM User | #5
Rading
New Coder

 
Join Date: Oct 2008
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Rading is an unknown quantity at this point
First I wanted to make sure the query is working properly, then I try and make the results of it be inserted into the fields instead of the div box at the bottom.

If I manage to get the results inserted into the fields I'll remove all the stuff after the query button and change the query button to a submit button instead.

Data will be inserted into the database after clicking this submit button, and you only click it after all the fields have been filled so as far as I know I don't think there's a risk of accidentally inserting data.

Back to the problem, how do I proceed fixing it??
Rading is offline   Reply With Quote
Old 08-09-2009, 11:19 PM   PM User | #6
tomws
Senior Coder

 
tomws's Avatar
 
Join Date: Nov 2007
Location: Arkansas
Posts: 2,644
Thanks: 29
Thanked 330 Times in 326 Posts
tomws will become famous soon enoughtomws will become famous soon enough
Maybe I misunderstand, but that sounds different than this:
Quote:
Originally Posted by Rading View Post
I need to make the query results to be inserted into fields 2, 3 and 4 after a user enters the student id and either uses the tab key or the mouse to move to the next field without the page reloading.
If you want to do it when the focus moves away from the input (what it says in the quote there), that's going to be an onblur event attached to the input field triggering some ajax. If just a regular submit without page reload, that's the onsubmit attached to the form tag.

I may be confused on what you're asking, though.
__________________
Are you a Help Vampire?
tomws is offline   Reply With Quote
Old 08-09-2009, 11:34 PM   PM User | #7
Rading
New Coder

 
Join Date: Oct 2008
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Rading is an unknown quantity at this point
Your right about what I'm asking. Was trying to clarify what you'd asked earlier about accidental entry of data into the database.
Rading is offline   Reply With Quote
Old 08-10-2009, 08:34 PM   PM User | #8
Rading
New Coder

 
Join Date: Oct 2008
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Rading is an unknown quantity at this point
Ok. This is where I've reached. Am now trying to make php return a response composed of first name, other names and class, each separated by a unique delimiter, eg. 'Jonn Adam^Smith^5M'.

There's something am not doing right. Any help??

Code below.

Code:
<!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>Payments</title>
</head>

<body>

<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
	var ajaxRequest;  // The variable that makes Ajax possible!
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			//var ajaxDisplay = document.getElementById('ajaxDiv');
			//ajaxDisplay.innerHTML = ajaxRequest.responseText;
			var stfField = document.getElementById('stfname');
			var stoField = document.getElementById('stoname');
			var stclassField = document.getElementById('stclass');
			var responseArray = ajaxRequest.responseText.split('^');//Split the response string into an array of strings, using "^" as delimiter. This must be compatible with what you built server-side in php.
			if(stfField) { stfField.value = responseArray[0]; }
			if(stoField) { stoField.value = responseArray[1]; }
			if(stclassField) { stclassField.value = responseArray[2]; }
		}
	}
	var stid = document.getElementById('stid').value;
	var stfname = document.getElementById('stfname').value;
	var stoname = document.getElementById('stoname').value;
	var stclass = document.getElementById('stclass').value;
	var queryString = "?stid=" + stid + "&stfname=" + stfname + "&stoname=" + stoname + "&stclass=" + stclass;
	
	ajaxRequest.open("GET", "ajax.php" + queryString, true);
	ajaxRequest.send(null); 

}
//-->
</script>

<form name="payment">
    <label class="cf_label" style="width: 150px;">Student Id</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
    <input class="cf_inputbox required validate-number" onblur="ajaxFunction()" maxlength="150" size="30" title="" id="stid" name="student_id" type="text" /> 
<br /><br />
    <label class="cf_label" style="width: 150px;">Student First Name</label>
    &nbsp; &nbsp; &nbsp; 
    <input class="cf_inputbox required" maxlength="150" size="30" title="" id="stfname" name="student_name" type="text" disabled="disabled" />
  <br /><br />
    <label class="cf_label" style="width: 150px;">Student Other Names</label>
    &nbsp; &nbsp; &nbsp;
	<input class="cf_inputbox required" maxlength="150" size="30" title="" id="stoname" name="student_name" type="text" disabled="disabled" />
<br /><br />
    <label class="cf_label" style="width: 150px;">Class</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
    <input class="cf_inputbox required" maxlength="150" size="30" title="" id="stclass" name="stclass" type="text" disabled="disabled" />
  <br /><br />

    <label class="cf_label" style="width: 150px;">Payment Method</label>
    <select class="cf_inputbox validate-selection" id="payment" size="1" title=""  name="payment_type">
    <option value="">Choose Option</option>
      <option value="Banker's Cheque">Banker's Cheque</option>
<option value="Deposit Slip">Deposit Slip</option>
<option value="Cash">Cash</option>

    </select>
    <br /><br />
    <label class="cf_label" style="width: 150px;">Amount</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 
    <input class="cf_inputbox required validate-number" maxlength="150" size="30" title="" id="amount" name="amount" type="text" />
  <br /><br />
  
  	<label class="cf_label" style="width: 150px;">Enter and other additional details</label>
  	&nbsp; &nbsp; &nbsp; &nbsp;
	<textarea name="amount" cols="30" class="cf_inputbox required validate-number" id="add" title=""></textarea>
	<br /><br />
    <label class="cf_label" style="width: 150px;">Names of Parent(s) or Legal Guardian</label>
    <input class="cf_inputbox required" maxlength="150" size="30" title="" id="pgname" name="guardian_parents_name" type="text" />
  <br /><br />
    <input value="Submit" name="button_6" type="submit" />
</form>

<!--<div id='ajaxDiv'>Your result will display here</div>-->

</body>
</html>
ajax.php
Code:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "school_database";

	//Connect to MySQL Server
	mysql_connect($dbhost, $dbuser, $dbpass);

	//Select Database
	mysql_select_db($dbname) or die(mysql_error());

	// Retrieve data from Query String
	
	$stid = $_GET['stid'];
	$stfname = $_GET['stfname'];
	$stoname = $_GET['stoname'];
	$stclass = $_GET['stclass'];
	
	// Escape User Input to help prevent SQL Injection

	$stid = mysql_real_escape_string($stid);
	//$stfname = mysql_real_escape_string($stfname);
	//$stoname = mysql_real_escape_string($stoname);
	//$stclass = mysql_real_escape_string($stclass);
	
	//build query
	$query = "SELECT `student_id`, `student_f.name`,`student_o.names`,`stclass` FROM `student_dat` WHERE `student_id` = '$stid'";
	
	//Execute query
	$qry_result = mysql_query($query) or die(mysql_error());

	//Build Result String
	//$display_string = "<table>";
	//$display_string .= "<tr>";
	//$display_string .= "<th>Student Id</th>";
	//$display_string .= "<th>First Name</th>";
	//$display_string .= "<th>Other Names</th>";
	//$display_string .= "<th>Class</th>";
	//$display_string .= "</tr>";

	// Insert a new row in the table for each person returned
	//while($row = mysql_fetch_array($qry_result)){
	//$display_string .= "<tr>";
	//$display_string .= "<td>{$row['student_id']}</td>";
	//$display_string .= "<td>{$row['student_f.name']}</td>";
	//$display_string .= "<td>{$row['student_o.names']}</td>";
	//$display_string .= "<td>{$row['stclass']}</td>";
	//$display_string .= "</tr>";
	
//}
//echo "Query: " . $query . "<br />";
//$display_string .= "</table>";
//echo $display_string;
?>
Rading is offline   Reply With Quote
Old 08-10-2009, 08:36 PM   PM User | #9
Rading
New Coder

 
Join Date: Oct 2008
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Rading is an unknown quantity at this point
deleted
Rading is offline   Reply With Quote
Old 08-10-2009, 09:07 PM   PM User | #10
tomws
Senior Coder

 
tomws's Avatar
 
Join Date: Nov 2007
Location: Arkansas
Posts: 2,644
Thanks: 29
Thanked 330 Times in 326 Posts
tomws will become famous soon enoughtomws will become famous soon enough
Quote:
Originally Posted by Rading View Post
There's something am not doing right. Any help??
It's helpful to know what the problem is. I'll bet it relates to every output line in ajax.php being commented out, though.
__________________
Are you a Help Vampire?
tomws is offline   Reply With Quote
Old 08-10-2009, 11:22 PM   PM User | #11
Rading
New Coder

 
Join Date: Oct 2008
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Rading is an unknown quantity at this point
Commenting out things that don't work helps me debug, so......

Thanks nway, I think I've figured it out. Will clean it up and post it if anyone wants to have a look.
Rading is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 02:09 PM.


Advertisement
Log in to turn off these ads.