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.
Related
I have a php page where users type in a specific id number in a text field and click a "SEARCH" button. Upon clicking "SEARCH", a php script runs to connect to a MySQL Database table "xxx"and grab the row id that matches the id number entered by the user. The SELECT statement grabs the database values: "productionstage" and "floornotes" for the identified row.
What I need to do is take those results and display them back on my form page:
A select menu needs to dynamically display the option corresponding to the "productionstage" value for the row and then a textarea needs to display the value from "floornotes".
MY CODE:
HTML:
<form id="workorderMovement" name='workorderMovement_form' action="workordermovementGET.php" method="post">
<fieldset id="userid">
<span>Welcome <?php echo $user ?> </span>
</fieldset>
<fieldset id="sgnum">
<fieldset id="fieldset" style="text-align: center;">
<span>Please enter the SG Number</span>
</fieldset>
<input type="text" name="sgnumber" id="sgnumber"> <input type="button" name="searchButton" id="searchButton" value="SEARCH">
</fieldset>
<br/>
<br/>
<fieldset id="stageSelectField">
<fieldset id="fieldset" style="text-align: center;">
<span>Please select the Stage Completed</span>
</fieldset>
<select name="stageSelect" id="stageSelect">
<option value="Please Select">Please Select</option>
<option value="Film Done">Film Done</option>
<option value="Staged Done">Staged Done</option>
<option value="Cleanroom Done">Cleanroom Done</option>
<option value="GB2 Done">GB2 Done</option>
<option value="Bagging Done">Bagging Done</option>
<option value="Inspection Done">Inspection Done</option>
<option value="LC Done">LC Inspection Done</option>
<option value="IGU Done">IGU Done</option>
</select>
</fieldset>
<br/>
<br/>
<fieldset id="floorNotesField">
<fieldset id="fieldset" style="text-align: center;">
<span>Please enter any new work order notes</span>
</fieldset>
<textarea type="text" name="floorNotes" id="floorNotes" class="floorNotesText"></textarea>
</fieldset>
<br/>
<br/>
<br/>
</form> <!-- End Work Order Movement Form -->
<fieldset id="doneButtonField">
<input type="button" name="doneButton" id="doneButton" value="DONE">
</fieldset>
MY AJAX:
j("#searchButton").click(function(){
//send Workorder Movement Data values to php using ajax.
var sgnumber = j('#sgnumber').val();
j.ajax ({
method: 'POST',
url: "workordermovementGET.php",
data: {sgNumber: sgnumber},
dataType: 'json',
success: function( data ){
if(data.status){
j("select#stageSelect option").filter(function() {
return j(this).val() == data.productionstage;
}).prop('selected', true);
j("textarea#floorNotes").val(data.floornotes);
}
}
});
});
MY PHP:
include('inc.php');
//Get Table Options.
if (isset($_POST['sgNumber'])) {
$sgNumber = $_POST['sgNumber'];
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql= "SELECT productionstage, floornotes FROM invoices WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $sgNumber);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->bind_result($productionstage, $floornotes);
$stmt->fetch();
echo json_encode(array('status' => true, 'productionstage' => $productionstage, 'floornotes' => $floornotes));
} else {
echo json_encode(array('status' => false));
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Free the result variable.
$result->free();
//Close the Database connection.
$conn->close();
}//End If statement
?>
I need to know how to properly post part of my ajax result as a select option (the database value will match one of the predefined select options) and and take the rest of the results and display in the textarea. Also, if I can do this dynamically, that would be perfect.
Thank you!
You need to make few changes in your code, such as:
You need to place the closing </form> tag beneath the DONE button, like this:
...
<fieldset id="doneButtonField">
<input type="button" name="doneButton" id="doneButton" value="DONE">
</fieldset>
</form>
Your question doesn't really explain how you're planning to use this DONE button but I'm sure you have something in mind regarding this. However, this answer revolves around SEARCH button and the associated jQuery/AJAX and PHP functionality.
Change your jQuery/AJAX script in the following way,
$("#searchButton").click(function(){
var sgnumber = $('#sgnumber').val();
$.ajax ({
method: 'POST',
url: "workordermovementGET.php",
data: {sgNumber: sgnumber},
dataType: 'json',
success: function( data ){
if(data.status){
$("select#stageSelect option").filter(function() {
return $(this).val() == data.productionstage;
}).prop('selected', true);
$("textarea#floorNotes").val(data.floornotes);
}
}
});
});
It selects a particular productionstage from the dropdown list and populates the floornotes data based on the id value entered by the user in input text field.
And finally, process your AJAX request in the following way i.e. your PHP code should be like this:
<?php
include('inc.php');
if (isset($_POST['sgNumber'])) {
$sgNumber = $_POST['sgNumber'];
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql= "SELECT productionstage, floornotes FROM invoices WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $sgNumber);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->bind_result($productionstage, $floornotes);
$stmt->fetch();
echo json_encode(array('status' => true, 'productionstage' => $productionstage, 'floornotes' => $floornotes));
} else {
echo json_encode(array('status' => false));
}
}
?>
It uses prepared statement, so you can be sure that it's fairly secure from SQL injection attacks. Furthermore, this is a good read on how you can prevent SQL injection in PHP?
You need to make an array with your database results and echo json_encode($your_array);. That will return your data as a JSON object to the Ajax success function. Then you can parse that object for the data for the select and the data for the textarea. I can't remember how you change the selected option with JS, but I know it is usually the first or second link on a Google search/
This is a Form I want to validate. The form has a select menu and if I select an option from the dropdown it shows two textboxes and an select menu. After submitting the form, the page refreshes and the form fields that I wanted to validate also hide.
What I want to do is validating the form without a page refresh.
Edited please note this: If i select other option that is IE,Safari except other option and submit the validation arise for that also
<html>
<head>
<style>
#browserother{display:none;}
.error
{
color:#F00;
}
</style>
<?php
$otherbrowser1="";
$otherbrowser1Err="";
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true;
if(empty($_POST["ob1"]))
{
$otherbrowser1Err="* otherbrowser1 is Required";
$valid=false;
echo "<style>#browserother{display:block;}</style>";
}
else
{
$otherbrowser1=test_input($_POST["ob1"]);
}
//if valid then redirect
if($valid){
include 'database.php';
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=success.php">';
exit;
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<form id="jsform" method="post" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>Chose Your Browser: <select name = "Browser" required>
<option value = "">-- Select an Option --</option>
<option value = "1" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "1") echo "selected"; ?>>IE</option>
<option value = "2" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "2") echo "selected"; ?>>FF</option>
<option value = "3" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "3") echo "selected"; ?>>Safari</option>
<option value = "4" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "4") echo "selected"; ?>>Opera</option>
<option value = "5" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "5") echo "selected"; ?>>Other</option>
</select>
</p>
<div id="browserother">
Please Specify: <label><input type="text" name="ob1" placeholder="Other Browser1" size="50" /></label>
<span class="error"><?php echo $otherbrowser1Err?></span>
<br>
Please Specify: <label><input type="text" placeholder="Other Browser2" size="50" /></label><br>
Please Specify: <label>
<select>
<option>Select an Option</option>
<option>Select an Option</option>
</select>
</label>
</div>
<!--currentstatus starts here-->
<script type="text/javascript">
$('p select[name=Browser]').change(function(e){
if ($('p select[name=Browser]').val() == '5'){
$('#browserother').show();
}else{
$('#browserother').hide();
}
});
$('p select[name=OS]').change(function(){
if ($('p select[name=OS]').val() == 'otheros'){
$('#osother').show();
}else{
$('#osother').hide();
}
});
</script>
<!--currentstatus Ends here-->
<input type="button" value = "Submit" onClick=" document.getElementById('jsform').submit();" />
</form>
</body>
</html>
PHP basically refresh the page,You could use the submitHandler option. Basically put the $.ajax call inside this handler, i.e. invert it with the validation setup logic.
you can use some code like this :
$('#form').validate(function(){
... your validation rules come here,
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
$('#answers').html(response);
}
});
}
return false;
});
and in your html
<form id="jsform" method="post" action="">
It's difficult to understand what is the exact question.
Anyway I believe that you you don't want #browserother to be hidden in case of error ?
if so make sure that when you validate the form, add a display block for: #browserother
if(empty($_POST["ob1"]))
{
$otherbrowser1Err="* otherbrowser1 is Required";
$valid=false;
echo "<style>#browserother{display:block;}</style>";
}
Anyway very ugly code.
for dropdown:
<p>Chose Your Browser: <select name = "Browser" required>
<option value = "">-- Select an Option --</option>
<option value = "1" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "1") echo "selected"; ?>>IE</option>
<option value = "2" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "2") echo "selected"; ?>>FF</option>
<option value = "3" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "3") echo "selected"; ?>>Safari</option>
<option value = "4" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "4") echo "selected"; ?>>Opera</option>
<option value = "5" <?php if(isset($_POST["Browser"]) && $_POST["Browser"] == "5") echo "selected"; ?>>Other</option>
</select>
</p>
I don't see any code for other cases, but to validate that field only when last option selected you should replace your code with this:
if ($_POST['Browser'] == 5) {
if(empty($_POST["ob1"]))
{
$otherbrowser1Err="* otherbrowser1 is Required";
$valid=false;
echo "<style>#browserother{display:block;}</style>";
}
else
{
$otherbrowser1=test_input($_POST["ob1"]);
}
}
which means to ask for validation of ob1 field only when last value is selected.
If you wish to check validation before submission of form and after validating all fields you wish to submit form, then instead "onclick" event of button, write a submit event of form or click event of button.
Inside that event check validation and then submit your form. If any field is invalid then return it from there only.
Upon submitting the form the page refreshes, either use AJAX as said above or in your inputs that you want to be saved type
<input type="text" name="whatever_name" value="<?php if (isset($_POST['whatever_name'])) echo $_POST['whatever_name'];?>" />
This way when you submit the data that was submited will be in the form "value" attributes.
But I would advise using ajax, as it's more clean.
PHP form will refresh once you click submit button.So please do validation in javascript or jquery and after that use php for getting form values.
Remove onclick from submit button and add id and name attr to it
$("#submitbuttonid").click(function(e){
if($('input[name^=ob1]').val() == "")
{
alert("Other browser is req.");
return false;
}
});
Your code was pretty cluttered I don't even know where to begin. Your validation had logical flaws, you were mixing HTML and PHP kinda strangely and so on. I felt free to rewrite it a little bit and I added the feature you asked for.
Normally I don't do this but I want to show you a cleaner way to do such kind of tasks for the future. Of course this isn't the ideal way either (stuffing evertything into a single file is not the best practice as you may know).
For your understanding I commented everything. But basically we are sending an ajax request to the script. The script validates our form and returns a json response. This is a neat way to manage data between client and server.
The redirection process then takes place on the client side and redirects the user if everything was okay.
Please note that I did not do any security checks here
<?php
// Just a helper function to check if a form field is set and filled
function fieldSet($field)
{
return isset($field) AND !empty($field);
}
// Our dropdown will be generated from that array
$browsers = array('IE', 'FF', 'Safari', 'Opera', 'Other');
/**
* Lets process this when a POST Request came in
*/
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// Set JSON Header
header('Content-Type: application/json');
// Prepare our response
$response = array('success' => false);
// Reassign POST variables just to make it look prettier
$browser_select = $_POST['browser'];
$specifications = $_POST['specify'];
// If a browser has not been selected the user failed hard!
if(!fieldSet($browser_select) OR $browser_select == 'init')
$response['errors'][] = 'Please Select a browser';
// If we selected 'other' check if the hidden form group has any input
// and push an error to our $response array if not
if($browser_select == $browsers[4] AND (!fieldSet($specifications) OR $specifications[2] == 'init'))
$response['errors'][] = 'Another Browser is required';
// If we got no errors in our $response array the request was successful
if(!isset($response['errors']))
$response['success'] = true;
// Encode our $response array into the JSON format and
// abort script execution
echo json_encode($response);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>My Ajax Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form action="cleanform.php" method="POST" id="ajax-form">
<label for="select-browser">Choose your Browser</label>
<option value="init">Please select a browser</option>
<select name="browser" id="select-browser">
<?php foreach($browsers AS $browser): ?>
<option value="<?php echo $browser; ?>"><?php echo $browser; ?></option>
<?php endforeach; ?>
</select>
<hr>
<div id="hidden-field-group" style="display: none;">
<label for="specify-1">Please Specify</label>
<input type="text" name="specify[]" placeholder="Other Browser 1" id="specify-1">
<br>
<label for="specify-2">Please Specify</label>
<input type="text" name="specify[]" placeholder="Other Browser 2" id="specify-2">
<br>
<label for="specification-3">Please Specify</label>
<select name="specify[]" id="specify-3">
<option value="init">Please Specify</option>
<option value="SP 1">SP1</option>
<option value="SP 2">SP2</option>
</select>
</div>
<input type="submit">
</form>
<script type="text/javascript">
$(function(){
var $form = $('#ajax-form');
var $browserSelect = $form.find('select[name="browser"]');
// Hide or Show the second form group
$browserSelect.on('change', function(){
$select = $(this);
if($select.val() == 'Other'){
$('#hidden-field-group').show();
}
else{
$('#hidden-field-group').hide();
}
});
// Here we send a POST Request to the server using AJAX
$form.on('submit', function(e){
// Prevent the browser from submitting the form
// in it's native way
e.preventDefault();
$.ajax({
type: 'POST',
url: $form.action,
data: $form.serialize(), //Serialize our form fields
success: function(response)
{
// Redirect if the server returned no error
if(response.success == true)
window.location.replace("http://example.com");
//otherwise print the error
else
alert(response.errors[0]);
}
});
});
});
</script>
</body>
</html>
I have a drop down where the users's select the types and when the user clicks on other in the drop down I have to display a text box that was done..
But now How can I get the value of the text box and insert into the database.
Here is my script which displays the text box when user select's others option.
<script type="text/javascript">
function CheckColors(val) {
var element = document.getElementById('others');
if (val == 'others') element.style.display = 'block';
else element.style.display = 'none';
}
</script>
<form name="f1" method="POST" action="">
<select name="type" onchange='CheckColors(this.value);'>
<option value="1">1</option>
<option value="2">2</option>
<option value="others">others</option>
</select>
<input type="text" name="others" id="others" style='display:none' />
<input type="submit" name="submit" />
</form>
Everything working fine.. Except getting value from text box. Can anybody help me how to get the textbox value and insert into the db..
your html page a.html
<script type="text/javascript">
function CheckColors(val) {
var element = document.getElementById('others');
if (val == 'others') element.style.display = 'block';
else element.style.display = 'none';
}
</script>
<form name="f1" method="POST" action="b.php"> <!--post data to b.php-->
<select name="type" onchange='CheckColors(this.value);'>
<option value="1">1</option>
<option value="2">2</option>
<option value="others">others</option>
</select>
<input type="text" name="others" id="others" style='display:none' />
<input type="submit" name="submit" />
</form>
php page b.php
<?php
if(isset($_POST['submit']))
{
$selectType=$_POST['type'];
$inputText=$_POST['others'];
$mysqli = new mysqli("localhost", "my_user", "my_password", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql="insert into tablename (keyType,keyOther) values(?,?)";
/* create a prepared statement */
if ($stmt = $mysqli->prepare($sql)) {
/* bind parameters for markers */
$stmt->bind_param("ds", $selectType,$inputText);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
}?>
You can just use an if statement in your php code, like this:
<?php
if ($_POST['type'] == 'others') {
$type = $_POST['others'];
} else {
$type = $_POST['type'];
}
?>
Then you can insert $type into the database as you would normally, obviously being careful to correctly validate and escape the data.
you can take value as
firsrt check
if(isset($_POST["submit"]))
{
$other = $_POST["other"];
then fire your sql insert query by making connection to database.
}
else
{
echo "post ! set";
}
<?php
if(isset($_POST['submit']))
{
$others=$_POST['others'];
}
?>
I assume you're posting the form to another page, and using MySQL.
Your form should have action="page.php" Page.php being the page your submitting to.
Here is what page.php could be:
<?php
$con=mysqli_connect("ipAddress","my_user","my_password","my_db");
//your database connection
$other = $_POST['others'];
//The "others" is the name of the field your posting
mysqli_query($con,"INSERT INTO... fieldname = '$other'");
// your SQL query goes here.
?>
Also, you'll want to prevent SQL injection, here is a link to get you started with that. http://www.veracode.com/security/sql-injection
You want to make sure you validate, sanitize, check for errors, etc BEFORE you insert the data into your database. Failure to do so could cause serious problems if someone tries to attack your database.
Also, you may want to set your database connection variable in another file and include it, that way your info is a little more secure.
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.
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...
}