Update mysql table with php using ajax - javascript

Here I create a table http://jsbin.com/OJAnaji/13/edit and DEMO: http://jsbin.com/OJAnaji/13
So when users click on some row on table automaticly populate input fields with values from table into modal window. Modal window user open when click on button "Edit row". Now I need to know how I can update mysql table with columns: Name,Gender,Age,Donuts eaten.
I create js ajax:
$("#edit").click(function() {
//in here we can do the ajax after validating the field isn't empty.
if($("#name").val()!="") {
$.ajax({
url: "update.php",
type: "POST",
async: true,
data: { Name:$("#name").val(), Gender:$("#gender").val(), Age:$("#age").val(), Donuts_eaten:$("#donuts_eaten").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
}
});
HTML - modal window and button:
<!-- Button trigger modal -->
<button id="edit" class="btn btn-success disabled" type="button" data-toggle="modal" data-target="#myModal">
Edit selected row</button>
<!-- 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">Name</span>
<input type="text" value="" id="name" class="form-control" placeholder="Type name">
</div></br>
<div class="input-group">
<span class="input-group-addon">Gender</span>
<input type="text" id="gender" class="form-control" placeholder="Gender?">
</div></br>
<div class="input-group">
<span class="input-group-addon">Age</span>
<input type="text" id="age" class="form-control" placeholder="Number of age">
</div></br>
<div class="input-group">
<span class="input-group-addon">Donuts eaten</span>
<input type="text" id="donuts_eaten" class="form-control" placeholder="Number of donuts eaten">
</div></br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
So how I can now update MySql database with php:
so file update.php how must looks like:
<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');
mysql_select_db('gmaestro_agro', $con);
//HOW I CAN UPDATE MYSQL DATABASE, WHAT I NEED TO ADD HERE?
?>

You should have a column in the table which is an auto-increment column, such as "id" or like the example below uses "index_id". This should be used when creating your form, and sent along with the $_POST array to reference the row you are updating. This is a simple example, which you can use to get you started.
$_POST = stripslashes_deep($_POST); # you will want to better filtering for security.
if(isset($_POST['Name']) && $_POST('Name') !=''){
$query = "UPDATE stat
SET Name ='". $_POST['Name'] . "',
Gender ='". $_POST['Gender'] . "',
Age ='". $_POST['Age'] . "',
Donuts_eaten ='" .$_POST['Donuts_eaten'] . "'
WHERE
index_id = '". $_POST['index_id'] . "'";
$result = mysql_query($query) or die(mysql_error());
exit(json_encode($_POST));
}
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
For your MYSQL table you can run this in your MYSQL PhpMyAdmin:
ALTER TABLE `stats` ADD `index_id` INT( 3 ) NOT NULL AUTO_INCREMENT FIRST ,
ADD PRIMARY KEY ( `index_id` )

In your update.php, do like this,
$name = $_POST['Name'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$donuts = $_POST['Donuts_eaten'];
$query = "UPDATE `your_table_name` SET name ='".$name."', gender ='".$gender."',
age='".$age."', donuts_eaten ='".$donuts."' ";
mysql_query($query, $con);
Just a basic to basic structure on what you need to do in update.php its up to you to kick it a notch and you've used POST in your ajax that why its $_POST.
note: Dont use reserved word as your field name in the database.

Related

Pass Javascript variable in PHP query

I've created a table with data and auto-generated buttons. When i click in 1 button .add_task, a modal opens, which display another table according to retrieved key: user_id of button.
The functionallity of button is shown below:
$(document).on('click', '.add_task', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"actions/fetch_jobs.php",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
$('#jobModal').modal('show');
$('.modal-title').text("Jobs");
`$('#vis_id')`.val(user_id);
$('#show_inseredjobs').html(data);
}
})
});
The problem is that i want to take value $('#vis_id') or user_id and put it in a php query of opened modal.
<div id="jobModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="job_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Jobs</h4>
</div>
<div class="modal-body">
<div id="show_inseredjobs"></div>
<br/>
<select name="job_desc" class="form-control action" id="job_desc" data-live-search="true" title="Select Job"></select>
</div>
<div class="modal-footer">
<input type="hidden" name="vis_id" id="vis_id" />
<?php
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
if($result->num_rows == 1) {
// row not found, do stuff...
?>
<span class="glyphicon glyphicon-print"></span>print button
<?php
}
?>
<input type="submit" name="action" id="action" form="job_form" class="btn btn-success" value="Προσθήκη" />
<button type="button" class="btn btn-default" data-dismiss="modal">Άκυρο</button>
</div>
</div>
</form>
</div>
</div>
More specifically, i want to do that: $result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
How can i pass that js variable in php?
I tried different combinations of expressing variable, but the code crashes. If i try to give manually numbers, the code works. To conclude, how can i pass value $('#vis_id') or user_id in $result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
Your modal is static and you can't run PHP code in the modal.
I think you must do this.
First change:
<?php
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = $('#vis_id') AND job_desc='Fumes'");
if($result->num_rows == 1) {
// row not found, do stuff...
?>
<span class="glyphicon glyphicon-print"></span>print button
<?php
}
?>
To:
<div id="job_desc"></div>
And then, in the actions/fetch_jobs.php file when you return data:
require 'conn.php';
$result = $conn->query("SELECT job_desc FROM jobspervisit WHERE jvid = '".$_POST["user_id"]."' AND job_desc='Fumes'");
if ($result->num_rows == 1) {
$response = "";
foreach ($result as $row) {
$response .= '<span class="glyphicon glyphicon-print"></span>print button';
}
}
return json_encode([YOUREPREVIOUSRETRUN,$response]);
And then in ajax part you must parse json data first variable [YOUREPREVIOUSRETRUN] your previous data and second data you must put it on $("#job_desc").html(second data).
Or, you can use an iframe for this part but I don't suggest that.
From what I can tell by looking at the structure of your modal, you seem to be using Bootstrap, though I am unclear on the version. If it's Bootstrap 5, read on. If not, please add that information to your question, and let me know.
Here's how you can do it all in one call.
First, change the page from which you are opening the modal, so that the modal isn't a part of it. You need to make a separate file to hold the modal contents. Let's call that file remote-file.php. This would be inside that file.
<?php
// your PHP logic goes here - parse the received $_POST parameters, prepare your query - if needed, query your database
// retrieve the data, and place it in variables for later display
require 'conn.php';
$jvid = isset($_POST['jvid'] ? (int)$_POST['jvid'] : 0;
$result = $conn->prepare("SELECT job_desc FROM jobspervisit WHERE jvid = ? AND job_desc='Fumes'");
$result->bind_param("i",$jvid);
$result->execute();
if($result && $result->num_rows == 1) {
// row found, do stuff
$output = '<span class="glyphicon glyphicon-print"></span>print button';
} else {
$output = "Nothing found";
}
?>
<div class="modal-dialog">
<form method="post" id="job_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Jobs</h4>
</div>
<div class="modal-body">
<div id="show_inseredjobs"></div>
<br/>
<select name="job_desc" class="form-control action" id="job_desc" data-live-search="true" title="Select Job"></select>
</div>
<div class="modal-footer">
<input type="hidden" name="vis_id" id="vis_id" value="<?=$jvid?>">
<?php
echo $output;
?>
<input type="submit" name="action" id="action" form="job_form" class="btn btn-success" value="Προσθήκη" />
<button type="button" class="btn btn-default" data-dismiss="modal">Άκυρο</button>
</div>
</div>
</form>
</div>
Some notes about previous code:
it is assumed that jvid in your database is an INT type colum. Because of that, we could do (int)$_POST['jvid']
if jvid is not an INT but another type of column, we wouldn't do the (int)$_POST['jvid'] bit, and our binding would be slightly different
// prepare the query
$jvid = $_POST["jvid"];
$results = $conn->prepare("SELECT job_desc FROM jobspervisit WHERE jvid = ? AND job_desc='Fumes'");
$results = $conn->bind_param("s",$jvid);
$result->execute();
Next, in the original page, where your buttons are (and where your modal's HTML was), you would need this line of code for the modal.
<div class="modal fade" id="jobModal"></div>
This is going to be a wrapper for your modal content. All the rest will be going inside the remote-file.php. Also, your button element, the one that's opening the modal on click? That button doesn't need to have a data-bs-target attribute, because the following code will work (since you're using jQuery and all).
<button class="btn btn-lg btn-success add-task" id="btn" data-id="1234">Open modal</button>
<div class="modal fade" id="jobModal"></div>
<script>
$(document).ready(function() {
$(document).on('click', '.add_task', function(){
var user_id = $(this).attr("id");
$('#jobModal').load('remote-file.php',{'jvid':user_id },function(){
var jobModal = new bootstrap.Modal($('#jobModal')[0], {
backdrop:"static",
show:true
});
jobModal.show();
});
});
});
</script>
Final notes:
jQuery version: 3.6.3
Bootstrap version: 5.3.0

Modal box does not close on successfull ajax return

I have a modal window that pops up whenever a screen is ideal for 3 minutes. It asks for a PIN to be entered and there is a Continue button on that to be clicked after the PIN is entered in it. On using this Continue button, an insert is made in a database table. Now my problem here is on entering the PIN and clicking on Continue button, the modal does not hides or closes itself. Although the database insertion is done but the modal does not hides. What can be possibly going wrong in this. Any suggestion will be highly helpful. My code,
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation <b>PIN</b><font color="red">*</font><br>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
<p style="font-size:11px"><b><font color="red">*</font><font color="grey"><b>PIN</b><i> is mentioned in your welcome email.</font></i></b></p><br>
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Continue</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(result){
if(result['status'] == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And processActivation.php,
<?php
$uid = $_SESSION['session_user_id'];
$dobCheck = $db->idToField("tbl_user", "dob", $uid);
$dob = explode("-", $dobCheck);
$pin = $_REQUEST['pin'];
$moduleId = $_REQUEST['module_id'];
$chapterId = $_REQUEST['chapter_id'];
$time_taken = $_REQUEST['seconds'];
$created = date("Y-m-d h:i:s");
if($pin != $dob[0])
{
echo "Please enter valid PIN."; die;
}
else
{
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
}
?>
I want to know if
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
is the right way?? Because all of the above operations are being performed correctly and upon that console.log(result) does not shows up anything. Something wrong with the above couple of lines. Very helpful if somebody points out the error in this.
Use the hide function from jQuery.
jQuery('#myModal').hide();
As I know modal('hide') is used for bootstrap modals.
A quick fix maybe, instead of doing
echo json_encode(array('status' => 'active')); and if(result['status'] == 'active')
do
echo "active"; and if(result == 'active')
Use
jQuery('#myModal').toggle().click();
instead of
jQuery('#myModal').modal('hide');

jquery+AJAX - Update MySQL record via Modal

I am loading record details into a modal allowing the user to edit. What I am trying to achieve is to have the user update the record in the modal and then submit to the MySQL table via AJAX / jQuery, however, afte pressing the "Save Changes" button nothing happens. I checked the JS Query and can confirm that the button is linked correctly and also managed to update the database when directly addressing the PHP update script. Not sure why the script refuses to start
Modal:
<div id="output"></div>
<!-- Modal MYMODAL -->
<div class="modal fade" id="myModal" 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">Edit Record</h4>
</div>
<div class="modal-body">
<!-- ID No. -->
<div class="form-group">
<label>ID No.:</label>
<input type="number" class="form-control" id="dataPID" name="dataPID" size="5" disabled />
</div>
<!-- /.id number -->
<!-- Category -->
<div class="form-group">
<label>Category:</label>
<input type="text" class="form-control" id="dataCat" name="dataCat" />
</div>
<!-- /.category -->
<!-- Issue -->
<div class="form-group">
<label>Issue:</label>
<input type="text" class="form-control" id="dataIssue" name="dataIssue" />
</div>
<!-- /.issue -->
<!-- Department Responsible -->
<div class="form-group">
<label>Department Responsible:</label>
<input type="text" class="form-control" id="dataDeptResp" name="dataDeptResp" />
</div>
<!-- /.department responsible -->
<!-- Experience -->
<div class="form-group">
<label>Experience:</label>
<input type="text" class="form-control" id="dataExp" name="dataExp" />
</div>
<!-- /.experience -->
<!-- textarea -->
<div class="form-group">
<label>Description:</label>
<textarea class="form-control" id="dataDesc" name="dataDesc" rows="3" ></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" id="SaveChanges" name="SaveChanges" class="btn btn-primary">Save Changes</button>
<button type="button" id="DeleteRecord" name="DeleteRecord" class="btn btn-danger">Delete Record</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.Modal MYMODAL -->
Javascript:
$("#SaveChanges").click(function() {
$.ajax({
type: "POST",
url: "plugins/MySQL/ajax_action.php",
data: { action:"update_mysqli",PID:$("#dataPID").val(), Category:$("#dataCat").val(), Issue:$("#dataIssue").val(), Department_Responsible:$("#dataDeptResp").val(), Experience:$("#dataExp").val(), Description:$("#dataDesc").val()}, //your form data to post goes here as a json object
dataType: "json",
contentType:"text",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
});
ajax_action.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['action']) && ($_POST['action']=='update_mysqli')) {
// include connection details
include 'connect_db.php';
//Open a new connection to the MySQL server
$db = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
//Output any connection error
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
// get variables and sanitize
$pid = mysqli_real_escape_string($db,$_POST['PID']);
$cat = mysqli_real_escape_string($db,$_POST['Category']);
$issue = mysqli_real_escape_string($db,$_POST['Issue']);
$dept_resp = mysqli_real_escape_string($db,$_POST['Department_Responsible']);
$exp = mysqli_real_escape_string($db,$_POST['Experience']);
$desc = mysqli_real_escape_string($db,$_POST['Description']);
// check if record exists based on ID number
$result = $db->query("SELECT * FROM qci_problems_index_new WHERE PID='".$pid."'");
// if record is found, update accordingly
if ($result->num_rows > 0){
$sql = "UPDATE qci_problems_index_new SET Category = '$cat', Issue = '$issue', Department_Responsible = '$dept_resp', Experience = '$exp', Description = '$desc' WHERE PID = '$pid'";
if (!$db->query($sql)) {
echo "Error - Update of record PID " . $pid . " failed: (" . $db->errno . ") " . $db->error;
}
} else {
// if no record with relevant PID is found, create new record
$sql = "INSERT INTO `qci_problems_index_new`(`PID`, `Category`, `Issue`, `Department_Responsible`, `Experience`, `Description`) VALUES ('".$pid."', '".$cat."', '".$issue."', '".$dept_resp."', '".$exp."', '".$desc."')";
if (!$db->query($sql)) {
echo "Error - could not insert new record: (" . $db->errno . ") " . $db->error;
}
}
echo "Success, record updated successfully";
//close connection
$db->close();
}
EDIT 1:
Chrome Console says the following:
EDIT 2:
updated code
Change you data type to json and content type to text,add your get variable to the post request
$("#SaveChanges").click(function() {
$.ajax({
type: "POST",
url: "plugins/MySQL/ajax_action.php",
data: { action:"update_mysqli",PID:$("#dataPID").val(), Category:$("#dataCat").val(), Issue:$("#dataIssue").val(), Department_Responsible:$("#dataDeptResp").val(), Experience:$("#dataExp").val(), Description:$("#dataDesc").val()}, //your form data to post goes here as a json object
dataType: "json",
contentType:"text",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
});
php
if(isset($_POST['action']) && ($_POST['action']=='update_mysqli')) {
You are passing the value "update_mysql" in "action" parameter in the ajax URL(plugins/MySQL/ajax_action.php?action=update_mysql). On the other hand your condition in ajax_action.php will only be executed the code if the value of "action" parameter is "update_mysqli"
Change the following line
if(isset($_GET['action']) && ($_GET['action']=='update_mysqli'))
to
if(isset($_GET['action']) && ($_GET['action']=='update_mysql'))
in your ajax_action.php file.
OR
Alternatively, you can pass value update_mysqli instead of update_mysql for your action parameter in ajax call.
Since you are using mysqli, you will prefer this for the sake of best practice as you are using mysqli functions inside code.

update database table return to true but did not change the value of the table

My code in view script
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('admin_technical/fileUploadblockquotes')?>";
} else {
url = "<?php echo site_url('admin_technical/ajax_updateblockquotes')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{reload_table();
alert(data.status);
$('#modal_formbq').modal('hide');
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data'+errorThrown);
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
view html modal
<div class="modal fade" id="modal_formbq" role="dialog">
<div class="modal-dialog">
<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>
<h3 class="modal-title">Objectives</h3>
</div>
<div class="modal-body form">
<form id="form" class="form-horizontal" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title</label>
<div class="col-md-9">
<input name="title" placeholder="Caption" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
controller
public function ajax_updateblockquotes()
{
$data = array(
'text' => $this->input->post('title'),
'id' => $this->input->post('id'),
);
$this->person->updateblockquotes($data);
echo json_encode(array("status" => TRUE));
}
im my model
public function updateblockquotes($data)
{
extract($data);
$this->db->where('id', $id);
return $this->db->update('technical_slide_blockquotes', array('text' => $text));
}
The problem is when I do a debugging using the developer tool from google chrome the result is true, no errors found but when I look the database nothing change on it.

Jquery ajax add to mysql database

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.

Categories