0

hi guys?

Im new to this so please bear with me. I have not seen a practical example of what I am trying to do so i'd appreciate any help I get.

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 a number of tutorials on this 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:

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 on how to go about 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

<!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" + 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" 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
$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;
?>
2
Contributors
19
Replies
20
Views
8 Years
Discussion Span
Last Post by manizzi
Featured Replies
0

I have managed to fix the parse error in ajax.php. It required changing the code around the error from:

$display_string .= "<td>$row[student_f.name]</td>";

to

$display_string .= "<td>{$row['student_f.name']}</td>";

Now I want the query results to be inserted into fields 2, 3 and 4 after the user enters a number in the first field and either uses the mouse or tab key to move to the next field without the page reloading.

Any ideas??

0

Manizzi,

Try

....
    $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>";
....

That should at least clear the error.

Airshow

0

Thanks for the reply nway. Any help with the new problem??

0

Manizzi,

The php looks like it should work now, providing the database is in place.

In the javascript, avoid variable name class . It's a "java keyword reserved by JavaScript" and will give an error in some(?) browsers. I generally use clss . Probably also good to avoid "class" as an HTML element id/name. Again, use "clss"

Apart from that, ajaxFunction looks like it should work (in browsers that support getElementById), providing all the element ids are correct (I've not checked them).

Airshow

0

Thanks for the tips. Will make those changes soon. Everything so far is working except one. I want to redirect the results of the query to be inserted into fields 2, 3 and 4 without the page reloading.

I have read somewhere that this is possible through the use of an onblur event attached to the fields I want the data to be inserted to. This event activates when the user tabs to or moves into the next field with a mouse.

Problem is how do I go about this? Any examples would be appreciated alot.

0

Manizzi,

Yes, this is eminently possible.

1.
Reduce your ajax querystring down to:

var queryString = "?stid=" + stid;

2.
In php, delete the lines:

$stfname = mysql_real_escape_string($_GET['stfname']);
$stoname = mysql_real_escape_string($_GET['stoname']);
$clss = mysql_real_escape_string($_GET['clss']);

These parameters are not used.

3.
In php, you can also get rid of the while loop, as the database should only ever return one row.

Now, instead of building a table, arrange for the php to return a response composed of first name, other names and class, each separated by a unique delimiter, eg. 'Jonn Adam^Smith^5M' (actual values as returned from the database).

4.
In the HTML, add onblur="ajaxFunction()" to the "stid" tag.

5.
In ajaxFunction , change the response handler as follows:

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 clssField = document.getElementById('clss');
	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(clssField) { clssField.value = responseArray[2]; }
  }
}

6.
In the HTML, you might now choose to "disable" the three fields that will be automatically populated, to prevent user entry. It may be wrong to allow users to overwrite the database values, which will effectively be displayed as a feedback/confidence check that the id is valid, eg:

<input class="cf_inputbox required" maxlength="150" size="30" title="" id="stfname" name="student_name" type="text" disabled="disabled" />

Of course, if this were a user-data-entry dialog then you would probably want to allow names etc to be entered/overwritten and you wouldn't disable the fields.

The syntax disabled="disabled" is a bit of nonsense to satisfy XHTML rules. In HTML disabled would suffice.

I think that's about it.

Airshow

0

Thanks for that airshow. Will to do that in the morning and post back the results.

Cheers!!

0

OK. This is the latest code. I'm missing something somewhere. Please help?

<!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

<?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;
?>
0

Manizzi,

Just two things, as far as I can see.

Frist, in javascript reduce the querystring composition right down as follows :

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;
	var queryString = "?stid=" + stid;

Then in php it must generate and output the response string. Add this to the bottom of the php file :

$row = mysql_fetch_array($qry_result);
echo $row['student_f.name'] . '^' . $row['student_o.names'] . '^' . $row['stclass'];

I think that will do it but I've not tested so you may need to debug.

Airshow

0

Thank you so much!!! Had a few problems but its finally worked!! :)

Will post a cleaner code when am done.

Cheers!!

0

1 more thing I've just thought about. Its about the disabled tag in the 3 fields. I'm not on my computer to test this but wouldn't it make these form fields not be submitted to a database if I added a submit button and linked it to a table??

If yes, is there a way around this so that the user can't change the inserted values but the values would be inserted into a database?

0

Manizzi

1 more thing I've just thought about. Its about the disabled tag in the 3 fields. I'm not on my computer to test this but wouldn't it make these form fields not be submitted to a database if I added a submit button and linked it to a table??

Yes, your're right.

If yes, is there a way around this so that the user can't change the inserted values but the values would be inserted into a database?

You have to "cheat". Display the name etc in either disabled, unnamed fields or in divs or paras or whatever gives a good layout. But also put the same data into three named hidden form fields. <input type="hidden" id=".... " name="....."> Airshow

0

Manizzi,

I've had another thought on this.

You may not need to send the names/class back to the server, as they are uniquely associated with the stid . As long as subsequent queries go back to the same server (or any server that has access to the same database) then the server-side script can fetch the names/class again by executing a query on the database. You may be able to get away with just sending the stid (plus any new/changed data).

In fact, this would be prefereable (unless the purpose of the dialog is to allow names/class to be changed) as it provides a better guarantee of data integrity.

Airshow

0

I was also thinking the same thing. You can leave those fields as disabled or not. It wouldn't matter even if the user changes them before he submits the form. The unique key stid is still linked back to the student database.

Anyways, thanks alot for the help. Much appreciated. Cheers!!

0

Manizzi,

Personally I would disable the fields if the user is not being invited to edit the data in them. Otherwise may will appear that the data is editable (and will be saved) when in fact it is not.

You may need to provide another version of the dialog which does allow names etc. to be edited (and saved).

Airshow

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.