I'm trying something very simple yet can't make it work and I have no idea why. I'm trying to load details on bootstrap modal windows from database so I can edit them. My button looks like
<button onclick="GetUserDetails('.$row['row_id'].')" class="btn btn-warning">Update</button>
Then this is the php part which should load the data
include("../../misc/database.inc.php");
error_reporting(E_ALL);
ini_set('display_errors', 1);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['row_id']) && isset($_POST['row_id']) != "") {
$row_id = $_POST['row_id'];
$value = $pdo->prepare('SELECT row_id, row_content, row_email FROM excel_table WHERE row_id = ?');
$value->bindParam(1, $id, PDO::PARAM_INT);
$value->execute();
$response = array();
if($value->rowCount() > 0){
while ($rs = $value->fetch(PDO::FETCH_ASSOC)) {
$response = $row;
}
}
else
{
$response['status'] = 200;
$response['message'] = "Data not found!";
}
echo json_encode($response);
//var_dump($_POST['row_id']); // return correct id
}
On the console->Network I see correct response
{"row_id":"1","row_content":"asd","row_email":"sad"}
Here is js part which should load data
function GetUserDetails(row_id) {
$("#row_id").val(row_id);
$.post("ajax/readUserDetails.php", {
row_id: row_id
},
function (data, status) {
// PARSE json data
var excel_table = JSON.parse(data);
// Assing existing values to the modal popup fields
$("#row_content").val(excel_table.row_content);
$("#row_email").val(excel_table.row_email);
}
);
// Open modal popup
$("#update_user_modal").modal("show");
}
And this is my modal
<div class="modal fade" id="update_user_modal" 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">Update</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="row_content">Desc</label>
<input type="text" id="row_content" placeholder="Описание" class="form-control"/>
</div>
<div class="form-group">
<label for="row_email">Email</label>
<input type="text" id="row_email" placeholder="Email" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="UpdateUserDetails()" >Save Changes</button>
<input type="hidden" id="row_id">
</div>
</div>
</div>
</div>
Can anyone tell me why modal isn't populated with data?
well my guess is you need to show the modal after the ajax asynchronous call end.
function GetUserDetails(row_id) {
$("#row_id").val(row_id);
$.post("ajax/readUserDetails.php", {
row_id: row_id
},
function (data, status) {
// PARSE json data
var excel_table = JSON.parse(data);
// Assing existing values to the modal popup fields
//add console.log to make sure you have some value
console.log('row_content: ' + excel_table.row_content);
$("#row_content").val(excel_table.row_content);
$("#row_email").val(excel_table.row_email);
// then add another to make sure you update it correctly.
console.log('#row_content: ' + $("#row_content").val());
// Open modal popup AFTER YOU UPDATE
$("#update_user_modal").modal("show");
}
);
}
Related
I am making a crud for my services table and I am using Angularjs and Codeigniter. But when i try to submit the data, this error happens
POST http://localhost/beauty-care-api/services/create 500 (Internal Server Error)
services.html
<!-- Service Modal -->
<div class="modal fade" id="modal-id">
<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">New Service</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="product_name">Service Name:</label>
<input type="text" id="service_name" class="form-control" ng-model="service.service_name">
</div>
<div class="form-group">
<label for="price">Price:</label>
<input type="number" id="price" class="form-control" min="0" ng-model="service.price">
</div>
<div class="form-group">
<label for="available">Available:</label>
<select id="available" class="form-control" ng-model="service.availability">
<option ng-repeat="availability in availabilities" ng-value="availability">
{{ availability }}
</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button ng-if="!edit" type="button" class="btn btn-primary" ng-click="saveService(service)">Save</button>
<button ng-if="edit" type="button" class="btn btn-primary" ng-click="updateProduct(service)">Save changes</button>
</div>
</div>
</div>
</div>
This is the code from ServiceController.js
$scope.service = {
service_name: '',
price: 0,
availability: 'active'
};
$scope.saveService = function(service){
httpService.post(`${urlService.apiURL}services/create`, angular.toJson(service))
.then((res) => {
listServices();
});
$('#modal-id').modal('toggle');
}
My httpService.js
var httpService = angular.module('httpService', [])
.service('httpService', function($http) {
this.get = function (url) {
return $http.get(url);
}
this.post = function (url, data) {
return jQuery.ajax({
type: 'POST',
url: url,
data: { data: data }
});
} });
ServiceController.php
public function create(){
$data = array(
'service_name' => $this->input->post('service_name'),
'status' => $this->input->post('available')
);
$this->db->set($data)
->insert('tbl_services');
$res['status'] = '1';
echo json_encode($res);
}
If you are using Codeigniter you must to separate the Controller functions to the Model (database) functions, so maybe it should be like this:
ServiceController.php
public function __construct() //Controller constructor
{
parent::__construct();
$this->load->helper('url');
$this->load->model('ServiceModel'); //load your model
}
public function create()
{
$data = array (
'service_name' => $this->input->post('service_name'),
'status' => $this->input->post('available')
);
$res['status'] = '0'; // default status response
$model = new ServiceModel(); //create an instance of your model
$response = $model->insertData($data); // insert the data
if($response) //if the insert was successful(true) set "status" = 1
{
$res['status'] = '1';
}
echo json_encode($res);
}
ServiceModel.php
function __construct() //Model constructor
{
parent::__construct();
$this->db = $this->load->database('default',TRUE);
}
public function insertData($mdata)
{
return $this->db->insert('tbl_services', $mdata);
}
I hope this can help you.
I have two elements of members data such as id and some other info in a modal which are hidden input elements inside my modal, I bind data from a anchor tag using javascript, example of data element in the anchor tag:
data-column="'.htmlspecialchars($column, ENT_QUOTES, 'utf-8').'"
Javascript example to bind into the modal:
$('#EnterExpiryModal').on('show.bs.modal', function (e) {
var memberID = $(e.relatedTarget).data('id');
$('#memID232').val(memberID);
var cola3 = $(e.relatedTarget).data('column');
$('#column3').val(cola3);
});
Having the relevant data for the members in question in my modal (modal code snippet below):
<div class="modal" id="EnterExpiryModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div id="ExpiryError"></div>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Please enter document expiry date</h4>
<br>
<form class="form-horizontal" method="post" id="ExpiryDateForm">
<div class="form-group">
<input id ="memID232" name="memID232" class="form-control" type="hidden">
</div>
<div class="form-group">
<input id ="column3" name="column3" class="form-control" type="hidden">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Date</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<div class="clearfix">
<div id="date" data-placement="left" data-align="top" data-autoclose="true">
<input name="date" type="text" class="form-control hasDatepicker" placeholder="Choose Date">
</div>
</div>
</div>
</div>
</div>
<div class="middleme"><p><i class="fa fa-info-circle iwarner" aria-hidden="true"></i><small> These documents can be uploaded again at any time...</small></p></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="expirySubmit" name="expirySubmit" class="btn clocumsbtn">Confirm</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
The above code produces the below modal:
As you can see user is prompted to enter a expiry date in the form field and click confirm.
However the issue I am having is when I hit submit the form does submit, my jQuery validation does all the necessary checks before submitting using ajax, but my hidden input elements don't submit with the values as they should, they appear to be empty, but the datepicker (date) field is populated - I know the values populate with the required data I need.
Here's what the modal looks like without the elements being hidden:
Here is the validation:
$("#ExpiryDateForm").validate({
rules:
{
memID232: {
required: true,
minlength: 0
},
column3: {
required: true,
minlength: 0
},
date: {
required: true,
minlength: 3
}
},
messages:
{
memID232: "There's an error",
column3: "There's an error",
date: "Please enter the expiry date",
},
submitHandler: submitExpiryDate
});
here's the submit handler:
function submitExpiryDate() {
var data = $("#ExpiryDateForm").serialize();
$.ajax({
type : 'POST',
url : 'enterdocexpiry.php',
data : data,
beforeSend: function() {
$("#expirySubmit").html('<span class="fa fa-spinner"></span> please wait...');
},
success : function(responses) {
if(responses=="1"){
$('#ExpiryError').removeClass('animated shake');
$("#ExpiryError").fadeIn(1000, function(){
$('#ExpiryError').addClass('animated shake');
$("#ExpiryError").html('<div class="alert alert-danger"> <span class="fa fa-exclamation"></span> Sorry there was an error!</div>');
});
}
else if(responses=="updated"){
$("#ExpiryError").fadeIn(2000, function(){
$("#expirySubmit").html('<span class="fa fa-spinner"></span> updating...');
$("#ExpiryError").html("<div class='alert alert-success'><span class='fa fa-check-square-o'></span> Added Expiry Date!</div>");
setTimeout(function(){
window.location.href="manage_docs.php";
},2000);
});
}
else {
$("#ExpiryError").fadeIn(1000, function(){
$("#ExpiryError").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#expirySubmit").html('<span class="glyphicon glyphicon-log-in"></span> Some other error');
});
}
}
});
return false;
}
here the php:
require "database.php";
$memberID = $_POST['memID232'];
$column = $_POST['column3'];
$date = DateTime::createFromFormat('d/m/Y',$_POST['dates']);
$expiryDate = $date->format("Y-m-d");
$docploaded = "Yes";
if (isset($_POST['expirySubmit'])) {
if ($column == "passport") {
$statement = $conn->prepare('UPDATE memberdocs SET pexpiry=:expiryDate,puploaded=:docploaded WHERE m_id=:memberID');
$statement->bindParam(':expiryDate', $expiryDate);
$statement->bindParam(':docploaded', $docploaded);
$statement->bindParam(':memberID', $memberID);
$statement->execute();
if($statement->execute() ):
echo 'updated';
else:
echo "1";
endif;
}else if ($column == "crb") {
$statement = $conn->prepare('UPDATE memberdocs SET cvexpiry=:expiryDate WHERE m_id=:memberID');
$statement->bindParam(':expiryDate', $expiryDate);
$statement->bindParam(':memberID', $memberID);
$statement->execute();
if($statement->execute() ):
echo 'updated';
else:
echo "1";
endif;
}
}
Now I have done some troubleshooting and it seems the datepicker is the issue here. If I remove the datepicker (date) form field and replace it with a standard free text input field my form submits successfully with the memID232 input field and column3 input field populated, executing my php script, I've tried to be as clear as possible I hope the screenshots and snippets help, any advice?
I have a table with multiple edit buttons. Each edit button is supposed to open up a modal and I am trying to pass the delivery_id to it, so I can then use it in MySQL query
echo "<td><button type='button' class='btn dt_buttons' data-toggle='modal' data-id='$delivery_id' data-target='#editModal'>Edit</button></td>";
What's the best way of retrieving that value in the modal and using it as a variable? I thought that just using $delivery_id would work, but of course that would be too simple!
Code inside the modal:
<div id="editModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Purchase</h4>
</div>
<div class="modal-body">
<?
$query = "SELECT id, supplier_id, date as del_date, delivery_number, po_number, cost_value FROM store_purchases WHERE id = $delivery_id";
echo $query;
$retval = f_select_query($query, $datarows);
$lint_product_id = f_htmlspecialchars_decode($datarows[0]->id , ENT_QUOTES);
$supplier_id = intval($datarows[0]->supplier_id);
$delivery_date = $datarows[0]->del_date;
$delivery_number = intval($datarows[0]->delivery_number);
$lint_unit_cost = f_htmlspecialchars_decode($datarows[0]->cost_value , ENT_QUOTES);
$lint_unit_cost = floatval($lint_unit_cost);
$lint_unit_cost = number_format($lint_unit_cost, 2);
$department_id_dropdown = f_get_dropdown("supplier_name", "supplier_name", "supplier_master", $supplier_id, "id", " store_id = $store_id", '', '', '', false, false, true);
?>
<div class="container-fluid" id="div_user_master" class="ae_form" >
<form id="myForm" action="/platformDev/create_subscription.php" method="POST">
<?
echo "Supplier Name: <td class='text-right' id='department_id' style='width:20%;'> $department_id_dropdown </td> <input id='purch_id' name='purch_id' class='form-control purch_id' value='$product_id' type='hidden'/>";
echo "Delivery Date: <span class='required_field'><i class='fa fa-star fa-sm'></i> </span> <input class='form-control' tabindex='3' id='date' name='date' value= '$delivery_date' type='text'/> <br/>";
echo "Delivery Number: <input type='text' id='unit_cost' name='unit_cost' class='form-control unit_cost' style='width:80%;' value='$delivery_number' />";
echo "Invoice Cost: <input type='text' id='unit_cost' name='unit_cost' class='form-control unit_cost' style='width:80%;' value='$lint_unit_cost' /></div>";
?>
</form>
</div>
</div>
<div class="modal-footer">
<button class="btn form-btns btn-primary" style="float: left;" data-dismiss="modal" id="customButton">Add Purchase</button>
<button type="button" class="btn dt_buttons close_this ajax_forms" data-dismiss="modal">Close</button>
</div>
</div>
</div>
The code below will get the data-id value from the button that was clicked.
You can use this template:
$('#editModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var delivery_id = button.data('id'); // delivery id here
var modal = $(this)
modal.find('.modal-title').text('Delivery #' + delivery_id);
modal.find('.modal-body').html('content here');
});
https://getbootstrap.com/docs/4.0/components/modal/
https://getbootstrap.com/docs/3.3/javascript/#modals
I guess that you are trying to use that id to fetch records and populate the modal with that data.
If that's the case :
You can retrieve the data-id attribute value with Javascript and send Ajax request to your php script and query your database.
$('.dt_buttons').on('click', function()
{
var id = $(this).attr('data-id');
$.ajax
({
url: "your/url",
data:
{
id : id
},
method: 'POST'
}).success(function(response)
{
var json = response,
obj = JSON && JSON.parse(json) || $.parseJSON(json);
// say you have following fields.
var fid = obj[0].id;
var title = obj[0].title;
//retrieve record fields here.
// or just pass the `id` skipping the Ajax stuff above.
$('#editModal')
.find('span.doc-title').text(title).end()
.find('[name="id"]').val(id).end();
/* show modal.. */
$('#editModal').modal('show');
});
});
I don't know what happens there. [
Here you see the Edit buttonedit(pencil) in actions when i uopdate the record modal will open.
When you click on edit(pencil) button modal will be open.
When i update the record first time its working fine and ajax runs one time. when i again update the record ajax runs twice and again update the record ajax run thrice. every time when i update the record the ajax run incremented
Here is my code:-
Html code of Button
enter code here
<button type="button" class="btn btn-info btn-edit editService"><i class="fa fa-pencil" aria-hidden="true"></i></button>// this button in foreach loop
My Modal:-
enter code here
<div class="modal fade" id="myModal-edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form id="subservicedata" role="form" method="POST" action="Javascript:;">
{{ csrf_field() }}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="add-cat">Edit Service</h4>
</div>
<div class="modal-body">
<div class="form-group row">
<span class="col-xs-3 add-cate-model">Service</span>
<div class="col-xs-8">
<input name="name" id="sname" class="form-control txtfield m-tb-10" type="text" placeholder="Service" value="">
<input type="hidden" name="id" id="id" value="">
<input type="hidden" name="serviceid" id="service_id" value="">
<input type="hidden" name="listid" id="list_id" value="">
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary editSubService">Submit</button>
</div>
</form>
</div>
</div>
My Jquery Code:-
enter code here
$(document).on ('click','.editService',function(){
var tdid = $(this).parents().parents().attr('id');
var service = tdid.split('-');
var subserviceid = service[1];
alert(subserviceid);
$.ajax({
type : "POST",
url : "get-service",
data : { id: subserviceid },
dataType: 'json',
success:function(resp){
if($.trim(resp)){
$('#myModal-edit').modal('show');
$('#sname').val(resp.name);
$('#id').val(resp.id);
$('#service_id').val(resp.service_id);
$('#list_id').val(resp.list_id);
$(document).on('click','.editSubService',function(){
$.ajax({
type : "post",
url : "edit-sub-service",
data : $("#subservicedata").serialize(),
success:function(resp){
if($.trim(resp)){
alert(resp);
alert(subserviceid);
$('#tr-'+subserviceid+' #tdid-'+subserviceid).html(resp);
$('#myModal-edit').modal('hide');
}else{
alert("Error"); return false;
}
},
error:function(){
alert("Something Went Wrong!");
}
});
});
} else{
alert("Failed"); return false;
}
}
});
});
And My laravel 5.2 function
enter code here
public function getCategoryService(Request $request){
if($request->ajax()){
$data = $request->all();
$servicedata= DB::table("session_subservices")->where('id',$data['id'])->first();
echo json_encode($servicedata);die;
}
}
public function editCategoryService(Request $request){
if($request->ajax()){
$data = $request->all();
//echo "<pre>"; print_r($data); die;
SessionSubservice::where('id', $data['id'])->update(array('name' =>$data['name']));
echo $data['name']; die;
}
}
The problem is that you append a new event every time the button is clicked.
You need to remove the first event if you want to retain your approach.
Change this $(document).on ('click','.editSubService',function(){
to this:
$(document).off('click').on('click','.editSubService',function(){
Other aproach is to create a function in your js and set it to be called in the html.
The problem is the .editSubSerice click handler:
$(document).on('click','.editSubService',function(){
...
}
You are adding this click handler in the success function of your ajax call which is part of another click handler, so every time that ajax call / click handler executes, you add an additional click handler and that causes the code to execute multiple times.
You should move that click handler to after (or before...) your other click handler so that it only gets called / binds once.
I am trying to POST data from a form using jQuery & Ajax. However, when I check on my PHP to see if the form has been "submitted", it shows it has not because the MySQL code does not run. I am guessing my HTML is not setup correctly and therefore the Ajax request is not sending the data to my post-update.php script. Here is my code:
<script type="text/javascript">
$(document).ready(function() {
$('#ajax-remove-completion-date').click(function() {
$.ajax({
type:'POST',
url:'post-update.php',
data: dataString,
success: function(response) {
$('#success-remove-completion-date').removeClass('hidden');
}
});
});
});
HTML:
<form action="">
<div id="myModal1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel3">Remove Completion Date</h3>
</div>
<div class="modal-body">
<p>Are you sure you want to remove the students Completion Date?</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn blue" data-dismiss="modal" id="ajax-remove-completion-date">Yes</button>
<input type="hidden" name="submitted" value="remove-completion-date" />
</div>
</div>
</form>
PHP:
<?
session_id();
session_start();
require_once('assets/includes/mysql-connect.php');
/*Check to see if the completion date is being removed*/
if ($_POST['submitted'] == 'remove-completion-date') {
$query = "UPDATE students SET completion_date = NULL, completed = NULL WHERE student_id = {$_SESSION['student_id']} LIMIT 1";
$result = mysqli_query($dbc, $query);
}
?>
Where does dataString come from?
It's better if you define the data you want to send as an object. It's more readable and it's automatically converted to a query String.
$(document).ready(function() {
$('#ajax-remove-completion-date').click(function() {
$.ajax({
type:'POST',
url:'post-update.php',
data: {
submitted: 'remove-completion-date'
},
success: function(response) {
$('#success-remove-completion-date').removeClass('hidden');
}
});
});
});
If you want to take the value from the field, set submitted as:
$('input[name="submitted"]').val()