FIXED! See bottom for solution.
I am having an incredibly hard time with this. I've been at it for weeks now. I am trying to use AJAX to add a new record into mysql. The PHP file works 100% but I can't seem to be able to make AJAX to work with my form which has a POST method of sending data. This is my first time here on StackOverflow btw so take it easy on me. Here is the code:
HTML code:
<form name='addform' method='POST' >
<td></td>
<td><input type='text' id='cname'></td>
<td>
<select id='fuel'>
<option value='Petrol'>Petrol</option>
<option value='Diesel'>Diesel</option>
<option value='Hybrid'>Hybrid</option>
<option value='LPG'>LPG</option>
</select>
</td>
<td>
<select id='trans'>
<option value='Automatic'>Automatic</option>
<option value='Manual'>Manual</option>
<option value='Semi-Auto'>Semi-Auto</option>
</select>
</td>
<td><input type='text' id='engine'></td>
<td><input type='text' id='doors'></td>
<td><input type='text' id='total'></td>
</tr>
<tr>
<td><input type='submit' value='Add Car' onclick='addRecord()'></td>
...
I have an external .js file to handle Javascript:
function addRecord(){
if (
document.addform.cname.value == ""
|| document.addform.fuel.value == ""
|| >document.addform.trans.value == ""
|| document.addform.engine.value == ""
|| document.addform.doors.value == ""
|| document.addform.total.value == ""
)
{
alert ("Empty >field(s) - Cannot create record");
return;
}
var mydata = null;
// Mozilla/Safari
if (window.XMLHttpRequest)
{
xmlHttpReq2 = new XMLHttpRequest ();
}
// IE
else if (window.ActiveXObject)
{
xmlHttpReq2 = new ActiveXObject ("Microsoft.XMLHTTP");
}
var cname = document.getElementById('cname').value;
var fuel = document.getElementById('fuel').value;
var trans = document.getElementById('trans').value;
var engine = document.getElementById('engine').value;
var doors = document.getElementById('doors').value;
var total = document.getElementById('total').value;
mydata = '?cname='+cname+'&fuel='+fuel+'&trans'+trans+'&engine'+engine+'&doors'+doors+'&total'+total;
alert ("To Server (Add New Record):\n\nadd.php" + mydata);
xmlHttpReq2.open('POST', "add.php" +mydata, true);
xmlHttpReq2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttpReq2.send(null);
xmlHttpReq2.onreadystatechange = addRecordCallback;
}
The PHP code:
<?php
$link = mysql_connect ("194.81.104.27", "www", "www");
mysql_select_db ("xyz") or die(mysql_error());
$tot=$_POST[total];
$door=$_POST[doors];
$query = "INSERT INTO tbl
(ID, CARNAME, FUELTYPE, TRANSMISSION, ENGINESIZE, DOORS, TOTAL, AVAILABLE)
VALUES ('$_POST[cname]','$_POST[cname]', '$_POST[fuel]', '$_POST[trans]','$_POST[engine]', $door, $tot, $tot)";
$result = mysql_query($query);
mysql_close ($link);
?>
What happens is I put the info into the form, click the button and the alert tells me that it does indeed get the data from the form. But after that nothing happens. I think that the data is not being sent in the right format to the PHP file for some reason.
Thanks!
Solution was:
I managed to get it working! Part of the fault was that like #adeneo said I did not have the onclick='addRecord(); return false;' in there! Another thing I did was to remove the id of the form, not sure if that did anything at all. I have also attached "mydata" to the .send like so: xmlHttpReq2.send(mydata); and finally I had to remove a "?" which was in front of cname in the mydata variable gathering thing. So it was mydata = '?cname='+cname+... and I had to remove the ?. Thanks everyone for all the help!
Your complicating your live since you already use jquery use it for AJAX too.
$.AJAX({
url: "path to php",
type: "post",
data: $("#formID").serialize(),
});
Send this as data and you will be fine.
Sorry for has spelling, sensed from phone.
Greetings
Ezeky
There are quite a few things wrong.
You are not using the name attribute on the input/select elements. They need to have a name in order for them to be sent with the POST request. The id attribute has nothing to do with forms (except when using labels; the for attribute points to them)
<form action="/path/to/php/file.php" method="post" id="addform">
<div>
<label for="carname">CName</label>
<input type="text" name="carname" id="carname">
</div>
<div>
<label for="fuel">Fuel</label>
<select id="fuel" name="fuel">
<option value="Petrol">Petrol</option>
<option value="Diesel">Diesel</option>
<option value="Hybrid">Hybrid</option>
<option value="LPG">LPG</option>
</select>
</div>
<div>
<label for="transmission">Transmission</label>
<select id="transmission" name="transmission">
<option value="Automatic">Automatic</option>
<option value="Manual">Manual</option>
<option value="Semi-Auto">Semi-Auto</option>
</select>
</div>
<div>
<label for="engine">Engine</label>
<input type="text" id="engine" name="engine">
</div>
<div>
<label for="doors">Doors</label>
<input type="text" id="doors" name="doors">
</div>
<div>
<label for="total">Total</label>
<input type="text" id="total" name="total">
</div>
<div>
<label for="submit">Engine</label>
<input type="submit" id="submit" value="Add Car" onclick="addRecord()">
</div>
</form>
As for the javascript, it is much easier to use jQuery (or a similar library). It abstracts away all the nitty-gritty details and browser differences, and makes your life much easier.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
// When the page is done loading...
$(function () {
// When the form is submitted
$("form#addform").on("submit", function () {
// Get the form data and serialize it
var data = $(this).serialize();
// Create a POST request
var post = $.post("/path/to/php/file.php", data);
// When the request is done show a message
post.done(function () {
alert("Form submitted!");
});
// If the request fails show another message
post.fail(function () {
alert("Error! Form not submitted.");
});
// Returning false prevents the form's normal
// behaviour, i.e. its submission
return false;
});
});
</script>
Looking at your PHP code it looks like you have just learnt PHP: You are using a deprecated extension (mysql); you just use POST variables without bothering with security; and your SQL code looks a little iffy (e.g. what is AVAILABLE and why is it set to $total?); and finally, string array indices should be quoted.
// Database handle
$db = new MySQLi('194.81.104.27', 'www', 'www', 'xyz');
// SQL query with placeholders
$sql = "INSERT INTO tbl (CARNAME,FUELTYPE,TRANSMISSION,ENGINESIZE,DOORS,TOTAL) VALUES (?,?,?,?,?,?)";
// Create a statement object
$stmt = $db->prepare($sql);
// Fill in the placeholders
$stmt->bind_param('ssssii', $carname, $fuel, $transmission, $engine, $doors, $total);
// Set the values
$carname = filter_input(INPUT_POST, 'cname', FILTER_SANITIZE_STRING);
$fuel = filter_input(INPUT_POST, 'fuel', FILTER_SANITIZE_STRING);
$transmission = filter_input(INPUT_POST, 'transmission', FILTER_SANITIZE_STRING);
$engine = filter_input(INPUT_POST, 'engine', FILTER_SANITIZE_STRING);
$doors = filter_input(INPUT_POST, 'doors', FILTER_SANITIZE_NUMBER_INT);
$total = filter_input(INPUT_POST, 'total', FILTER_SANITIZE_NUMBER_INT);
// If the statement was not executed then there was an error
if ($stmt->execute() === false) {
header('HTTP/1.0 404 Not Found', true, 404);
}
// Done
Note: I never tested any of the examples. I just wrote them down in my text editor, as needed, so you will probably need to adapt them.
I think part of the issue is that you're pasting data "mydata = '?cname='+cname+'&fuel..." onto the back of the URL like you would if using GET as your transmittal method, but you define POST as the transmittal method, so doing this is unnecessary.
The POST method encapsulates the data for you.Try removing the +mydata from this line
xmlHttpReq2.open('POST', "add.php" +mydata, true);
Also, two more lines down, you're calling a function that's not listed here
xmlHttpReq2.onreadystatechange = addRecordCallback;
Seeing what that function does would be helpful.
Related
I am working on a html form which will connect to a database using a php script to add records.
I have it currently working however when I submit the form and the record is added , the page navigates to a blank php script whereas I would prefer if it when submitted , a message appears to notify the user the record is added but the page remains the same. My code is below if anyone could advise me how to make this change.
Html Form :
<html>
<form class="form" id="form1" action="test.php" method="POST">
<p>Name:
<input type="Name" name="Name" placeholder="Name">
</p>
<p>Age:
<input type="Number" name="Age" placeholder="Age">
</p>
<p>Address
<input type="text" name="Address" placeholder="Address">
</p>
<p>City
<input type="text" name="City" placeholder="City">
</p>
</form>
<button form="form1" type="submit">Create Profile</button>
</html>
PHP Database Connection Code :
<html>
<?php
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx",
"Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values
('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
</html>
Typically your action file would be something like thankyou.php where you'd put whatever message to the user and then maybe call back some data that was submitted over. Example:
Thank you, [NAME] for your oder of [ITEM]. We will ship this out to you very soon.
Or this file can be the the same page that your form resides on and you can still show a thank you message with some javascript if your page is HTML. Something like:
<form class="form" id="form1" action="test.php" method="POST onSubmit="alert('Thank you for your order.');" >
I am taking into consideration that your PHP Database Connection Code snipplet that you posted above is called test.php because you have both connecting to the data base and inserting data into the database in one file.
Taking that into consideration, I think the only line you are missing, to return you back to to top snipplet of code that I shall call index.php would be an include statement just after the data has been added to the database
$query = "INSERT INTO [SalesLT].[Test]
(Name,Age,Address,City) Values ('$Name','$Age','$Address','$City');";
$params1 = array($Name,$Age,$Address,$City);
$result = sqlsrv_query($conn,$query,$params1);
echo "Data added";
include 'index.php'; //This file is whatever had the earlier form
Once you hit the submit button on your form, test.php is called, your data is handled and passed back to index.php.
N.B:
The other thing i should mention is to make it a habit of using mysqli_real_escape_string() method to clean the data that is in the $_POST[]; because in a real website, if you don't, you give an attacker the chance to carry out SQL injection on your website :)
you said page is coming blank and data is saved so i assumed that there are two files one which contains form and another which contains php code (test.php).
when you submit the form you noticed that form is submitted on test.php
and your test.php has no any output code that's why you are seeing blank page.
so make a page thankyou.php and redirect on it when data is saved.header('Location: thankyou.php'); at the end of file.
Put this in form action instead of test.php
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
Put your php code at top of the page.
$Name = $_POST['Name'];
This is step closer to being a safer way to posting into your db as well.
$Name =mysqli_real_escape_string( $_POST['Name']);
I like the jscript Alert from svsdnb to tell user data was successfully added to db.
This is not intended to be an out of the box solution; it's just to get you pointed in the right direction. This is completely untested and off the top of my head.
Although you certainly could do a redirect back to the html form after the php page does the database insert, you would see a redraw of the page and the form values would be cleared.
The standard way to do what you're asking uses AJAX to submit the data behind the scenes, and then use the server's reply to add a message to the HTML DOM.
Using JQuery to handle the javascript stuff, the solution would look something like this:
HTML form
<html>
<!-- placeholder for success or failure message -->
<div id="ajax-message"></div>
<form class="form" id="form1">
<p>Name: <input type="Name" name="Name" placeholder="Name"></p>
<p>Age: <input type="Number" name="Age" placeholder="Age"></p>
<p>Address: <input type="text" name="Address" placeholder="Address"></p>
<p>City: <input type="text" name="City" placeholder="City"></p>
<!-- change button type from submit to button so that form does not submit. -->
<button id="create-button" type="button">Create Profile</button>
</form>
<!-- include jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- ajax stuff -->
<script>
// wait until DOM loaded
$(document).ready(function() {
// monitor button's onclick event
$('#create-button').on('click',function() {
// submit form
$.ajax({
url: "test.php",
data: $('#form1').serialize,
success: function(response) {
$('#ajax-message').html(response);
}
});
});
});
</script>
</html>
test.php
<?php
// note: never output anything above the <?php tag. you may want to set headers.
// especially in this case, it would be better to output as JSON, but I'm showing you the lazy way.
$serverName = "xxxxxxxxxxxxxxxxxxxxxxxx";
$options = array( "UID" => "xxxxxxxxx", "PWD" => "xxxxxxxx", "Database" => "xxxxxxxxxx");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false ) {
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$Name = $_POST['Name'];
$Age = $_POST['Age'];
$Address = $_POST['Address'];
$City = $_POST['City'];
// if mssql needs the non-standard brackets, then put them back in...
// note placeholders to get benefit of prepared statements.
$query = "INSERT INTO SalesLT.Test " .
"(Name,Age,Address,City) Values " .
"(?,?,?,?)";
$params1 = array($Name,$Age,$Address,$City);
$success = false;
if($result = sqlsrv_query($conn,$query,$params1)) {
$success = true;
}
sqlsrv_close($conn);
// normally would use json, but html is sufficient here
// done with php logic; now output html
if($success): ?>
<div>Form submitted!</div>
<?php else: ?>
<div>Error: form not submitted</div>
<?php endif; ?>
I'm trying to get multiple checked checkbox value data added to mysql with php without reloading the form page and show confirmation message in div on form page. At the moment, showing on div works but data is not being sent.
I already have done another similar one which I had almost the same code that had the input as text area so I changed that part and it works but the this one is not working. Could anyone give me help here?
form is in vote.php:
<html>
<form action="vote_received.php" method="post" target="" id="vote-submit">
<input type="hidden" name="recieved-date" id="todayDate" />
<input type="hidden" name="user-occup" id="user-occup" value="<?php $_SESSION['occupation']; ?>" />
<input type="checkbox" name="voting[]" value="How might we improve driver facilities such as lunch rooms or break rooms?" id="voting_1">
<label for="voting_1">How might we improve driver facilities such as lunch rooms or break rooms?</label>
<input type="checkbox" name="voting[]" value="How might be increase driver security at night time?" id="voting_2">
<label for="voting_2">How might be increase driver security at night time?</label>
<input type="checkbox" name="voting[]" value="How might we change the on-call communication with management?" id="voting_3">
<label for="voting_3">How might we change the on-call communication with management?</label>
<input type="checkbox" name="voting[]" value="How might we enhance the passenger conflict management system?" id="voting_4">
<label for="voting_4">How might we enhance the passenger conflict management system?</label>
<br><br>
<input type="submit" name="submit" value="Submit" class="btn align-right"></form>
<script>
$("#vote-submit").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
$messages = $("input[name='voting[]']"),
$occup = $form.find('input[name="user-occup"]'),
$submit = $form.find('button[type="submit"]'),
message_value = $messages.val(),
url = $form.attr('action');
var posting = $.post(url, { submission : message_value});
posting.done(function(data) {
/* Put the results in a div */
$("#vote_success").html('<h2>THANK YOU!</h2><p>Thank you for your voting. Meeting invitations will be send out on December 7th, 2017.');
/* Hide form */
$form.hide();
});
});
</script>
</html>
the vote_received.php is:
<?php
session_start();
if(isset($_POST['vote-submit'])) {
$voteArray=$_POST['voting'];
$conn = mysqli_connect($servername, $username, $password, $database);
if(is_null($voteArray)) {
echo("<p>You didn't select any topic.</p>\n");
} else {
$N = count($voteArray);
for($i=0; $i < $N; $i++) {
$var1 = $voteArray[$i];
$jobTitle = $_SESSION['occupation'];
$sql = "INSERT INTO vote_response (occupation, voting,
created) VALUES('$jobTitle', '$var1', now())";
$success = mysqli_query($conn, $sql);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
echo $var1;
$conn->close();
}
}
}
?>
Thank you very much!
try to change this part of your code
var $form = $(this),
$messages = $("input[name='voting[]']"),
$occup = $form.find('input[name="user-occup"]'),
$submit = $form.find('button[type="submit"]'),
message_value = [],
url = $form.attr('action');
$.each($messages, function(idx, val){
message_value.push($(val).val());
});
var posting = $.post(url, { submission : message_value});
on further reading of your code, try to change this part of you code also:
if(isset($_POST['submission'])) {
$voteArray=$_POST['submission'];
The user goes change the nm_peca, will select tipo_preco and then find the price in MySQL database to complete the textbox vlr_peca.
What do I need to do to get the value of products?
<?php>
$query = mysql_query("SELECT id, nm_peca, vlr_original,
vlr_paralelo, fabricante
FROM peca
ORDER BY nm_peca");
<select id="nm_peca" name="nm_peca"
title="Selecione um status."
class="form-control" size="1">
<option value="">Status</option>
<option value="N/A">N/A</option>
<option value="S">S - Substituir</option>
</select>
</div>
</div>
<select id="tipo_preco" name="tipo_preco"
class="form-control" size="1">
<option value="">Tipo</option>
<option value="Peça Original">Original</option>
<option value="Peça Paralela">Paralela</option>
</select>
</div>
</div>
<div class="col-md-1">
<div class="input-group btn-group">
<input type="text" value="????????" name="vlr_peca"
class="form-control" readonly>
</div>
</div>
Well your code is a little confusing because what you really want is not clear to me, maybe it doesn't help that it's in a different language. What is the $query for? You are not using this in the code, so you'll need to do this to access it:
$rows = array();
while ($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
print '<pre>'. print_r($rows, true) . '</pre>';
Then you'll need to use an ajax request OR setup javascript vars on the front end to make changes. I'm just going to go ahead and use the latter since it's more illustrative.
So I would add the cdn of jQuery which is https://code.jquery.com/jquery-2.1.4.min.js to the top of your file in a tag like:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
Then you'll need to add an input id to that input tag like <input id="dynamic-variable" type="text" value="????????" name="vlr_peca"> and then use something like:
<script type="text/javascript">
$(document).ready(function() {
$('#tipo_preco').change(function() {
if ($(this).val() == 'Peça Original') {
$('#dynamic-variable').val('$5,000,000,000.00');
} else if ($(this).val() == 'Peça Paralela') {
$('#dynamic-variable').val('$300 billion trillion dollars');
} else {
$('#dynamic-variable').val('Bro. Choose one.');
}
});
});
</script>
I'm not going to program this whole thing for you since I don't know what kind of data you are getting from your DB, but this should be good enough to get you started. You need to be able to access the data in the mysql query, and you may just want to use the <?= $db_variable ?> or <?php echo $db_variable?> in your javascript where I have the amount variables. This should be good enough to get you started. Read up on php mysql_query and jQuery
AJAX
If you were to do this via AJAX, you would need a second page that accesses the database, you'd have to $_GET or $_POST variables and then print back the amount.
So your JavaScript would be something like this:
$.get('/the/page.php?tipo_preco=' + $('#tipo_preco').val(), function(response) {
if (response != '') {
$('#dynamic-variable').val(response);
}
});
And your second page would be something like this:
<?php
// code that sets up the database
// .... //
// now your code
$selected_value = $_GET['tipo_preco'];
$result = mysql_query("SELECT price FROM table WHERE column_val = '" . mysql_real_escape_string($selected_value) . "'");
$row = mysql_fetch_assoc($result); // assuming you're only fetching one row
print $row['price'];
?>
I would suggest you just go with the first suggestion, it's faster, less moving parts.
I'm trying to pass multiple values to the javascript function "get2" and then call "data2.php" file in order to retrieve data from the database according to the submitted values from the dropdown list/textbox. Both work separately but not together, the error I'm getting is "Undefined index". Can anyone help me please?
<script type="text/javascript">
function get2() {
$.post('data2.php', { gender: form2.gender.value },
function(output) {
$('#gender').html(output).show();
}
);
$.post('data2.php', { skills: form2.skills.value },
function(output) {
$('#skills').html(output).show();
});
}
</script>
...
...
<form name="form2">
<Select name="gender">
<OPTION>Male</OPTION>
<OPTION>Female</OPTION></SELECT>
What is the patients relationship status?
(hold "Ctrl" key to select multiple options at one time):
<br/><br/>
<BR>
<BR>
<select name="skills">
<OPTION value="Single" selected="selected">Single</OPTION>
<OPTION value="With partner">With partner</OPTION>
<OPTION value="Separated from partner">Separated from partner</OPTION>
<OPTION value="Partner died">Partner died</OPTION>
<OPTION value="DK">DK</OPTION>
</select>
<BR>
<BR>
<INPUT TYPE="button" VALUE="search" onClick="get2();">
</form>
<div id="gender"></div>
<div id="skills"></div>
DATA2.PHP
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("grist");
$gender = $_POST['gender'];
$skills = $_POST['skills'];
if (($gender==NULL) && ($skills==NULL)) {
echo"please enter gender and skills!";
}
else
{
$dob4 = mysql_query("SELECT * FROM patients WHERE gender='$gender' AND relationship_status='$skills'");
//$dob_num_rows = mysql_num_rows($dob);
while($row4 = mysql_fetch_array($dob4)){
$a=$row4['patient_id'];
$b=$row4['gender'];
$c=$row4['dob'];
echo "<b>Patient:</b> $a";
echo "<b>Patient:</b> $b";
echo "<b>Patient:</b> $c";
}
}
?>
This is how you can send two values to a page using a POST request:
<script type="text/javascript">
function get2() {
$.post('data2.php', { gender: form2.gender.value,
skills: form2.skills.value },
function(output) {
$('#gender').html(output).show();
$('#skills').html(output).show();
}
);
}
</script>
Note that now this updates both the gender and skills elements. I'm not sure what you want to do; data2.php requires/permits using both parameters.
You should also sanitize the user input: currently you are vulnerable to SQL injection attacks. It would be even better to use a database client library that permits using prepared statements, such as PDO. The old mysql library you are using is deprected and will be removed from PHP at some point.
OK, let me start off by saying im an amateur, so all your help is really appreciated.
OK, I have a form, called 'skills.php' and on this form, you enter the following fields 'Skills_ID, Employee_ID, First_name, Last_name and Skill'. I have used java so when you select employee_ID, the name fields change to what employee that is (linked to employee table).
HOWEVER, since i have added this function, i can not save my form data into my database. Maby i accidently deleted a line of code when implementing the java function. Can someone help me figure it out? below is my form 'Skill.php':
<html>
<?php
// Connecting to database
$pdo = new PDO("mysql:host=localhost;dbname=hrmwaitrose;charset=utf8", "root", "");
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!-- Online Jquery -->
<title>Skill</title>
</head>
<body>
<div id="content">
<h1 align="center">Add Employee Skill</h1>
<form action="insertskill.php" method="post">
<div>
<p>
Skill ID:
<input type="text" name="Training_ID">
</p>
<p>
Employee ID:
<select id="Employee_ID">
<option value="">Select one</option>
<?php
$st = $pdo->prepare("SELECT Employee_ID FROM Employee");
$st->execute();
$rows = $st->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
?><option value="<?php echo $row ['Employee_ID']; ?>"><?php echo $row ['Employee_ID']; ?></option><?php
}
?>
</select>
<p>
First name:
<input type="text" name="First_name" id="First_name">
</p>
<p>
Last name:
<input type="text" name="Last_name" id="Last_name">
</p>
<p>
<p>Skill: <select name="Skill">
<option value="">Select...</option>
<option value="Checkouts">Checkouts</option>
<option value="Fresh goods">Fresh goods</option>
<option value="Dry goods">Dry goods</option>
<option value="Fruit & Veg">Fruit & Veg</option>
<option value="Operations">Operations</option>
</select>
</p>
<input type="submit">
<INPUT Type="BUTTON" VALUE="Back" ONCLICK="window.location.href='index.html'">
</form>
</div>
<script type="text/javascript">
$(function() { // This code will be executed when DOM is ready
$('#Employee_ID').change(function() {
var $self = $(this); // jQuery object with the select inside
$.post("insertskill.php", { Employee_ID : $self.val()}, function(json) {
if (json && json.status) {
$('#First_name').val(json.name);
$('#Last_name').val(json.lastname);
}
})
});
})
</script>
</body>
</html>
And here is the code used when the submit button is pressed 'insertskill.php':
<?php
$pdo = new PDO("mysql:host=localhost;dbname=hrmwaitrose;charset=utf8", "root", "");
header("Content-Type:application/json; Charset=utf-8");
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
$st->execute(array ('employee_id' => $_POST['Employee_ID']));
$data = $st->fetch(PDO::FETCH_ASSOC);
echo json_encode(array ('status' => true, 'name' => $data ['First_name'], 'lastname' => $data ['Last_name']));
?>
Just by looking at this code imn pretty sure i might of accidently deleted the coding to insert it into database, HOWEVER i dont know how to fix it :( can someone help? much appreciated! Thanks in advance
in "insertskill.php" line 6:
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
You're performing a SELECT query (read), sounds to me more like you wanted an INSERT query (write).
An INSERT statement in your case would be something similar to:
$st = $pdo->prepare("INSERT INTO Employee (Training_Id,Employee_Id,First_Name,Last_Name,Skill) VALUES (:training_id,:employee_id,:first_name,:last_name,:skill)")
$st->execute(array(':training_id' => $training_id, ':employee_id' => ...));
First, watch out. Java is not JavaScript!
And you're right, you removed the INSERT lines. There are several articles on the web about how to do that. Here is one. Just google PDO Insert for more results.
You should put these INSERT commands in your insertskill.php file and create another one, maybe fetchName.php or something like that, with the code that you presented to return first and last name for an employee based on its id, and use that in your JavaScript $.change() function. It doesn't make sense for a file called insertskill.php to fetch data.
And your forgot to specify that you're expecting a JSON in your $.post() command. Do that instead:
$.post("insertskill.php", { Employee_ID : $self.val()}, function(json) {
if (json && json.status) {
$('#First_name').val(json.name);
$('#Last_name').val(json.lastname);
}
}, 'json'); // Here!
First thing to say is that you are NOT using Java. You are using JavaScript (actually ECMAScript which is VERY VERY different from Java.
Next, you are correct, that there is now no INSERT statement there at all, you will need to write one to insert whatever data you want to insert.
HOWEVER, you also need to somehow tell the difference between when insertskill.php is called for an Ajax request (to get the names for the form) and when it is called to insert the data. So on your Javascript (jQuery I guess) request, you could change the url to:
$.post("insertskill.php?ajax"
and then in insertskill.php do:
if(isset($_GET['ajax'])) {
header("Content-Type:application/json; Charset=utf-8");
$st = $pdo->prepare("SELECT First_name, Last_name FROM Employee WHERE Employee_ID = :employee_id");
$st->execute(array ('employee_id' => $_POST['Employee_ID']));
$data = $st->fetch(PDO::FETCH_ASSOC);
echo json_encode(array ('status' => true, 'name' => $data ['First_name'], 'lastname' => $data ['Last_name']));
}
else {
// Do the insert statement stuff...
}