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
Related
So basically to give a brief before exploring in to the code I give below.
Basically what I'm trying to do is, I have a modal in one of my php page as below. I'm trying to show the model from a php function "fetch_assignment_history" given below. There is a button in which we can add users to the assignment, and the button onclick event(onClick="assign(this.dataset.id)") call function passing the id from the php function to JS function.
So when the user click the button the JS function shows the modal as well as get the assignment id in the function. This assignment id is set (through JS) to data attribute of multiple select dropdown in the modal.
Now the point where I'm stuck is, a setinterval constantly fetch the assigned users. This basically collect from mysql database of users who were added to the assignment (comma delimitted id's).
When the modal is opened I want the previously assigned users to be selected in the multiple select (as per data in mysql) as default. For this I want to get the id passed from the onclick event
My HTML part (modal)
<div id="assignee" class="modal custom-modal fade" role="dialog">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title text-center">Assignment</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="col-md-12 col-sm-12 col-xs-12 form-group has-feedback">
<label style="color:#333D79FF; font-size:15px;">Add Users <span class="text-danger">*</span></label>
<div>
<select class="select2_multiple form-control" multiple="multiple" id="userslist" name="userslist[]" style="width: 100%;left: 10px;">
<option id="none" value="">Select Users</option>
<?php
My PHP CODE TO PULL OUT DATA FROM MYSQL DB
?>
<option value="<?php echo $id; ?>" data-useravatar="<?php echo $avatar; ?>" data-usertitle="<?php echo $firstname;echo " ";echo $lastname; ?>" data-role="<?php echo $role; ?>" data-assignment=""><?php echo $firstname;echo " ";echo $lastname; ?></option>
<?php } ?>
</select>
</div>
<div id="usersfetch"></div>
</div>
</div>
</div>
</div>
</div>
My PHP
1. function to fetch assignment history.
Below button onclick goes to JS and shows modal. and also pass id
function fetch_assignment_history($connect)
{
$query = "
SELECT * FROM assignment
WHERE id = '".$_SESSION['id']."'
ORDER BY id ASC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '<ul class="list-unstyled">';
foreach($result as $row)
{
$user_name = '';
$dynamic_background = '';
$message = '';
$assignmentname = $row["assignmentname"];
$name = $row["name"];
$id = $row['id'];
$output .= '
<div class="x_panel" style=" font-size:14px;">
<span class="controlbuttons">
<button class="btn btn-round" data-id="'.$id.'" onClick="assign(this.dataset.id)"><i class="material-icons" title="Assign">person_add</i></button>
</span>
</div>
';
}
$output .= '</ul>';
return $output;
}
function to assigned user history
function fetch_assigned_user_history($connect)
{
some php queries
}
My JS
I want the assignid from function assign(assignid) to be called from function fetch_assigned_user_history(). How do I accomplish this??????
setInterval(function(){
fetch_assigned_user_history();
}, 1000);
function assign(assignid)
{
var assignid = assignid;
$("#assignee").modal("show");
$('#userslist').data("assignment",assignid);
}
function fetch_assigned_user_history()
{
var action = "fetch_assigned_user_data";
var getid = ;// I need to get the ID from the previous function from onclick event function assign(assignid)
$.ajax({
url:"assignment.php",
method:"POST",
data:{action:action, assignmentid:getid},
success:function(data)
{
$('#usersfetch').html(data);
}
})
}
Hope I'm clear with my question. Appreciate for an advise to fix.
To summarise, the basic question is how to call variable of one JS function in to another (in this example id's) so that i can get the list of users in that assignment? Also how to get it selected by default the Multiple select with database values.
You already stored 'assignid' in data-* attribute, you can just retrieve it when you need it
function assign(assignid) {
var assignid = assignid;
$("#assignee").modal("show");
// You already store your assignid at here
$('#userslist').data("assignment",assignid);
}
function fetch_assigned_user_history()
{
var action = "fetch_assigned_user_data";
// Now you just need to retrieve it
var getid = $('#userslist').data("assignment");
$.ajax({
url:"assignment.php",
method:"POST",
data:{action:action, assignmentid:getid},
success:function(data)
{
$('#usersfetch').html(data);
}
})
}
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');
I have a dynamic form for Product Orders. I am setting the price based on company(select2) and product using onchange from the product dropDownList. Company is on the base form outside the dynamicform (easy to reference) but product is a list item within the dynamicform. My code is working for the first item but I cannot set the subsequent because I cannot figure out how to address the item # of the added dynamic form items.
dynamic form loop:
<?php foreach ($modelsOrderItem as $o => $modelOrderItem): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="clearfix"></div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelOrderItem->isNewRecord) {
echo Html::activeHiddenInput($modelOrderItem, "[{$o}]id");
}
?>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="col-md-5">
<?= $form->field($modelOrderItem, "[{$o}]idProduct")->
dropDownList
(
ArrayHelper::map(Product::find()->all(), 'id','ProductCodeWithName'),
['prompt' => 'Select a Product','style'=>'width:400px' ,
'onchange' => '$.post( "index.php?r=pricelist/pricelist&idProduct='.'"+$(this).val()+"'.'&idCompany='.'"+$("#order-idcompany").val(),
function(data)
{
$( "#orderitem-0-itemprice" ).val(data);
});']
)->label(false);
?>
</div>
<div class="col-md-3" >
<?= $form->field($modelOrderItem, "[{$o}]itemQuantity")->textInput(['style'=>'width:150px'])->label(false) ?>
</div>
<div class="col-md-2">
<?= $form->field($modelOrderItem, "[{$o}]itemPrice")->textInput(['style'=>'width:200px'])->label(false) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
I have now removed the onchange function and added Javascript that allows me to control which form element to change but, I cannot figure out how to do this with dynamically added elements. I have included script looking for a change in the added price element but the script does not get activated. So it works for the zero(0) element but will not respond with orderitem1, etc. Here is my updated code and the Javascript.
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsOrderItem as $o => $modelOrderItem):?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="clearfix"></div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelOrderItem->isNewRecord)
{
echo Html::activeHiddenInput($modelOrderItem, "[{$o}]id");
}
?>
<div class="form-group kv-fieldset-inline">
<div class="col-sm-4">
<?= $form->field($modelOrderItem, "[{$o}]idProduct")->dropDownList
(
ArrayHelper::map(Product::find()->orderBy('productCode')->all(), 'id','ProductCodeWithName'),
['prompt' => 'Select a Product','style'=>'width:360px' ,]
)->label(false);
?>
</div>
<div class="col-sm-2" >
<?= $form->field($modelOrderItem, "[{$o}]itemQuantity")->textInput(['style'=>'width:100px','padding'=>'100px'])->label(false) ?>
</div>
<div class="col-sm-2" >
<?= $form->field($modelOrderItem, "[{$o}]quantityType")->DropdownList(['Cartons'=>'Cartons','Bags'=>'Bags','Kilograms'=>'Kilograms',
'Tubs'=>'Tubs', 'Pieces' => 'Pieces'],['style'=>'width:150px'])->label(false) ?>
</div>
<div class="col-sm-2">
<?= $form->field($modelOrderItem, "[{$o}]itemPrice")->textInput(['style'=>'width:200px'])->label(false) ?>
</div>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
Javascript:
<?php
$script = "$('#orderitem-0-idproduct').change(function()
{
var idProduct = $(this).val();
$.get( 'index.php?r=pricelist/getpricelist&idProduct',{ idProduct:idProduct, idCompany:$model->idCompany },
function(data)
{
$('#orderitem-0-itemprice').val(data);
});
});
$('#orderitem-1-idproduct').change(function()
{
var idProduct1 = $(this).val(data);
alert();
$.get( 'index.php?r=pricelist/getpricelist&idProduct',{ idProduct:idProduct1, idCompany:$model->idCompany },
function(data)
{
$('#orderitem-1-itemprice').val(data);
});
});";
$this->registerJs($script);
?>
I was able to use Javascript to find out which element was being clicked. This avoided the problem of being able to run code on dynamic elements that had not been initiated.
<?php $js = <<<JS
$('body').change(function(e)
{
var element = '#'+$(e.target).attr('id');
var field = element.substring(element.length - number_of_chars_in_your_fieldname, element.length); //stripping the string to identify the field you are looking
if(field === "field_you_are_looking_for") //element usually looks like #formID-row-field
{
var dropdownID = $(element).val();
if (element.length === 22) //single digit row numbers
{
var row = element.substring(11,12); //extract the current row number
} else //row numbers higher than 9
{
var row = element.substring(11,13);
}
//Do whatever you need to do
$('#formID-'+row+'-field_you_want_to_change').val(data); //set the field to change on current row
}
});
JS;
$this->registerJs($js);
?>
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.
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.