Getting Ajax error 500 when trying to post items from Database - javascript

What I am trying to do is modify some attributes in my database. The way I want to do it, is to have a dropdown menu that is populated with options (in this case, student names) from the table I am calling, and then populating text fields with the information that pertains to that specific student, that can then be edited and then submitted to the database. So far, my drop down menu works. It fills itself with the appropriate attributes. My problem comes when I'm trying to populate the text fields with the other attributes. I opened up the console to see if I was getting any errors (because nothing was happening after I selected a student) and it said there was an error 500 with my POST.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
# Perform database query
$query = "SELECT * FROM student";
$result = $conn->query($query) or die('Query 1 failed: ' . mysql_error());
?>
<label for="studentSelect">Student Name: </label>
<select id="studentSelect">
<option value="0">Please select</option>
<?php
while ($row = $result->fetch_assoc())
{
echo '<option value="' . $row['studentID'] . '" > "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>';
}
?>
</select>
<div>
<label for="element_5_1">First Name</label>
<input id="element_5_1" name="element_5_1" class="element text large" type="text">
</div>
<div>
<span class="floatLeft">
<label for="element_5_3">Last Name</label>
<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text">
</span>
<span style="float:left">
<label for="element_5_4">Major</label>
<input id="element_5_4" name="element_5_4" class="element text medium" style="width:4em" type="text">
</select>
</span>
<span style="float:left">
<label for="element_5_5">Credits Earned</label>
<input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" type="text">
</span>
</div>
<script type="text/javascript">
function makeAjaxRequest(studentFirstName)
{
$.ajax({
type: "POST",
data: { studentFirstName: studentFirstName },
dataType: "json",
url: "process_ajax.php",
success: function(json)
{
insertResults(json);
},
failure: function (errMsg)
{
alert(errMsg);
}
});
}
$("#studentSelect").on("change", function()
{
var id = $(this).val();
if (id === "0")
{
clearForm();
}
else
{
makeAjaxRequest(id);
}
});
function insertResults(json)
{
$("#element_5_1").val(json["studentFirstName"]);
$("#element_5_3").val(json["studentLastName"]);
$("#element_5_4").val(json["major"]);
$("#element_5_5").val(json["creditsEarned"]);
}
function clearForm()
{
$("#element_5_1, #element_5_3, #element_5_4, #element_5_5").val("");
}
</script>
I then have a separate ajax processing file
<?php
$host = "********.mysql.database.azure.com";
$username = "************";
$password = "*******";
$db_name = "**********";
//Establishes the connection
$conn = mysqli_init();
mysqli_real_connect($conn, $host, $username, $password, $db_name, 3306);
if (mysqli_connect_errno($conn)) {
die('Failed to connect to MySQL: '.mysqli_connect_error());
$studentName = $_POST['studentFirstName'];
$query = "SELECT * FROM student";
$result = mysql_query($query) or die('Query 2 failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
if ($studentName == $row['studentFirstName']){
echo json_encode($row);
}
}
?>
I hope I've given enough information for someone to be able to spot my errors. Thank you!

Parse error line 22.
<?php
$host = "********.mysql.database.azure.com";
$username = "************";
$password = "*******";
$db_name = "**********";
//Establishes the connection
$conn = mysqli_init();
mysqli_real_connect($conn, $host, $username, $password, $db_name, 3306);
if (mysqli_connect_errno($conn)){
die('Failed to connect to MySQL: '.mysqli_connect_error());
$studentName = $_POST['studentFirstName'];
$query = "SELECT * FROM student";
$result = mysql_query($query) or die('Query 2 failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
if ($studentName == $row['studentFirstName']){
echo json_encode($row);
}
}
}
?>
You have to change also your javascript
function insertResults(json)
{
$("#element_5_1").val(json.studentFirstName);
$("#element_5_3").val(json.studentLastName);
$("#element_5_4").val(json.major);
$("#element_5_5").val(json.creditsEarned);
}

After 4 hours of trial and error, this is the code I came up with that works in populating the input fields. I'm pretty sure your error was the fact that your
<option value="' . $row['studentID'] . '" > "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>
should have been
<option value="' . $row['studentID'] . '" name="studentFirstName"> "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>
anyways onto my code:
config.php
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = ""; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
index.php
<?php
include("config.php");
$sql = "SELECT * FROM messaging";
$result = $conn->query($sql);
$conn->close();
?>
<!Doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<label for="studentSelect">Student Name: </label>
<select id="studentSelect">
<option value="0">Please select</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?php echo $row['msg_id']; ?>" name="studentFirstName" id="studentFirstName">"<?php echo $row['msg_from'] ?>" "<?php echo $row['msg_to'] ?>"</option>
<?php } ?>
</select>
<div>
<span class="floatLeft">
<label>First Name</label>
<input id="populate_first_name" class="element text large" type="text">
</span>
<span class="floatLeft">
<label>Last Name</label>
<input id="populate_last_name" class="element text medium" style="width:14em" type="text">
</span>
<span style="float:left">
<label>Major</label>
<input id="populate_major" class="element text medium" style="width:4em" type="text">
</select>
</span>
<span style="float:left">
<label>Credits Earned</label>
<input id="populate_credits_earned" class="element text medium" style="width:6em" type="text">
</span>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#studentSelect").change(function(){
var studentFirstName = $(this).val();
$.ajax({
url: 'process_ajax.php',
type: 'post',
data: {studentFirstName:studentFirstName},
dataType: 'json',
success:function(response) {
var len = response.length;
for( var i = 0; i<len; i++) {
var studentFirstName = response[i]['studentFirstName'];
var studentLastName = response[i]['studentLastName'];
var major = response[i]['major'];
var creditsEarned = response[i]['creditsEarned'];
$("#populate_first_name").val(studentFirstName);
$("#populate_last_name").val(studentLastName);
$("#populate_major").val(major);
$("#populate_credits_earned").val(creditsEarned);
}
}
});
});
});
</script>
</body>
</html>
process_ajax.php
<?php
include("config.php");
$studentName = $_POST['studentFirstName']; // department id
$sql = "SELECT * FROM student";
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ) {
if ($row['msg_id'] == $studentName) {
$studentFirstName = $row['studentFirstName'];
$studentLastName = $row['studentLastName'];
$major = $row['major'];
$creditsEarned = $row['creditsEarned'];
$users_arr[] = array("studentFirstName" => $studentFirstName, "studentLastName" => $studentLastName, "major" => $major, "creditsEarned" => $creditsEarned);
}
}
// encoding array to json format
echo json_encode($users_arr);
?>
Try it out and lemme know if it works

Related

Get data MySQL DB and display on in HTML

How would I code into my program using PHP/JavaScript and HTML/CSS to display data from a database I made in MySQL Monitor on the blue section below:
I made buttons that use PHP to go into the database and show the data on the HTML page:
HTML:
<form action="fullridez.php" method="post">
<h4 id="Filter">GPA</h4>
<input id="FilterBox" name="gpa" type="text"/>
<h4 id="Filter">Amount</h4>
<input id="FilterBox" name="amount" type="text"/>
<h4 id="Filter">School</h4>
<input id="FilterBox" name="school" type="text"/>
<input type="submit" id="FilterBox" name="myForm" onkeypress="checkEnter()" ><img src="search.png" width=15 height=15 /></button>
</form>
<script>
</script>
PHP:
<?php
if(isset($_POST['myForm'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarshiplist";
$conn = mysqli_connect($servername, $username, $password, $database);
$gpa = $_POST['gpa'];
$amount = $_POST['amount'];
$count = "SELECT * FROM scholarships";
$result = mysqli_query($conn, $count);
if ($result->num_rows > 0) {
$sql = "SELECT * FROM scholarships WHERE GPA <= " . $gpa . " AND Amount <= "
. $amount;
if ($result = mysqli_query($conn, $sql)) {
while ($row=mysqli_fetch_row($result)) {
for($i = 0; $i < count($row); $i++) {
echo $row[$i] . '<br>';
}
}
}
} else {
echo "0 results";
}
$conn->close();
}
SQL:
USE ScholarshipList;
CREATE TABLE Scholarships
(
id int unsigned NOT NULL auto_increment,
School varchar(500) NOT NULL,
GPA decimal(10,2) NOT NULL,
Amount decimal(10,2) NOT NULL,
PRIMARY KEY (id)
);
I am using XAMPP
When I click the button on the HTML file it bring me to the PHP page and all I see is the PHP code. I don't want it to go to the page but stay on the same page showing the data below the buttons.
This is what the page looks like so far
page
What am I doing wrong?
If your HTML form is contained within the 'fullridez.php' file and you are posting the form inputs to that same file, then you need to have some PHP where you'd like to output to be checking for results and then looping through those results while echoing them out:
<table>
<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td></tr>
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<tr><td>"
. $row['col_1'] . "</td><td>"
. $row['col_2'] . "</td><td>"
. $row['col_3'] . "</td></tr>";
}
?>
</table>
You can build a wireframe div table with for loop:
<?php
$num_rows = mysql_num_rows($result);
for ($i=0;$i<$num_rows;$i++) {
//loop through all rows of data
$row = mysql_fetch_assoc($result); // your data is now: $row['fieldName']
?>
<div>
GPA <input name="" value="<?php echo($row['gpa'])?>;" type="text">
AMOUNT <input name="" value="<?php echo($row['amount'])?>;" type="text">
SCHOOL <input name="" value="<?php echo($row['school'])?>;" type="text">
</div>
<?php
} //end of the loop
?>

Sort output from MySql with php

I try to return table values from Mysql db sorted
. I manage to connect and update the table right,
at the same page I wish to return the table back to html as chat history. just can't get the messages to show up sorted by time .
2) how is there a better way to return the output with ajax & jquery to the last div id messages?
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sender = $_POST["sender"];
$receiver = $_POST["receiver"];
$message = $_POST["message"];
date_default_timezone_set('Asia/Tel_Aviv');
$create_date = date('Y-m-d H:i:s');
//Not sure this is right way to update the date.
if ($create_date != $update_date)
$date == $update_date;
$sql = "INSERT INTO messages (sender, receiver, message, create_date) VALUES ('$sender', '$receiver', '$message', '$create_date')";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, sender, receiver, message, create_date FROM messages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["id"]. ") " . $row["sender"]. " to " . $row["receiver"]. " : " . $row["message"]. " / " . $row["create_date"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Html
<form action="" method="POST" enctype="multipart/form-data">
<p>name of sender:
<input class="input" name="sender" id="sender" value="" size="13"
maxlength="13" dir="ltr" autocomplete="on" type="text" height="20" required><br>
<p>name of receiver:
<input class="input" name="receiver" id="receiver" value="" size="13"
maxlength="13" dir="ltr" autocomplete="on" type="text" height="20" required><br>
<p>Message: <br>
<textarea name="message" id="message" value="" rows="5" cols="30" dir="ltr" required></textarea><br>
<input value="Submit" name="button" alt="submit" onsubmit="return checkForm(this);" border="0" type="submit" align="absmiddle"></p>
</form>
<P>MESSAGES</P>
<div id="messages">
<?php include_once("action.php") ?>
Javascript validation
(can't work )
I used required in html5 instead
function checkForm(form)
{
if($('#sender').val() == ''){
alert("Sender name can not be left blank");
form.sender.focus();
return false;
}
if($('#receiver').val() == ''){
alert("Receiver name can not be left blank");
form.receiver.focus();
return false;
}
if($('#message').val() == ''){
alert("Message input can not be left blank");
form.message.focus();
return false;
}
return true;
}
Maybe you can change your select query to
SELECT id, sender, receiver, message, create_date FROM messages ORDER BY create_date

Populate a text box based on a dynamic drop down box in php

I am trying to input a value (Rating) from the database when an item is selected. I need to also be able to update that rating and then put that value into another table.
My problem is that I'm trying to figure out how to make the value in the text box be related to the selection made in the drop down. I've found coding to make another option box but cannot figure out how to make that a text box.
REWORDING: Originally when I posted the question I thought it was possible to do this without JQuery and was trying to copy the for loop and run a while loop to populate the text box. I now know that isn't possible and would like to figure out how to run a script to populate a text box on change for the drop down box. The problem being the function has to be connected to the database as well as the drop down.
1. pull the data for the drop down (from the JOURNAL table). 2. Select a journal from that drop down 3. Inside the JOURNAL table a JournalRating has been assigned to every journal pull that value and place inside a textbox.
What I've tried to do is
<?php
include 'dbc.php';
connect();
//insert form values into database
$sql = "SELECT JournalName, JournalID, Rating, JournalActive from JOURNAL where JournalActive = 1;";
//Can take out JournalActive if we do not want it
$result = mysqli_query($conn, $sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
$sql2 = "SELECT FName, LName, FacultyID from FACULTY where FacultyActive = 1;";
//Can take out JournalActive if we do not want it
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
//array to hold all of the data
$journals = array();
//print out all of the first names in the database
$rownumber = 0;
while ($row = mysqli_fetch_assoc($result)) {
$journals[$rownumber][0] = $row['JournalName'];
$journals[$rownumber][1] = $row['JournalID'];
$journals[$rownumber][2] = $row['JournalRating'];
$journals[$rownumber][3] = $row['JournalActive'];
$rownumber++;
}
$faculty = array();
//print out all of the first names in the database
$rownum = 0;
while ($row = mysqli_fetch_assoc($result2)) {
$faculty[$rownum][0] = $row['FName'];
$faculty[$rownum][1] = $row['LName'];
$faculty[$rownum][2] = $row['FacultyID'];
$rownum++;
}
?>
<!DOCTYPE html>
<head>
<link href="styles.css" rel="stylesheet">
<h1> Miami University </h1>
<h4> Information Systems and Analytics Department </h4>
<script>
(function($){
$(function(){
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('Rating'));
});
});
})(jQuery);
</script>
</head>
<body>
<div class="StyleDiv" >
<!-- coding for journal -->
<form id="form1" name="form1" method="post" action="RR2.php">
<label for="FacultyID">Faculty Name</label>
<select multiple="multiple" name="FacultyID[]" id="FacultyID">
<?php
for($i = 0; $i < sizeof($faculty); $i++) {
print "<option value=\"" . $faculty[$i][2] . "\">" . $faculty[$i][0] .' '. $faculty[$i][1] . "</option>\r\n";
}
?>
</select>
<br class="clear" />
<br class="clear" />
<label for="JournalID">Journal Name</label>
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
<br class="clear"/>
<label for="JournalRating">Journal Rating</label><input type="text" name="JournalRating" id="JournalRating" />
<br class="clear" />
<!-- coding for publication -->
<label for="Title">Publication Title</label><input type="text" name="PubID" id="PubID" />
<br class="clear" />
<label for="Year">Year</label><input type="text" name="Year" id="Year" />
<br class="clear" />
<label for="Volume">Volume</label><input type="text" name="Volume" id="Volume" />
<br class="clear" />
<label for="Issue">Issue</label><input type="text" name="Issue" id="Issue" />
<br class="clear" />
<label for="Comments">Comments</label><textarea name="Comments" id="Comments" cols="45" rows="5"></textarea>
<br class="clear" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
<br class="clear" />
</br>
</br>
</div>
</form>
<?php
//Post Parameters
$JournalID = $_POST['JournalID'];
//for($i = 0; $i < sizeof($journals); $i++) {
//if ($JournalID = $journals[$i][1]) {
//$JournalName = $journals[$i][0];
//}
//}
$Year = $_POST['Year'];
$Comments = $_POST['Comments'];
$Volume = $_POST['Volume'];
$Issue = $_POST['Issue'];
$Title = $_POST['Title'];
$JournalRating = $_POST['JournalRating'];
$FacultyMemID = $_POST['FacultyID'];
//Query
//INSERT
$stmt = $conn->prepare(" INSERT INTO PUBLICATION ( JournalID, Year, Comments, Volume, Issue, Title, JournalRating ) VALUES ( ?, ?, ?, ?, ?, ?, ? )");
$stmt->bind_param('sssssss', $JournalID, $Year, $Comments, $Volume, $Issue, $Title, $JournalRating);
$stmt->execute();
$pubID = $stmt->insert_id;
$facmemid = 0;
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( ?, ? )");
$stmt->bind_param('ii', $facmemid, $pubID);
//for ($_POST['FacultyID'] as $FacultyMemID) {
for($i = 0; $i < sizeof($FacultyMemID); $i++) {
$facmemid = $FacultyMemID[$i];
$stmt->execute();
}
mysqli_close($conn);
?>
</body>
</html>
Add the rating to your HTML using a data attribute:
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
Then you can access this using jQuery .data():
(function($) {
$(function() {
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('rating'));
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="JournalID">
<option>Select a journal</option>
<option value="1" data-rating="3">Journal #1</option>
<option value="2" data-rating="2">Journal #2</option>
<option value="3" data-rating="5">Journal #3</option>
</select>
<br>
Rating: <input id="JournalRating">

Query MySQL database using value from a dropdown, then populate a text field with the result without refreshing the page

I have a dropdown in a form that is being populated with a list of employees from a table called 'employees' in a MySQL database (employee_id, fname, lname). This is working just fine.
What I need to do next is when an employee is selected from the dropdown, I need to query the employees table to get the employees commission percentage (commission) and then populate another text field in the form with that value.
The issue is that i need to do this without reloading the page. I have been searching Google and it looks like i need to use AJAX and JavaScript. to accomplish this, my problem is that I don't know a thing about AJAX, though i do have some experience with java script.
The employees table looks like this:
employee_id
fname
lname
commission
Below is what I have so far.
<?php
// DB connection
require_once('Connections/freight.php');
// get employee list for dropdown
$query_rsEmployeeList = "SELECT employee_id, fname, lname FROM employees ORDER BY fname ASC";
$rsEmployeeList = mysqli_query($con, $query_rsEmployeeList) or die(mysqli_error($con));
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
$totalRows_rsEmployeeList = mysqli_num_rows($rsEmployeeList);
?>
<html>
<head>
<title>demo</title>
</head>
<body>
<form id="frmAddAgents" name="frmAddAgents" method="post" action="">
Agent:
<select name="employee_id" id="employee_id">
<option selected="selected" value="">- select agent -</option>
<?php do { ?>
<option value="<?php echo $row_rsEmployeeList['employee_id']?>"><?php echo $row_rsEmployeeList['fname']?> <?php echo $row_rsEmployeeList['lname']?></option>
<?php
} while ($row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList));
$rows = mysqli_num_rows($rsEmployeeList);
if($rows > 0) {
mysqli_data_seek($rsEmployeeList, 0);
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
}
?>
</select>
Commision:
<input name="commission" type="text" id="commission" size="3" />
<input type="submit" name="button" id="button" value="Add Agent To Load" />
</form>
</body>
</html>
<?php
mysqli_free_result($rsEmployeeList);
?>
OK, I looked at the other question and although it is different, I tried to change the code around to make it work, but i'm not having any luck. When I select an item from the dropdown, nothing happens. Below is the updated code. I'm not sure if i'm on the right path or not.
<?php
// DB connection
require_once('Connections/freight.php');
// get employee list for dropdown
$query_rsEmployeeList = "SELECT employee_id, fname, lname FROM employees ORDER BY fname ASC";
$rsEmployeeList = mysqli_query($con, $query_rsEmployeeList) or die(mysqli_error($con));
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
$totalRows_rsEmployeeList = mysqli_num_rows($rsEmployeeList);
?>
<html>
<head>
<title>demo</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function() {
$("#employee_id").change(function () {
var employee_id = $(this).val();
$.ajax({
type: "GET",
url: "ajax.php",
data: {employee_id: employee_id},
dataType: "json",
success: function(data){
var comm = data[0].commission;
$('#commission').empty();
$('#commission').append('<option value="0">0.00</option>');
$('#commission').append('<option value="' + comm + '">' + comm + '</option>');
$('#commission').focus();
},
beforeSend: function(){
$('#commission').empty();
$('#commission').append('<option value="0">Loading...</option>');
},
error: function(){
$('#commission').empty();
$('#commission').append('<option value="0.00">0.00</option>');
}
})
});
});
</script>
</head>
<body>
<form id="frmAddAgents" name="frmAddAgents" method="post" action="">
Agent:
<select name="employee_id" id="employee_id">
<option selected="selected" value="">- select agent -</option>
<?php do { ?>
<option value="<?php echo $row_rsEmployeeList['employee_id']?>"><?php echo $row_rsEmployeeList['fname']?> <?php echo $row_rsEmployeeList['lname']?></option>
<?php
} while ($row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList));
$rows = mysqli_num_rows($rsEmployeeList);
if($rows > 0) {
mysqli_data_seek($rsEmployeeList, 0);
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
}
?>
</select>
Commision:
<input name="commission" type="text" id="commission" size="3" />%
<input type="submit" name="button" id="button" value="Add Agent To Load" />
</form>
</body>
</html>
<?php
mysqli_free_result($rsEmployeeList);
?>
Here is the test2.php file that ajax is using to query the database
<?php
// DB connection
require_once('Connections/freight.php');
if (isset($_GET['employee_id'])) {
$employee_id = $_GET['employee_id'];
$return_arr = array();
$result = $con->query ("SELECT commission FROM employees WHERE employee_id = $employee_id");
while($row = $result->fetch_assoc()) {
$row_array = array("commission" => $row['commission']);
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
}
?>
I figured it out. Here is the final code.
test.php
<?php
// DB connection
require_once('Connections/freight.php');
// get employee list for dropdown
$query_rsEmployeeList = "SELECT employee_id, fname, lname FROM employees ORDER BY fname ASC";
$rsEmployeeList = mysqli_query($con, $query_rsEmployeeList) or die(mysqli_error($con));
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
$totalRows_rsEmployeeList = mysqli_num_rows($rsEmployeeList);
?>
<html>
<head>
<title>demo</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function() {
$("#employee_id").change(function () {
var employee_id = $(this).val();
$.ajax({
type: "GET",
url: "ajax.php",
data: {employee_id: employee_id},
dataType: "json",
success: function(data){
var comm = data[0].commission;
$('#commission').empty();
$('#commission').val(comm);
$('#commission').focus();
},
beforeSend: function(){
$('#commission').empty();
$('#commission').val('0.00');
},
error: function(){
$('#commission').empty();
$('#commission').val('0.00');
}
})
});
});
</script>
</head>
<body>
<form id="frmAddAgents" name="frmAddAgents" method="post" action="">
Agent:
<select name="employee_id" id="employee_id">
<option selected="selected" value="">- select agent -</option>
<?php do { ?>
<option value="<?php echo $row_rsEmployeeList['employee_id']?>"><?php echo $row_rsEmployeeList['fname']?> <?php echo $row_rsEmployeeList['lname']?></option>
<?php
} while ($row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList));
$rows = mysqli_num_rows($rsEmployeeList);
if($rows > 0) {
mysqli_data_seek($rsEmployeeList, 0);
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
}
?>
</select>
Commision:
<input name="commission" type="text" id="commission" size="3" />%
<input type="submit" name="button" id="button" value="Add Agent To Load" />
</form>
</body>
</html>
<?php
mysqli_free_result($rsEmployeeList);
?>
ajax.php
<?php
// DB connection
require_once('Connections/freight.php');
if (isset($_GET['employee_id'])) {
$employee_id = $_GET['employee_id'];
$return_arr = array();
$result = $con->query ("SELECT commission FROM employees WHERE employee_id = $employee_id");
while($row = $result->fetch_assoc()) {
$row_array = array("commission" => $row['commission']);
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
}
?>

Inserting data into two tables resulting in "Array to string conversion"

I'm trying to create a form for my system, user could add the numbers of input fields, the input fields are mostly drop down box with the options coming from tables in the database. The forms would insert the data into two different database. But it shows error of "Array to string conversion" Right now the data only inserted into the first table. Here's what I'd done so far
My form's code:
<form method="post" name="maklumat_akaun" action="proses_daftar_akaun.php">
<label for="NoAkaun">No. Akaun</label>
<input type="text" id="NoAkaun" name="NoAkaun" class="required input_field" required/>
<div class="cleaner_h10"></div>
<label for="KodDaerah">Daerah</label>
<?php
include('dbase.php');$sql = "SELECT KodDaerah, NamaDaerah FROM koddaerah";
$result = mysql_query($sql);
echo "<select name='KodDaerah' id='KodDaerah' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodDaerah'].">" .$kod['NamaDaerah']."</OPTION>";
}
echo "</select>";
?>
<div class="cleaner_h10"></div>
<label for="KodBahagian">Bahagian</label>
<?php
$sql = "SELECT KodBahagian, NamaBahagian FROM kodbahagian";
$result = mysql_query($sql);
echo "<select name='KodBahagian' id='KodBahagian' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodBahagian'].">" .$kod['NamaBahagian']."</OPTION>";
}
echo "</select>";
?>
<div class="cleaner_h10"></div>
<label for="KodKategori">Kategori Akaun</label>
<?php
$sql = "SELECT KodKategori, NamaKategori , SubKategori FROM kodkategori";
$result = mysql_query($sql);
echo "<select name='KodKategori' id='KodKategori' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodKategori'].">" .$kod['NamaKategori']." (".$kod['SubKategori'].")</OPTION>";
}
echo "</select>";
?>
<div class="cleaner_h10"></div>
<label for="Tarif">Tarif</label>
<input type="text" maxlength="4" size="4" id="Tarif" name="Tarif" class="required year_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')">
<div class="cleaner_h10"></div>
<!-----------------------------------------------------------//-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var max_fields = 25; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initial text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div>'+
'<td> <?php
$sql = "SELECT KodLokasi, NamaLokasi FROM kodlokasi";
$result = mysql_query($sql);
echo "<select name=\'KodLokasi[]\' id=\'KodLokasi[]\' class=\'input_field\' required ><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodLokasi'].">" .$kod['NamaLokasi']. "</OPTION>";
}
echo "</select>";
?> </td> </tr>'+
'<tr> <td> <?php
$sql = "SELECT KodJenisAkaun, NamaJenisAkaun FROM kodjenisakaun";
$result = mysql_query($sql);
echo "<select name=\'KodJenisAkaun[]\' id=\'KodJenisAkaun[]\' class=\'input_field\' required ><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodJenisAkaun'].">" .$kod['NamaJenisAkaun']. "</OPTION>";
}
echo "</select>";
?> </td>'+
'<td> <input type="text" name="NoTelefon[]" id="NoTelefon[]" value="0" class="required input_field"> </td>' +
'Batal</tr></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
});
});
</script>
<fieldset>
<div class="input_fields_wrap">
<h3 class="add_field_button">Add More Fields</h3>
<table>
<tr>
<td> <label for="KodLokasi">Lokasi</label> </td> <td> <label for="KodJenisAkaun">Jenis Akaun</label> </td> <td> <label>No.Telefon:</label> </td>
</tr>
<tr>
<td> <?php
$sql = "SELECT KodLokasi, NamaLokasi FROM kodlokasi";
$result = mysql_query($sql);
echo "<select name='KodLokasi[]' id='KodLokasi' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodLokasi'].">" .$kod['NamaLokasi']."</OPTION>";
}
echo "</select>";
?>
</td>
<td> <?php
$sql = "SELECT KodJenisAkaun, NamaJenisAkaun FROM kodjenisakaun";
$result = mysql_query($sql);
echo "<select name='KodJenisAkaun[]' id='KodJenisAkaun' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodJenisAkaun'].">" .$kod['NamaJenisAkaun']."</OPTION>";
}
echo "</select>";
?>
</td>
<td> <input type="text" name="no_telefon[]" value="0" class="required input_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')"> </td>
</tr>
</table>
</div>
</fieldset>
<!-----------------------------------------------------------//-->
<div class="cleaner_h10"></div>
<div class="cleaner_h10"></div>
<input type="submit" value="Daftar" id="submit" name="register-submit" class="submit_btn" />
<input type="reset" value="Batal" id="reset" name="reset" class="submit_btn" />
</table>
</form>
While this is my code for the inserting process.
<?php
require("dbase.php");
if ($_POST) {
$NoAkaun = isset($_POST['NoAkaun']) ? $_POST['NoAkaun'] : '';
$KodBahagian = isset($_POST['KodBahagian']) ? $_POST['KodBahagian'] : '';
$Tarif = ISSET($_POST['Tarif']) ? $_POST['Tarif'] : '';
$KodDaerah = isset($_POST['KodDaerah']) ? $_POST['KodDaerah'] : '';
$KodKategori = isset($_POST['KodKategori']) ? $_POST['KodKategori'] : '';
$NoTelefon = isset($_POST['NoTelefon']) ? $_POST['NoTelefon'] : '';
$KodLokasi = isset($_POST['KodLokasi']) ? $_POST['KodLokasi'] : '';
$KodJenisAkaun = isset($_POST['KodJenisAkaun']) ? $_POST['KodJenisAkaun'] : '';
$akaun_idAkaun = isset($_POST['akaun_idAkaun']) ? $_POST['akaun_idAkaun'] : '';
$sql = mysql_query("INSERT INTO maklumatakaun VALUES ('', '$NoAkaun' , '$KodBahagian' , '$KodDaerah' , '$KodKategori' , '$Tarif' )");
$akaun_idAkaun = mysql_insert_id();
foreach ($NoTelefon AS $i => $telefon) {
$sql = mysql_query("INSERT INTO detailakaun VALUES ('', '$KodLokasi[$i]', '$KodJenisAkaun' , '$telefon' , '$akaun_idAkaun' )");
}
echo "<script type='text/javascript'> alert('AKAUN BERJAYA DIDAFTARKAN')</script> ";
echo "<script type='text/javascript'>window.location='pilih_kategori_daftar.php'</script>";
}
?>
Can anyone help me figure this out?
The error "Array to string conversion" means you are using an array as a string somewhere in your code. That error message is usually followed by a filename and line number which should help you narrow down your search. One helpful way to see what is contained within a variable is to use the following:
echo '<pre>'; print_r($stuff); die();
If the error is happening on a line inside of a while loop you should put the echo '' before the while and the die(); after so that you can see all instances of the problem within the loop.
I found your problem on this statement
$sql = mysql_query("INSERT INTO detailakaun VALUES ('', '$KodLokasi[$i]', '$KodJenisAkaun' , '$telefon' , '$akaun_idAkaun' )");
$KodJenisAkaun is an array and you use it as a string

Categories