I'm working with DataTables and CodeIgniter, and Right now I want to be able to edit any row in my table, and I'm already doing it! But I'm only updating the row that has the ID = 1, that's because in my controller I defined this :
$this->db->set('NameContact', $_POST['Name']);
$this->db->set('NumberContact', $_POST['Number']);
$this->db->where('IdContact', 1);
$this->db->update('contacts');
As you can see I need to get the id of the selected row in the table to pass it with the $_POST method. But I can't seem to find a right way to do it via JS. Any help pls?
My HTML:
{Contacts}
<tr>
<td id="{IdContact}">{IdContact}</td>
<td>{NameContact}</td>
<td>{NumberContact}</td>
<td><a data-toggle="modal" data-target="#EditNumber"> <i class="fa fa-edit"></i></a></td>
</tr>
{/Contacts}
My JS:
function EditPhoneNumber(){
var Name = document.getElementById("EditName").value;
var Number = document.getElementById("EditNumber").value;
console.log(Name);
console.log(Number);
jQuery.ajax({
type: "POST",
url: 'http://localhost/projeto/index.php/Backoffice_Controller/EditContacts',
data: {Name: Name, Number: Number},
success: function (response) {
console.log("success");
console.log(response);
},
error: function(response){
console.log("error");
console.log(response);
}
});
}
Here is my Modal:
<div id="EditNumber" class="modal fade" role="dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Editar Contacto</h4>
</div>
<div class="modal-body">
<input type="text" name="NameContact" placeholder="Name" id="EditName"><br>
<input type="text" name="NumberContact" placeholder="Number" id="EditNumber">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-default" onclick="EditPhoneNumber()">Editar</button>
</div>
</div>
Pass data-id into your html tag like below and on tag click you need to manage function instead of opening modal directly.Look at the below code.
HTML
{Contacts}
<tr>
<td id="{IdContact}">{IdContact}</td>
<td>{NameContact}</td>
<td>{NumberContact}</td>
<td> <i class="fa fa-edit"></i></td>
</tr>
{/Contacts}
In your Modal
<div id="EditNumber" class="modal fade" role="dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Editar Contacto</h4>
</div>
<div class="modal-body">
<input type="text" name="NameContact" placeholder="Name" id="EditName"><br>
<input type="text" name="NumberContact" placeholder="Number" id="EditNumber">
<input type="hidden" name="NumberContactId" id="EditId">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-default" onclick="EditPhoneNumber()">Editar</button>
</div>
</div>
</div>
JS
function editNumberModal(obj){
vat id = jQuery(obj).attr('data-id');
jQuery('#EditNumber').modal();
}
function EditPhoneNumber(){
var Name = document.getElementById("EditName").value;
var Number = document.getElementById("EditNumber").value;
var Id = document.getElementById("EditId").value;
console.log(Name);
console.log(Number);
jQuery.ajax({
type: "POST",
url: 'http://localhost/projeto/index.php/Backoffice_Controller/EditContacts',
data: {Name: Name, Number: Number, Id:Id},
success: function (response) {
console.log("success");
console.log(response);
},
error: function(response){
console.log("error");
console.log(response);
}
});
}
Related
HTML required attribute not working with AJAX submission
I have created a model Form and set its input field to require attribute but its not working with ajax
<div class="modal fade hide" id="ajax-book-model" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="ajaxBookModel">Add New Machine</h5>
<!-- <button type="reset" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> -->
<button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" onClick="window.location.reload();">
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST">
<input type="hidden" name="id" id="id">
<input type="hidden" name="user_id" id="user_id" value="{{ Auth::user()->id }}">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Name</label>
<input type="text" id="machine_name" name="machine_name" class="form-control form-control-sm" placeholder="Enter Machine Name" required>
<span class="text-danger">{{ $errors->first('machine_name') }}</span>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>IOT Device ID</label>
<input type="text" id="iot_device_id" name="iot_device_id" class="form-control form-control-sm" placeholder="Enter IOT Device ID" required>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Local device ID</label>
<input type="text" id="local_device_id" name="local_device_id" class="form-control form-control-sm" placeholder="Enter Local Device ID" required>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-gradient-danger mb-2" data-dismiss="modal" onClick="window.location.reload();">Close</button>
<button type="submit" id="btn-save" value="addNewBook" class="btn btn-sm btn-gradient-danger mb-2">Save</button>
</div>
</form>
</div>
</div>
</div>
and this is ajax code
i just want to run simpal html required field validation with ajax
$('body').on('click','#btn-save', function (event){
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save"). attr("disabled", true);
// ajax
$.ajax({
type:"POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id:id,
user_id:user_id,
machine_name:machine_name,
iot_device_id:iot_device_id,
local_device_id:local_device_id,
},
dataType: 'json',
success: function(res){
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save"). attr("disabled", false);
}
});
});
i just want to run required field validation with ajax i could not find any solution .
Try changing your btn click event to form submit event.
$('body').on('submit', '#addEditBookForm', function (event) {
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save").attr("disabled", true);
// ajax
$.ajax({
type: "POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id: id,
user_id: user_id,
machine_name: machine_name,
iot_device_id: iot_device_id,
local_device_id: local_device_id,
},
dataType: 'json',
success: function (res) {
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save").attr("disabled", false);
}
});
});
The following should help: change to a form confirmation event instead of a Click button event. And do not forget to write this code so that the page does not reload:
event.preventDefault();
I'm trying to insert data to my PHP using ajax post method.I have passed the first form data to hidden value in first script , but data is not inserted in database.Now I want to pass those variables (response.lastname, response.firstname ) into my database.Please help me to solve this issue. Any example will be very useful.. thank u in advance.
php ajax
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div> <form role="form" id="add_name" method="post" enctype="multipart/form-data" action="">
<div class="modal-body">
<table class="table">
<tr>
<th>Last Name</th>
<td id="lname" name="lname" ></td>
</tr>
<tr>
<th>First Name</th>
<td id="fname" name="fname"></td>
</tr>
<tr><td>name</td>
<td><input type="text" name="nam"></td>
</tr> </table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" >Cancel</button>
<button type="submit" class="btn btn-success" id="submit" name="submit"><i class="glyphicon glyphicon-inbox"></i> Submit</button>
</div>
</div>
</form><div id="response"></div>
<script>
$(document).ready(function(){
$('#submitBtn').click(function() {
$('#lname').text($('#lastname').val());
$('#fname').text($('#firstname').val());
var fname = $('#firstname').val();
$('#fname').val(fname);
alert(fname);
var laname = $('#lastname').val();
$('#lname').val(laname);
alert(laname);
});
});
</script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var lname = $('#lname').val();
var fname = $('#fname').val();
alert(lname);
$.ajax({
url:"insert.php",
method:"POST",
data:$('#add_name').serialize(),
beforeSend:function(){
$('#response').html('<span class="text-info">Loading response...</span>');
},
success:function(data){
$('form').trigger("reset");
$('#response').fadeIn().html(data);
setTimeout(function(){
$('#response').fadeOut("slow");
}, 5000);
}
});
});
});
<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "demoss");
$name = mysqli_real_escape_string($connect, $_POST["lname"]);
$message = mysqli_real_escape_string($connect, $_POST["fname"]);
$query = "INSERT INTO tbl_form(name, message) VALUES ('".$name."', '".$message."')";
if(mysqli_query($connect, $query))
{
echo '<p>You have entered</p>';
echo '<p>Name:'.$name.'</p>';
echo '<p>Message : '.$message.'</p>';
}
?>
Try This:
<div class="modal fade" id="confirm-submit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
Confirm Submit
</div>
<form role="form" id="add_name" method="post">
<div class="modal-body">
<table class="table">
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" id="lname"></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" id="fname"></td>
</tr>
<tr>
<td>name</td>
<td>
<input type="text" name="name" id="name">
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success" id="submit">
<i class="glyphicon glyphicon-inbox"></i> Submit</button>
</div>
</div>
</form>
<div id="response"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#submit').click(function () {
var lname = $('#lname').val();
var fname = $('#fname').val();
alert(lname);
$.ajax({
method: "POST",
url: "insert.php",
data: $('#add_name').serialize(),
beforeSend: function () {
$('#response').html('<span class="text-info">Loading response...</span>');
},
success: function (data) {
$('form').trigger("reset");
$('#response').fadeIn().html(data);
setTimeout(function () {
$('#response').fadeOut("slow");
}, 5000);
}
});
});
});
</script>
data:$('#add_name').serialize(), - this convert inputs / textareas in form to one string for url. Your form not have inputs. Try
alert($('#add_name').serialize()) or<br>
alert($('#add_name').serialize().toSource()) // firefox <br>
And, may be second problem, if you call two times $(document).ready, may be rewrite first code with second. Combine to one $(document).ready.<br>
$(document).ready(function(){ callfunction1(); callfunction2(); }
I have a modal, e.g the modal is in modal.html, the method i wrote in a javascript file modal.js. when I am trying to submit data through modal, it is not working properly. the code is below. please help me someone.
/modal.html
<div class="col-md-12 text-right">
<button type="button" data-toggle="modal" data-target="#myModal">Update User Information</button>
<div class="modal fade" id="myModal" 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">Enter User Information</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" class="form-control" id="user_name" placeholder="User name">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email_id" placeholder="Enter email">
</div>
<div class="form-group">
<input type="text" class="form-control" id="address" placeholder="Enter Address">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" id="myFormSubmit">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
/modal.js
$(function() {
$('#myFormSubmit').click(function () {
$.post("/api/adduserInfo/v1",
{
user_name : $("#user_name").val(),
email : $("#email_id").val(),
address : $("#address").val()
});
});
});
You can use something like this (you will have to get the parametres via post on the server side):
<!-- FORM -->
<form id="idform">
<!-- FORM INPUTS -->
<input class="btn btn-large btn-primary" value="Submit" type="submit">
</form>
<script>
// Variable to hold request
var request;
$("#idform").submit(function(event) {
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
$.ajax({
url: '/api/adduserInfo/v1',
type: 'post',
data: serializedData,
beforeSend: function () {
$("#divtoaddresult").html("Processing, please wait...");
},
success: function (response) {
$("#divtoaddresult").html(response);
}
});
});
</script>
My view Page :
<form id="myForm" >
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control datepicker pull-right" name="from_date" placeholder="From"> // want this value in my modal box
</div>
</div>
<div class="col-md-6">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control datepicker pull-right" name="to_date" placeholder="To"> // want this value in my modal box
</div>
</div>
<div class="col-md-12">
<br/>
<center><button class="btn btn-success" onclick="search_sale_return()"><i class="glyphicon glyphicon-plus"></i> Create New Stock</button></center> // on this click call the modal
</div>
</form>
JavaScript
<!-- Search sale return -->
function search_sale_return()
{
save_method = 'sale_return';
$('#form_sale_return')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('PharmacyController/search_sale_return')?>/" + 1, // bring value from database via controller in json_encode form
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="ph_name"]').val(data.from_date);
$('#modal_sale_return').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Sale return'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
Modal
<!-- Bootstrap Receptionist modal -->
<div class="modal fade" id="modal_sale_return" 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">Stock</h3>
</div>
<div class="modal-body form">
<form action="#" id="form_sale_return" class="form-horizontal">
<input type="hidden" value="" name="ph_id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Medicine Name</label>
<div class="col-md-9">
<input name="ph_name" placeholder="Medicine Name" class="form-control" type="text">
<input name="ph_clinic_id" value="<?php echo $userinfo['id']; ?>" type="hidden">
<span class="help-block"></span>
</div>
</div>
</div>
<div class="col-md-12">
<br/>
<table id="table_account" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Transaction Id</th>
<th>Patient Id</th>
<th>Ammount payed</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
</table>
</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 -->
This is my code , here i would like to get the value from form and than use it in my controller via javascript code and get json data and display it on my modal box
My problem :: on submit either i get link to controller or my modal (i wanna go to controller and from there i wanna go to modal in just one click button)
Fast example:
FORM:
<form id="myForm">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar">
</i>
</div>
<input type="text" class="form-control datepicker pull-right" name="from_date" placeholder="From" /> // want this value in my modal box
</div>
<div class="col-md-6">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar">
</i>
</div>
<input type="text" class="form-control datepicker pull-right" name="to_date" placeholder="To" /> // want this value in my modal box
</div>
</div>
<div class="col-md-12">
<br/>
<center>
<button class="btn btn-success" type="submit">
<i class="glyphicon glyphicon-plus">
</i> Create New Stock
</button>
</center>
// on this click call the modal
</div>
</form>
Modal:
<!-- Bootstrap Receptionist modal -->
<div class="modal fade" id="modal_sale_return" 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">Stock</h3>
</div>
<div class="modal-body form">
<form action="#" id="form_sale_return" class="form-horizontal">
<input type="hidden" value="" name="ph_id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Medicine Name</label>
<div class="col-md-9">
<input name="ph_name" placeholder="Medicine Name" class="form-control" type="text">
<input name="ph_clinic_id" value="<?php echo $userinfo['id']; ?>" type="hidden">
<span class="help-block"></span>
</div>
</div>
</div>
<div class="col-md-12">
<br/>
<table id="table_account" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Transaction Id</th>
<th>Patient Id</th>
<th>Ammount payed</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" id="btnSave" 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>
Script:
<script>
$(function() {
$('form#myForm').on('submit',function(event) {
//get value
event.preventDefault();
var from_date = $(this).find('input[name="from_date"]').val();
var to_date = $(this).find('input[name="to_date"]').val();
//get data $_GET
$.ajax({
url: "<?php echo site_url('PharmacyController/search_sale_return')?>", // bring value from database via controller in json_encode form
type: "GET",
data: {from_date: from_date,to_date:to_date},
dataType: "JSON",
success: function(data) {
var modal = $('#modal_sale_return').modal('show');
modal.find('[name="ph_name"]').val(data.name);
modal.find('.modal-title').text('Sale return');
modal.find('#form_sale_return').trigger('reset');
modal.find('.help-block').empty();
modal.find('.form-group').removeClass('has-error');
//etc
//save in modal
$(modal).on('submit','form#form_sale_return',function(e) {
e.preventDefault();
var form = $(this);
var ph_name = form.find('[name="ph_name"]').val();
//etc
$.ajax({
url: "<?php echo site_url('PharmacyController/save')?>",
type: "post",
data:{ph_name:ph_name},
success: function(response) {
alert('SUCCESS')
},
error: function(xhr) {
alert('ERROR');
}
});
});
$('#modal_sale_return').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Sale return'); // Set title to Bootstrap modal title
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
});
});
</script>
I not tested... you try :)
Use
$('#modal_sale_return').modal();
to manually open the modal
Sending form data to controller :
$('#myForm').submit(function(e){
var ajaxForm = $(this)[0];
var formData = new FormData(ajaxForm);
$.ajax({
url: 'url',
type: 'POST',
data: formData,
success: function (result) {
},
error : function() {
}
});
});
I don't know what's wrong with my code, it didn't work.
My controller :
public function add_user_driver()
{
if(!$this->user_permission->check_permission())return;
$plate_number = $this->input->post('plate_number');
$location_id = $this->input->post('location_id');
$data_user = array(
'plate_number' => $plate_number,
'location_id' => $location_id,
);
$this->db->insert('user_driver', $data_user);
echo json_encode(array("plate_number" => $plate_number, "location_id" => $location_id));
}
The view :
<div class="modal fade" id="usermodal" 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">USER_DRIVER</h4>
</div>
<div class="modal-body" id='add'>
<div class="row" id="form_pesan">
<input type="hidden" name="id" id="id" />
<div class="col-sm-6">
<input type="text" class="form-control input-lg" id="plate_number" name="plate_number" placeholder="Plate Number" required>
</div>
<div class="col-sm-6">
<input type="text" class="form-control input-lg" id="location_id" name="location_id" placeholder="Location Id" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="add" type="button" class="btn btn-primary btn-md" onclick=add()>Add</button>
</div>
</div>
<div id="form_submit_result"></div>
</div>
</div>
JavaScript :
$(document).ready(function(){
matchFormFields = "#form_pesan input[required]";
matchFormSubmitResult = "#form_submit_result";
errorColor = 'red';
});
function add(){
var formIsValid = true;
$(matchFormFields).each(function() {
$(this).css('border-color', '');
if(!$.trim($(this).val())) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
});
if (formIsValid) {
plate_number = $("#plate_number").val();
location_id = $("#location_id").val();
$.ajax
({
url : "<?php echo site_url('admin/add_user_driver')?>/",
type: "POST",
dataType: "text",
data:{plate_number: plate_number, location_id: location_id},
success: function(data)
{
$("#usermodal").modal("hide");
$("#alert").show();
//location.reload();
},
error: function (jqXHR, textStatus, errorThrown)
{
notify('Error data');
}
});
};
}
I want to submit value from input text to JavaScript add function, but somehow, the .val() doesn't return the actual value. What did I do wrong?
please try this
datatype: "json"
or
datatype: "text"
JSON.stringify({plate_number: plate_number, location_id: location_id})
var abc = $("#plate_number").val();
alert(abc);
return false;
You can use the variable abc in javascript.