I'm developing a CRUD application as part of a course I am studying.
I'm able to read data from my DB, however I am now trying to add data - a new employee in this case as I am developing a company directory and so far I'm unsuccessful.
I know the issue isn't the connection with the DB as I'm able to read data. However the function getEmployeeData(); function to refresh the display of current employee records after the new addition is never called in the $.post callback func so I suspect the error happens before this point. You'll see in my code below that I'm attempting to print the firstName variable to the console. The firstName does appear in the console when the form is submitted but only for less than a second then it disappears.
I'm really stumped as to what is causing this issue.
Please see my code below:
The form in index.html:
<!--Form to add employee-->
<div class="modal fade" id="addEmployeeModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Employee</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="addEmployeeForm" onsubmit="addEmployee()">
<div class="modal-body">
<div class="names">
<input type="text" class="form-control" style="width: 48% !important;" id="newFirstName" name="newFirstName" placeholder="First Name..." required>
<input type="text" class="form-control" style="width: 48% !important;" id="newLastName" name="newLastName" placeholder="Last Name..." required>
</div>
<div class="names">
<input type="email" class="form-control" id="newEmail" name="email" placeholder="E-mail">
</div>
<div id="location-dept">
<select id="add-employee-dept-list" class="form-select" aria-label="Default select example" name="newDepartment">
<option selected>Department</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<!--End of add employee modal-->
The addEmployee() function:
function addEmployee() {
let firstName = $('#newFirstName').val();
let lastName = $('#newLastName').val();
let email = $('#newEmail').val();
let departmentID = $('#add-employee-dept-list').val();
console.log(firstName);
$.post(
"php/addNewEmployee.php",
{
fname: firstName,
lname: lastName,
email: email,
department: departmentID
},
function(data) {
getEmployeeData();
alert(data + "It worked");
}
)
}
addNewEmployee.php:
<?php
// example use from browser
// http://localhost/companydirectory/libs/php/insertDepartment.php?name=New%20Department&locationID=<id>
// remove next two lines for production
echo($_POST['$firstName']);
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true);
// this includes the login details
include("config.php");
header('Content-Type: application/json; charset=UTF-8');
$conn = new mysqli($cd_host, $cd_user, $cd_password, $cd_dbname, $cd_port, $cd_socket);
if (mysqli_connect_errno()) {
$output['status']['code'] = "300";
$output['status']['name'] = "failure";
$output['status']['description'] = "database unavailable";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
exit;
}
// SQL statement accepts parameters and so is prepared to avoid SQL injection.
// $_REQUEST used for development / debugging. Remember to change to $_POST for production
$jobTitle = "";
$query = $conn->prepare('INSERT INTO personnel (firstName, lastName, jobTitle, email, departmentID) VALUES(?,?,?,?)');
$query->bind_param("si", $_REQUEST['fname'], $_REQUEST['lname'], $jobTitle, $_REQUEST['email'], $_REQUEST['department']);
$query->execute();
if (false === $query) {
$output['status']['code'] = "400";
$output['status']['name'] = "executed";
$output['status']['description'] = "query failed";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
exit;
}
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
$output['data'] = [];
mysqli_close($conn);
echo json_encode($output);
?>
Related
My target is, after I submit the form, there'll be a modal after reload that shows the transaction details. I have made a next page transaction details, however, it is much better to do the receipt php on onload modal after submission. But I don't know how to start. I provided a screenshot below of my current work. Any help will be appreciated. Thank you
View:
<button type="button" data-id="<?php echo $rows->userID; ?>" data-firstname="<?php echo $rows->firstname; ?>" class=" showmodal btn btn-success btn-sm text-bold " data-toggle="modal" data-target="#fundModal"><i class="fas fa-hand-holding-usd mr-1"></i> FUND </button> // This button shows modal when clicked
//This is my modal for transferring fund
<div class="modal fade" id="fundModal" tabindex="-1" role="dialog">
<div class="modal-dialog " role="document">
<div class="modal-content">
<div class="modal-header bg-green">
<h5 class="modal-title text-bold" id="exampleModalLabel">Fund</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body bg-white text-center">
<label><h3>Transfer fund:</h3></label>
<br>
<!-- FORM -->
<div id="errorMessage" style="color: red; display: none; font-size: 11px"></div>
<form method="POST" action="<?php echo site_url('network/form_validation');?>">
<div class="input-group input-group-sm" style="width: 100%" >
<input type="hidden" id="usertransferid" name="userID">
<input type="hidden" id="firstname" name="receiptname" value="<?php echo $rows->firstname; ?>">
<div class="col-lg-12" >
<input type="text" placeholder="Enter Amount" name="amount" autocomplete="new-amount" value="" class="form-control number" id="box" >
<br>
<?php echo $this->session->flashdata('warning'); ?>
<input type="password" placeholder="Enter Password" autocomplete="new-password" name="fundpass" class="form-control" id="password" required ">
<br>
<!-- buttons -->
<input type="submit" class="btn btn-success text-bold" name="save" id="insert" value="Transfer">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Controller:
public function form_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$this->load->library('form_validation');
$this->form_validation->set_rules('fundpass', 'fundpass', 'callback_password_check');
if($this->form_validation->run() == false) {
echo '<script>alert("Invalid input of Password!");</script>';
redirect('network/agents', 'refresh');
}
else {
if($this->form_validation->run())
{
$ref= $this->session->userdata('uid') + time ();
$id = $this->input->post('userID');
$fname = $this->input->post('receiptname');
$pData = array(
'userID' => $id,
'transactionSource' => 'FR',
'refNumber' => 'FI' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"in",
);
$this->networks->fundin($pData);
$ref= $this->session->userdata('userID') + time ();
$data1 = array(
'userID' => $this->session->userdata('uid'),
"transactionSource" => 'FR',
"refNumber" => 'FO' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"out",
);
$this->networks->insert_data($data1);
// return json_encode($data1);
$_SESSION["amount"] = $this->input->post("amount");
$_SESSION["receivedID"] = $id;
$_SESSION["receiptFName"] = $fname;
$_SESSION["reference"] = $this->input->post("refNumber");
redirect(base_url() . "network/receipt");
}
else
{
$this->index();
}
}
}
public function password_check($fundpass)
{
$id = $this->session->userdata('uid');
if($this->session->userdata('password')!== md5($fundpass)) {
$this->form_validation->set_message('password_check', 'The {field} does not match');
return false;
}
return true;
}
Model:
function fundin($data)
{
// Fund in
$id = $this->input->post('userID');
$sqlInsertLedger = "INSERT INTO transaction_ledger (transactionSource, transType, refNumber, userID, amount, currentBalance, previousBalance, remarks, createdBy)
select '".$data['transactionSource']."', '".$data['transType']."', '".$data['refNumber']."', ".$data['userID'].", ".$data['amount'].", sum(TU.currentPoints + ".$data['amount'].") as totalPoints, TU.currentPoints,
'funded by agent', '".$this->session->userdata('uid')."'
from users TU where TU.userID=?";
$Q = $this->db->query($sqlInsertLedger, $data['userID']);
//update user table
$sqlUpdate = "update users set currentPoints = currentPoints + ? where userID = ?";
$Q = $this->db->query($sqlUpdate, array($data['amount'], $data['userID']));
}
function insert_data($data1)
{
// fund out
$sql1 = "select * from transaction_ledger where userID = ? order by ledgerID desc limit 0,1";
$Q1 = $this->db->query($sql1, $data1['userID']);
$R1 = $Q1->row_array();
$ref= $this->session->userdata('userID') + time ();
$idata1 = array(
'userID' => $data1['userID'],
'transactionSource' => 'FR',
'transType' => 'out',
'refNumber' => 'FO' . $ref,
'amount' => $data1['amount'],
'currentBalance' => $R1['currentBalance'] - $data1['amount'],
'previousBalance' => $R1['currentBalance'],
'remarks' => 'transfer fund to agent',
);
$this->db->insert('transaction_ledger', $idata1);
$sqlUpdate = "update users set currentPoints = '".$idata1['currentBalance']."', dateUpdated = '".date('Y-m-d h:i:s')."'where userID = ?";
$this->db->query($sqlUpdate, $idata1['userID'] );
}
You can programmatically open the bootstrap modal when document ready
Just like
$(document).ready(function(){
$("#fundModal").modal('show');
});
</script>
I would suggest to do with ajax call for better user experience.
$( "#formId" ).on('submit', function(e){
e.preventDefault();
let $form = $(this);
$.post( 'post-url-here', $form.serialize(), function(result) {
var result = JSON.parse(result);
if( result.status == 'success' ) {
$("#fundModal").modal('show');
}
});
});
I have a form in a bootstrap modal window and what is happening, is when I click the 'send' button, the modal closes and a white page displays the result of my action call to contact-form.php and shows the error message for blank field but thid should be showing in the message div in the form in the the modal window.
I am obviously doing something fundementally wrong and would appreciate any help you can offer. I wouls have done a snippet but couldn't see how to include php code.
Many thanks
Bootstrap V3.3.7
UPDATE: The form works fine if i use as normal form outside of the modal
window.
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal__title"><div style="color: white; margin-top: -14px; margin-left: 36px;">Contact Us</div></h2>
<div style="color: white; margin-left: 36px; margin-bottom: 20px;">If you need to contact us, please use this form and we shall respond as soon as possible. Thanks</div>
</div>
<div class="modal-body">
<div class="content-block contact-3">
<div class="container">
<div class="row">
<div class="col-md-9">
<div id="contact" class="form-container">
<div id="message"></div> <-ERROR SHOULD BE DISPLAYED HERE
<form method="post" action="js/contact-form.php" name="contactform" id="contactform">
<div class="form-group">
<input name="name" id="name" type="text" value="" placeholder="Name" class="form-control" />
</div>
<div class="form-group">
<input name="email" id="email" type="text" value="" placeholder="Email" class="form-control" />
</div>
<div class="form-group">
<input name="phone" id="phone" type="text" value="" placeholder="Phone" class="form-control" />
</div>
<div class="form-group">
<textarea name="comments" id="comments" class="form-control" rows="3" placeholder="Message" id="textArea"></textarea>
<div class="editContent">
<p class="small text-muted"><span class="guardsman">* All fields are required.</span> Once we receive your message we will respond as soon as possible.</p>
</div>
</div>
<div class="form-group">
<button class="btn btn-default" type="button" class="modal" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit" id="cf-submit" name="submit">Send</button>
</div>
</form>
</div>
<!-- /.form-container -->
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!--// END Contact 3-1 -->
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
contact-form.php
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Please enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Phone number can only contain digits and no spaces.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "yourname#yourdomain.com";
$address = "yourname#yourdomain.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name from your website, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name by email, $email or by phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
sendmail.js
jQuery(document).ready(function () {
$('#contactform').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
$("#message").fadeOut(500, function () {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(),
},
function (data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#submit').removeAttr('disabled');
if (data.match('success') != null) {
$('#contactform').fadeOut('slow');
$("#message").delay(3000).fadeOut();
$("#contactform").delay(4000).fadeIn();
$("#contactform").css("margin-top", "40px !important");
$("#contactform").trigger("reset");
}
}
);
});
return false;
});
});
I can't test you code but in my opinion i would not do the submit action with $(form).submit().... also if you are doing a event.preventDefault(), i explain better, you are doing an ajax call and with different errors you have differents answers, so in your place i would delete the action in the html at on click of the send button i would do an ajax call and manage the answer.Try in this way, because i think that if you use the submit in that way the browser interpret the submit form also because you are using the action url to send the call.
$('#cf-submit').click(function(){
name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
comments = $('#comments').val();
$.ajax({
url : 'js/contact-form.php',
type : 'POST',
data : {
name : name,
email : email,
phone : phone,
comments : comments,
},
dataType : 'html',
success : function(response){
$('#message').html(response);
}
});
});
I think you forget to put exit(); at the end of file contact-form.php
I worked for php over last 7-8 years. But i never try ajax, jquery or javascript more then very simply copy-paste work.Now i need jquery for my work.I almost finished all worked except a login with password process. So i try to write php and jquery code for this.
Here is my code:
index.php
<html>
<head>
<script>
function login() {
// get values
var db = $("#db").val();
var pass = $("#pass").val();
// Check record
$.post("check.php", { db: db, pass: pass }, function (data) {
if (data.status=='s') //status is proper of the json object, which we gave in php code
{
var form = $('<form action="success.php" method="post">' +
'<input type="text" name="db" value="new1" />' +
'<input type="text" name="pass" value="12345" />' +
'</form>');
$('body').append(form);
form.submit();
} else {
alert( "status: " + data );
}
// close the popup
$("#pass").modal("hide");
// clear fields from the popup
$("#pass").val("");
});
}
</script>
</head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body style="color:#ece9e9;background:#184C5D;"><div style="margin-top:25%; margin-left:25%; margin-right:auto;">
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "new1";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo '<button class="btn btn-success" data-toggle="modal" data-target="#pass">Login</button><br/><br/>';
$conn->close();
?>
</div>
<!-- Modal - login -->
<div class="modal fade" id="pass" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Enter Password</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="pass">Password</label>
<input type="text" name="pass" id="pass" placeholder="pass" class="form-control"/>
</div>
<?php echo '<input type="hidden" name="db" id="db" value="'.$dbname.'">'; ?>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="login()">Login</button>
</div>
</div>
</div>
</div>
<!-- // Modal -->
</body>
</html>
Here is code for check.php
<?php
$server = "localhost";
$username = "root";
$password = "";
$dbname = "$_POST[db]";
$pass = "$_POST[pass]";
$conn = new mysqli($server, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$dpass ="";
$sql = "SELECT pass FROM project WHERE id ='1' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dpass = $row["pass"];
}
} else {}
if ($pass == $dpass) {
echo "s";
} else {
echo "xx";
}
$conn->close();
?>
My problem is when try with correct password [12345] its showing xx in alert pop. Can anyone find out what i missing? Because i write that jquery code from 3 different source. in other hand, when i test check.php with a simple post method page, its work. means check.php is ok.
You've got 2 HTML elements with id="pass":
line 47:
<div class="modal fade" id="pass" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
and line 57:
<input type="text" name="pass" id="pass" placeholder="pass" class="form-control" />
Therefore your var pass from line 8 will take the value of the first element with id 'pass' it will encounter. In this case that will be the div from line 47.
As #jeroen van der Hel said, i've got 2 HTML elements with id="pass". So first i need to change pass to anything, like passtab
<div class="modal fade" id="passtab" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
Then main thing is response contain spaces. So i'd to trim response before doing the checking through jquery trim function.
if (data.status=='s')
to
if ($.trim(data) == 's' )
Why the response contain spaces. You can find the answers here
Space Before Ajax Response (jQuery, PHP)
2.strange thing, ajax response includes whitespace
Trailing spaces in Ajax response
Recently, i take some template from the internet and trying to understand the code.
But i got stuck when trying to insert data to the database and the error message wont show.
Im sorry for my bad English
This is my piece of, master_menu.php
<div class="form-group">
<label for="first_name">Nama Menu</label>
<input type="text" id="first_name" placeholder="Contoh : Ayam Goreng" class="form-control"/>
</div>
<div class="form-group">
<label for="last_name">Harga Pokok</label>
<input type="text" id="last_name" placeholder="Contoh : 15000" class="form-control"/>
</div>
<div class="form-group">
<label for="email">Harga Jual</label>
<input type="text" id="email" placeholder="Contoh : 15000" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
<button type="button" class="btn btn-primary" onclick="addRecord()">Tambahkan Menu</button>
</div>
And this is my piece of, function_script_master.js
function addRecord() {
// get values
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var email = $("#email").val();
// Add record
$.post("ajax/addRecord.php", {
first_name: first_name,
last_name: last_name,
email: email
}, function (data, status) {
// close the popup
$("#add_new_record_modal").modal("hide");
//reload
readRecords();
// clear fields from the popup
$("#first_name").val("");
$("#last_name").val("");
$("#email").val("");
});
}
// READ records
function readRecords() {
$.get("ajax/readRecords.php", {}, function (data, status) {
$(".records_content").html(data);
});
}
And this is my piece of, addRecord.php
<?php
if(isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email'])){
// include Database connection file
include("function_connection.php");
alert('clcicked');
// get values
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$query = "INSERT INTO MENUS(NAMA_MENU, HARGA_POKOK, HARGA_JUAL, STATUS) VALUES('$first_name', '$last_name', '$email', 'aktif')";
if ($conn->query($query) === TRUE) {
alert("Registrasi Sukses!");
} else {
alert("Username Yang Anda Inginkan Sudah Terpakai");
}
$conn->close();
echo "1 Record Added!";
}
?>
Try below code hope this helps, i just replaced alert with echo.
<?php
if(isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email'])){
// include Database connection file
include("function_connection.php");
// get values
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$query = "INSERT INTO MENUS(NAMA_MENU, HARGA_POKOK, HARGA_JUAL, STATUS) VALUES('$first_name', '$last_name', '$email', 'aktif')";
if ($conn->query($query) === TRUE) {
echo "Registrasi Sukses!";
} else {
echo "Username Yang Anda Inginkan Sudah Terpakai";
}
$conn->close();
echo "1 Record Added!";
}
?>
I want to save data from input fields to mysql database so first I create a modal window and input fields:
<!-- Button trigger modal -->
<button class="btn btn-success" data-toggle="modal" data-target="#myModal">
Add new</button>
<div id="output"></div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add new row</h4>
</div>
<div class="modal-body">
......
<div class="input-group">
<span class="input-group-addon">Ime</span>
<input type="text" id="Ime" class="form-control" placeholder="Upisi ime">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Pol</span>
<input type="text" id="pol" class="form-control" placeholder="Pol (male/female)">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Godine</span>
<input type="text" id="godine" class="form-control" placeholder="Godine starosti">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Broj pojedenih krofni</span>
<input type="text" id="krofne" class="form-control" placeholder="Pojedene krofne">
</div>
</br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="newData" class="btn btn-primary">Add new data</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Now I write jQuery AJAX code to add data to database:
<script>
//add data to database using jquery ajax
$("#newData").click(function() {
//in here we can do the ajax after validating the field isn't empty.
if($("#ime").val()!="") {
$.ajax({
url: "add.php",
type: "POST",
async: true,
data: { Name:$("#ime").val(), Gender:$("#pol").val(), Age:$("#godine").val(), Donuts_eaten:$("#krofne").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
} else {
//notify the user they need to enter data
}
});
</script>
and finally I create a php file (add.php)
<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');
mysql_select_db('gmaestro_agro', $con);
mysql_select_db('gmaestro_agro', $con);
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= mysql_real_escape_string($_POST['Name']) . ", ";
$query .= mysql_real_escape_string($_POST['Gender']) . ", ";
$query .= mysql_real_escape_string($_POST['Age']) . ", ";
$query .= mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= ")";
$result = mysql_query($query);
if($result != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
Now, when I try to add data I just get this error: an error occurred saving your data!.
What is the problem here exactly? I try to find the error whole day...
You are not quoting your strings:
$query .= mysql_real_escape_string($_POST['Name']) . ", ";
should be:
$query .= "'" . mysql_real_escape_string($_POST['Name']) . "', ";
(for all string values)
By the way, it would probably make your life easier if you switched to PDO or mysqli and prepared statements. Then you would not have to escape and quote your variables and the mysql_* functions are deprecated anyway.
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= "'".mysql_real_escape_string($_POST['Name']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Gender']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Age']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= "')";
Put all the values in single quotes.