How to use outsider function of jquery document.ready - php

Here i am giving you snippet of my jquery source code. And this is wrote in separate JS file. Guide me how to access add_user function in directly.
if i wrote SRC = assets/js/functions.js. It will give me error of JS because i am using function directly on button onclick event. and I am using single form for ADD USER and EDIT USER.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Demo</title>
<link href="<?php echo base_url() ?>assests/css/bootstrap.min.css"
rel="stylesheet">
<link href="<?php echo base_url() ?>assests/css/dataTables.bootstrap.css"
rel="stylesheet">
<link href="<?php echo base_url() ?>assests/css/custom.css"
rel="stylesheet">
</head>
<body>
<div class="col-md-10 col-md-offset-1">
<button class="btn btn-primary" id="btn_adduser" onclick="add_user()">Add
user</button>
<table id="table_id" class="table table-bordered" cellspacing="0" >
<thead>
<tr>
<th>User ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Status</th>
<th>Created</th>
<th>Modified</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($user as $user){?>
<tr>
<td><?php echo $user->id;?></td>
<td><?php echo $user->firstname;?></td>
<td><?php echo $user->lastname;?></td>
<td><?php echo $user->email;?></td>
<td><?php echo $user->status;?></td>
<td><?php echo $user->created_date;?></td>
<td><?php echo $user->modified_date;?></td>
<td>
<button class="btn btn-primary"
onclick="edit_user(<?php echo $user->id;?>)"><i class="glyphicon glyphicon-
pencil"></i></button>
<button class="btn btn-primary"
onclick="delete_user(<?php echo $user->id;?>)"><i class="glyphicon
glyphicon-
trash"></i></button>
</td>
</tr>
<?php }?>
</tbody>
</table>
</div>
<!--Add / Edit User Section-->
<div class="panel panel-primary col-md-6 col-md-offset-3" style="display:
none;">
<div class="panel-heading">Add user</div>
<div class="panel-body">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<input name="txt_fname" id="txt_fname"
placeholder="Firstname" class="form-control" type="text" required>
</div>
<div class="form-group">
<input name="txt_lname" id="txt_lname"
placeholder="Lastname" class="form-control" type="text" required>
</div>
<div class="form-group">
<input name="txt_email" id="txt_email" placeholder="Email
address" class="form-control" type="email" required>
</div>
<label class="control-label" for="radio_status">Status</label>
<div class="radio">
<label><input type="radio" name="radio_status" id="sta_active"
value="0">Active</label>
</div>
<div class="radio">
<label><input type="radio" name="radio_status"
id="sta_inactive" value="1">Inactive</label>
</div>
</div>
<div class="form-group col-md-6">
<button type="button" class="btn btn-primary" id="btnSave"
onclick="save()" >Save</button>
<button type="reset" class="btn btn-primary">Reset</button>
<button type="button" class="btn btn-primary"
id="btn_hide">Hide</button>
</div>
</form>
</div>
</div>
<!-- End Add / Edit User Section-->
<script src="<?php echo base_url()?>assests/js/jquery-3.1.0.min.js">
</script>
<script src="<?php echo base_url()?>assests/js/bootstrap.min.js"></script>
<script src="<?php echo base_url()?>assests/js/jquery.dataTables.min.js">
</script>
<script src="<?php echo base_url()?>assests/js/dataTables.bootstrap.js">
</script>
<script src="<?php echo base_url()?>assests/js/functions.js"></script>
</body>
</html>
$(document).ready( function () {
$('#table_id').DataTable();
$("#btn_hide").click(function(){
$(".panel").slideUp(500);
});
});
var save_method; //for save method string
var table;
function add_user() {
save_method = 'add';
$(".panel").slideDown(500);
$(".panel-heading").text("Add user");
$('#form')[0].reset(); // reset form on modals
}
function edit_user(id) {
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('index.php/user/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data) {
$('[name="id"]').val(data.id);
$('[name="txt_fname"]').val(data.firstname);
$('[name="txt_lname"]').val(data.lastname);
$('[name="txt_email"]').val(data.email);
$(".panel").slideDown(500);
$(".panel-heading").text("Edit user");
}, error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
}
function save() {
var url;
if(save_method == 'add') {
url = "<?php echo site_url('index.php/user/user_add')?>";
} else {
url = "<?php echo site_url('index.php/user/user_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data) {
//if success close modal and reload ajax table
$(".panel").slideUp(500);
location.reload();// for reload a page
}, error: function (jqXHR, textStatus, errorThrown) {
alert('Please enter valid data');
}
});
}
function delete_user(id) {
if(confirm('Are you sure delete this data?')) {
// ajax delete data from database
$.ajax({
url : "<?php echo site_url('index.php/user/user_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data) {
location.reload();
}, error: function (jqXHR, textStatus, errorThrown) {
alert('Error deleting data');
}
});
}
}
How to use function add_user directly on button's onClick event in HTML from external JS file.

function.js must be before jquery code
<script src='function.js'>
<script>
$(document).ready( function () {
$('#table_id').DataTable();
$("#btn_hide").click(function(){
$(".panel").slideUp(500);
});
$('button.class').click(function(){
add_user();
})
});
</script>

Related

Passing an id from foreach to jquery modal

I want the modal to open when the user clicks on the create asset button, and after filling in the modal fields and clicking the save button, the asset group ID with the modal data is also received from foreach and sent via Ajax request.
How is this possible?
foreach:
#foreach ($AssetsGroup as $AssetGroup)
<tr id="assetgroup{{$AssetGroup->id}}" class="active">
<td>{{$AssetGroup->name}}</td>
<td></td>
<td></td>
<td width="auto">
// if click this button then modal show
<button id="btn_add" name="btn_add" value="{{ $AssetGroup->id }}" data-toggle="modal" and data-target="#assetModal">create assets</button>
</td>
</tr>
#endforeach
Jquery Modal:
<div class="modal fade" id="assetModal" tabindex="-1" role="dialog" aria-labelledby="assetModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<form id="frmassets" name="frmassets" class="form-horizontal" novalidate="">
<div class="form-group row">
<label for="name">asset name</label>
<input type="text" id="name2" name="name2">
</div>
<div class="form-group row">
<label for="name">tags</label>
<input id="tags2" name="tags2" type="text"/>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btn-save" value="add">save</button>
<input type="hidden" id="asset_id" name="asset_id" value="0">
</div>
</div>
</div>
</div>
Ajax:
$("#btn-save").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
e.preventDefault();
var formData = {
name: $('#name2').val(),
group: i want to resive group id from foreach and send group id with ajax request
tags: $('#tags2').val(),
}
//used to determine the http verb to use [add=POST], [update=PUT]
var state = $('#btn-save').val();
var type = "POST"; //for creating new resource
var asset_id = $('#asset_id').val();
var my_url = '/assets';
if (state == "update"){
type = "PUT"; //for updating existing resource
my_url += '/' + asset_id;
}
console.log(formData);
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
...
},
error: function (data) {
console.log('Error:', data);
}
});
});
You can use data attribute to achieve this -
Blade file code -
#foreach ($AssetsGroup as $AssetGroup)
<tr id="assetgroup{{$AssetGroup->id}}" class="active">
<td>{{$AssetGroup->name}}</td>
<td></td>
<td></td>
<td width="auto">
<button id="btn_add" name="btn_add" data-asset-id="{{ $AssetGroup->id }}">create assets</button>
</td>
</tr>
#endforeach
Js code -
$('#btn_add').click(function() {
$('#assest_id').val($(this).data('asset-id'));
$('#assetModal').modal('show');
});
Now when you send your ajax request you can get the asset_id field value.

I am trying to retrieve data from a database using ajax and populate in form that is in a bootstrap modal

I need a help here when I click on the edit button on the image below i expect to see data populated on a form in a bootstrap modal window I am using jquery ajax method to populate the data in the form of
and the edit modal image
Here is code for the home page
<?php require_once("connect.php"); ?>
<?php require_once("fetch.php"); ?>
<?php require_once("select.php"); ?>
<?php require_once("process.php"); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Home</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<ul class="nav nav-pills">
<li>Home</li>
</ul>
<button type="button" class="btn btn-primary pull-right" data-toggle="modal" data-target="#myModal">Add</button>
<table class="table" id="table">
<tr>
<th>S/N</th>
<th>Name</th>
<th>Email</th>
<th>Description</th>
<th>Edit</th>
<th>View</th>
<th>Delete</th>
</tr>
<?php
$query = "SELECT * FROM contact";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run select query ".mysqli_error($connect));
}
$sn = 1;
while($row = mysqli_fetch_assoc($runQuery)){ ?>
<tr>
<td><?php echo $sn++ ?></td>
<td><?php echo $row["name"] ?></td>
<td><?php echo $row["email"] ?></td>
<td><?php echo $row["description"] ?></td>
<td>
<button type="button" data-toggle="modal" data-target="#myModal" class="btn btn-warning btn-sm edit-data" id="<?php echo $row['userid'] ?>">Edit</button>
</td>
<td>
<button type="button" data-target="#viewModal" data-toggle="modal" class="btn btn-primary btn-sm view-data" id="<?php echo $row['userid'] ?>">View</button>
</td>
<td>
<button type="button" class="btn btn-danger btn-sm del-data" id="<?php echo $row['userid'] ?>">Danger</button>
</td>
</tr>
<?php } ?>
</table>
<!-- Modal -->
<div id="myModal" 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">Add Data</h4>
</div>
<div class="modal-body">
<div id="success" class="alert alert-success"></div>
<form class="form" method="POST" id="insertData">
<div id="nameError" class="alert alert-danger"></div>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div id="emailError" class="alert alert-danger"></div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" id="email">
</div>
<input type="hidden" name="userid" id="contactUserId">
<div id="descriptionError" class="alert alert-danger"></div>
<div class="form-group">
<label>Description</label>
<textarea name="description" id="description" class="form-control"></textarea>
</div>
<input type="submit" class="btn btn-primary" value="Add" name="add" id="add">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="viewModal" 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">View Data</h4>
</div>
<div class="modal-body" id="contactDetail">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/myscript.js"></script>
</body>
</html>
This code is for entering and updating data in the database process.php
<?php
if(!empty($_POST)){
$name = $_POST["name"];
$email = $_POST["email"];
$description = $_POST["description"];
$userid = $_POST["userid"];
if($userid != ''){
$query = "UPDATE contact SET name = '$name', email='$email', description='$description' WHERE userid = $userid ";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run query ".mysqli_error($connect));
}
}else{
$query = "INSERT INTO contact(name, email, description) VALUES ";
$query .=" ('$name', '$email', '$description')";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run insert query ".mysqli_error($connect));
}
}
}
This code retrieves data from database
<?php
if(isset($_POST['userid'])){
$editId = (int)$_POST['userid'];
$query = "SELECT * FROM contact WHERE userid = $editId";
$runQuery = mysqli_query($connect, $query);
if(!$runQuery){
die("Could not run query ".mysqli_error($connect));
}
$getData = mysqli_fetch_assoc($runQuery);
echo json_encode($getData);
}
This is my js file
$(document).ready(function(){
$("#insertData").submit(function(event){
event.preventDefault();
if($("#name").val() == ""){
$("#nameError").css("display", "block").html("Name is required");
}else if ($("#email").val() == "") {
$("#emailError").css("display", "block").html("Email is required");
}else if ($("#description").val() == "") {
$("#descriptionError").css("display", "block").html("Description is required");
}else{
$.ajax({
url: "index.php",
method: "POST",
data: $("#insertData").serialize(),
success: function(data){
$("#success").css("display", "block").html("Data added");
$("#insertData")[0].reset();
}
});
}
});
$(document).on("click", ".edit-data", function(){
var contactId = $(this).attr("id");
$.ajax({
url:"index.php",
method: "POST",
data: {contactId:contactId},
dataType: "json",
success: function(data){
$("#name").val(data.name);
$("#email").val(data.email);
$("#description").val(data.description);
$("#contactUserId").val(data.userid);
$("#add").val("Update");
$("#myModal").modal("show");
}
});
});
$(document).on('click', '.view-data', function(){
var contactId = $(this).attr("id");
if(contactId != '')
{
$.ajax({
url:"index.php",
method:"POST",
data:{contactId:contactId},
success:function(data){
$('#contactDetail').html(data);
$('#viewModal').modal('show');
}
});
}
});
});
You are sending contactId and in your PHP you are looking for userid. Change your data to data: { userid: userid }.
$(document).on("click", ".edit-data", function() {
var userid = $(this).attr("id");
$.ajax({
url: "index.php",
method: "POST",
data: { userid: userid },
dataType: "json",
success: function(data) {
$("#name").val(data.name);
$("#email").val(data.email);
$("#description").val(data.description);
$("#contactUserId").val(data.userid);
$("#add").val("Update");
$("#myModal").modal("show");
}
});
});

how to update with modal bootstrap and checkbox

hey guys how can i update multiple rows with checkbox and display modal bootstrap after pressing update button?
example like this:
I checked the line with the checkbox
After that I press "Pindah Department" or in english "Move Departemen"
actually I do not need the edit book () function, I only need one function and the funtion it can call modal bootstrap pops up, to update from the dropdown menu"
i forgot to change save button to call function prepareData(), pop up appears, but I do not know what it is
I can only edit it one by one, with Modal Bootstrap, how can i be like above that?
this is my view:
<table id="emp_id" class="table table-bordered dt-responsive" cellspacing="0" width="100%">
<thead>
<tr>
<th width="1%" align="center"><input type="checkbox" onClick="toggle(this)" id="checkAll" name="checkAll" /></th>
<th width="1%" align="center">No.</th>
<th width="1%" align="center">Edit</th>
<th width="20%" align="center">Nama Lengkap</th>
<th width="5%" align="center">No Induk</th>
<th width="10%" align="center">Jenis Kelamin</th>
<th width="5%" align="center">PIN</th>
<th width="20%" align="center">Departemen</th>
</tr>
</thead>
<tbody>
<?php
foreach($data as $d){
?>
<tr>
<td>
<input class="childbox" width="1%" type="checkbox" name="msg[]" id="id" align="center" value="<?php echo $d['emp_id'] ?>" />
</td>
<td width="1%" align="center"><?php echo $d['emp_id']; ?></td>
<td><button class="btn btn-light" onclick="edit_book(<?php echo $d['emp_id'];?>)"><i class="glyphicon glyphicon-pencil"></i></button></td>
<td class="data-check"><?php echo $d['first_name']; ?></td>
<td class="data-check"><?php echo $d['nik']; ?></td>
<td class="data-check"><?php echo $d['gender']=='0' ? 'Laki-Laki' : 'Perempuan'; ?></td>
<td class="data-check"><?php echo $d['pin']; ?></td>
<td class="data-check"><?php echo $d['dept_name']; ?></td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<th width="1%" align="center"><input type="checkbox" onClick="toggle(this)" id="checkAll" name="checkAll" /></th>
<th width="1%" align="center">No.</th>
<th width="1%" align="center">Edit</th>
<th width="20%" align="center">Nama Lengkap</th>
<th width="5%" align="center">No Induk</th>
<th width="10%" align="center">Jenis Kelamin</th>
<th width="5%" align="center">PIN</th>
<th width="20%" align="center">Departemen</th>
</tr>
</tfoot>
</table>
this is my script to bring up modal bootstrap and for checkbox functions:
<script type="text/javascript">
$(document).ready( function () {
$('#emp_id').DataTable( {
"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
} );
$("input[name='checkAll']").click(function() {
var checked = $(this).attr("checked");
$("#emp_id tr td input:checkbox").attr("checked", checked); });
} );
function toggle(id) {
checkboxes = document.getElementsByName('msg[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = id.checked;
}
}
function add_book()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
//$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
}
function edit_book(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('proses/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="emp_id"]').val(data.emp_id);
$('[name="dept_id_auto"]').val(data.dept_id_auto);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Departemen'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('proses/book_add')?>";
}
else
{
url = "<?php echo site_url('proses/book_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
</script>
and this is my modal bootstrap :
<div id="modal_form" 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" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Tambah Siswa</h4>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="emp_id"/>
<div class="form-body">
<div class="form-group">
<label for="colFormLabelLg" class="col-sm-4 col-form-label col-form-label-lg">Pilih Departemen Baru</label>
<div class="col-sm-6">
<select name="dept_id_auto" class="form-control pull-right">
<?php
foreach($groups as $row)
{
echo '<option name="dept_id_auto" value="'.$row['dept_id_auto'].'">'.$row['dept_name'].'</option>';
}
?>
</select>
</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-info" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
and this is my controller :
public function book_update()
{
$data = array(
'dept_id_auto' => $this->input->post('dept_id_auto'),
);
$this->Pindah_dept_model->book_update(array('devid_auto' => $this->input->post('devid_auto')), $data);
echo json_encode(array("status" => TRUE));
}
public function ajax_edit($id)
{
$data = $this->Pindah_dept_model->get_by_id($id);
echo json_encode($data);
}
and this is my model :
public function get_by_id($id)
{
$this->db->from($this->table);
$this->db->where('emp_id',$id);
$query = $this->db->get();
return $query->row();
}
public function book_update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
hey Eiji can you modify this code because, if I use this code I can do multiple update rows, but this code does not display modal bootstrap, it's just this code directly call the function in the controller, but have the same concept only this code can not display modal bootstrap, please
function update(id)
{
var list_id = [];
$("#id:checked").each(function() {
list_id.push(parseInt(this.value));
});
console.info(JSON.stringify(list_id));
if(list_id.length > 0)
{
if(confirm('Are you sure update this '+list_id.length+' data?'))
{
$.ajax({
type: 'POST',
data: {'devid_auto': list_id},
url: '<?php echo site_url('setting/mesin_update')?>',
success: function(result)
{
var hasil = result.replace(/\s/g,'');
if(hasil == 'y')
{
alert("Data Berhasil di Update");
location.reload();
}
else
{
alert('Failed.');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error update data');
}
});
}
}
else
{
alert('no data selected');
}
}
Small correction in your html, Please delete the id="id", this is a big mistakes, because the id shoud be unique.
<input class="childbox" width="1%" type="checkbox" name="msg[]" align="center" value="" data-userid="<?php echo $d['emp_id'] ?>"/>
you have to define which of your line has been checked.
var user_id_list = []; //this will be the collection of id
//for each checked checkbox do...
$("input[type=checkbox].childbox").each(function(){
//get the user id value of the line
var the_userid = $(this).data('userid');
//add it to our collection
user_id_list.push( the_userid );
});
you find what is the option selected.
var new_dept = $("#modal_form select[name=dept_id_auto] option:selected").val();
You have to pass all this to your ajax request. So there is your ajax and a new function to add
function save()
{
var url;
if(save_method == 'add')
{
url = "<?php echo site_url('proses/book_add')?>";
}
else
{
url = "<?php echo site_url('proses/book_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: prepareData(), //<-- here we call it
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
function prepareData(){
$data = [];
var user_id_list = []; //this will be the collection of id
//for each checked checkbox do...
$("input[type=checkbox].childbox").each(function(){
//get the user id value of the line
var the_userid = $(this).data('userid');
//add it to our collection
user_id_list.push( the_userid );
});
//select the new debt value
var new_dept = $("#modal_form select[name=dept_id_auto] option:selected").val();
//we pass all the data to an array
data.push('user_id_list',user_id_list);
data.push('new_dept', new_dept);
return data;
}
Now, in your controller, you should have two post data :
* new_dept, which content an int of the new dept
* user_id_list, which is an array of id.
So you just need to adapt your model and it's over.
Change the line
<div class="modal-footer">
<!-- change here -->
<button type="button" id="btnSave" onclick="prepareData()" class="btn btn-primary">Save</button>
<!-- end change -->
<button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
</div>
Then, in your javascript function prepareData()
//we pass all the data to an array
data.push('user_id_list',user_id_list);
data.push('new_dept', new_dept);
//add this line for the debugging
alert( JSON.stringify(data) )
//this will display the current data value, even if it's an array/object or whatever
return data;
you can use my code for referenction
<td>
<button class="btn btn-success" data-toggle="modal" data-target="#r<?php echo $rule2->id_forward;?>">Edit </button>
<?=anchor('guru/hapus_rule/'.$rule2->id_forward,'Hapus',['class'=>'btn btn-danger btn-sm'])?>
</td>
<div class="modal modal-success" id="r<?php echo $rule2->id_forward;?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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>
<h4 class="modal-title" align="center">Edit Rule</h4>
</div>
<div class="modal-body">
<?php echo form_open_multipart('guru/ubah_rule/'.$rule2->id_forward);?>
<div class="form-group">
<label for="Kondisi">Kondisi 1</label>
<select class="form-control" name="kondisi">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_1==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_2">Kondisi 2</label>
<select class="form-control" name="kondisi_2">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_2==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_3">Kondisi 3</label>
<select class="form-control" name="kondisi_3">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_3==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_4">Kondisi 4</label>
<select class="form-control" name="kondisi_4">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_4==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="Kondisi_5">Kondisi 5</label>
<select class="form-control" name="kondisi_5">
<option value="">Pilih</option>
<?php foreach ($kondisi as $key) {?>
<option value="<?php echo $key->nama_kondisi?>" <?php if($rule2->gejala_5==$key->nama_kondisi){echo "selected";} ?>><?php echo $key->nama_kondisi; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="hasil">Hasil</label>
<input type="text" name="hasil" class="form-control" value="<?php echo $rule2->hasil; ?>">
</div>
<div class="form-group">
<label for="artikel">Artikel</label>
<select class="form-control" name="id_artikel">
<option value="">Pilih</option>
<?php foreach ($artikel as $data_rule) { ?>
<option value="<?php echo $data_rule->id_artikel; ?>" <?php if($rule2->id_artikel==$data_rule->id_artikel){echo "selected";} ?> ><?php echo $data_rule->judul; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label for="exampleInputFile">File Pembelajaran</label>
<input type="file" name="berkas" id="exampleInputFile">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-outline">Save changes</button>
</div>
</form>
</div>
<!-- /.modal-content -->
</div>
</div>

Showing fake path while updating the image in the database

<script type="text/javascript">
$('#t').on('click','#btns',function() {
var id = $(this).attr('data-id');
var image = $(this).attr('data-image');
$('#dats').val(id);
$('#Mimage').val(image);
});
$(document).ready(function() {
$.ajax({
type: "POST",
url: "query1.php",
success: function(data) {
var parsed = $.parseJSON(data);
$.each(parsed, function(i,parsed) {
$('#t').append('<tr><td>'+parsed.id+'</td><td id="edi"><img src="upload/'+parsed.image+'" height = "50px" width = "50px"></td><td>'+'<button class="button info" name="btn" data-toggle="modal" data-target="#Mpn" id="btns" data-id="'+parsed.id+'" data-image="'+parsed.image+'">Edit</button>'+'<button class="button info1" name="btn" data-toggle="modal" data-target="#Mpd" id="btns" data-id="'+parsed.id+'" data-image="'+parsed.image+'">Delete</button>'+'</td></tr>');
});
}
});
$('body').on('click','#update',function(e) {
alert("hi");
var id = $('#dats').val();
alert(id);
var images = $('#Limage').val();
alert(images);
$.ajax({
type:"POST",
url:"upd.php",
data:{mode:'upd',id:id,images:images},
success:function(data){
alert(data);
alert("successfully updated");
}
});
});
});
</script>
<!Doctype html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="modal fade" id="Mpn" tabindex="-1" role="dialog" aria-labelledby="edit-modal-label">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form class="form-horizontal" id="edit-form">
<input type="hidden" id="dats" name="id" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 align="center" class="modal-title" id="edit-modal-label" >Save Changes</h4>
</div>
<div class="modal-body">
<div class="form-group" enctype="multipart/form-data">
<label for="username" class="col-sm-2 control-label">Image</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Mimage" name="image" />
</br>
<input type="file" class="form-control" id="Limage" name="image" placeholder=""required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="update" id="update">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<?php
if(($_POST['mode'])=='upd') {
$id = $_POST['id'];
echo $id;
$images = $_POST['images'];
echo $images;
$query = mysqli_query($con,"UPDATE image SET image = '$images' WHERE id = '".$_POST["id"]."'");
<img class="img-responsive" src= "upload/3.jpg" alt="image" id="Mimage" name="image" />
if($query == true) {
echo "File Uploaded";
}
}
?>
Context:
This code is to update the image in the database.This is not working properly when i uploading the image the image enters into the database but as C:fakepathimg.jpg.It is not entering into the actual folder.If it is get rid of fake path the image will be updated.The image displays as fakepath.If the path is correct i think the the image will be updated.

Codeigniter and Angular data post

[EDIT]just put the post data in a var and delete $scope.
$scope.deleteData = function(email) {
if(confirm("Are you sure you want to delete this record?")){
var email1= email; $http.post('<?php echo site_url("index.php/user/delete_user");?>', {'email':email1}).error(function(){ console.log("error"); });
}
}
whenever i press delete button nothing happens.
please check the code and please reply with the solution. network payload pass nothing {}.
view/user_view.php
<!DOCTYPE html >
<html lang="en" ng-app="userApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script type="text/javascript" src="<?php echo base_url('assets/jquery/jquery-3.1.1.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo base_url('assets/bootstrap/js/bootstrap.min.js'); ?>"></script>
<link href="<?php echo base_url('assets/bootstrap/css/bootstrap.min.css'); ?>">
<script type="text/javascript">
/*function userController($scope,$http) {
$scope.users = [];
$http.get('<?php echo site_url('index.php/user/user_list'); ?>').success(function($data){ $scope.users=$data; });
}*/
var app = angular.module('userApp', []);
app.controller('userController', function($scope, $http) {
//$scope.buttonName = "Add";
$scope.deleteData = function() {
/*$http.post("<?php echo base_url(); ?>index.php/User/delete_user/",{'id':$scope.id})
.success(function(data,status,headers,config){
$scope.message = "Deleted Successfully!";
});
*/
$http.post('<?php echo site_url('index.php/user/delete_user');?>',
{'email':$scope.email}).error(function(){
console.log("error");
})
}
$scope.displayUsers = function() {
$scope.users = [];
$http.get('<?php echo site_url("index.php/user/user_list"); ?>').success(function($data){ $scope.users=$data; });
}
$scope.insertData = function(){
$http.post('<?php echo site_url('index.php/user/insert_user');?>',
{
'name':$scope.name,
'gender':$scope.gender,
'email':$scope.email,
'address':$scope.address,
'phone':$scope.phone
}).error(function() {
console.log("Error");
});
}
});
</script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body ng-controller="userController">
<!-- ng-app : which tells the Angular framework to parse data from this div -->
<div class="container" ng-init="displayUsers()">
<button class="btn" data-toggle="modal" data-target="#myModal">Add Users</button>
<div class="row">
<div class="col-lg-12 col-md-12">
<input type="search" class="form-control" ng-model="searchUser" placeholder="Live Search">
<table class="table table-bordered table-condensed table-responsive" ng-controller="userController">
<thead>
<tr>
<td>Select</td>
<td>Name</td>
<td>Gender</td>
<td>Email</td>
<td>Address</td>
<td>Phone Number</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | filter:searchUser">
<td><input type="checkbox"></td>
<td class="hidden">{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.gender}}</td>
<td>{{user.email}}</td>
<td>{{user.address}}</td>
<td>{{user.phone}}</td>
<td>
<button class="btn btn-primary">Edit</button>
<button class="btn" name="btnDelete" ng-click="deleteData(user.email)" value="delete">Delete</button></td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-lg" 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">Modal title</h4>
</div>
<div class="modal-body">
<div class="col-md-12">
<form class="form form-horizontal">
<div class="form-group hidden">
<label for="name">id</label>
<input type="hidden" class="form-control" ng-model="id" id="name">
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" ng-model="name" id="name">
</div>
<div class="form-group">
<label for="gender">Gender</label>
<input type="radio" id="gender" ng-model="gender" value="male">Male
<input type="radio" id="gender" ng-model="gender" value="female">Female
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" ng-model="email" id="email">
</div>
<div class="form-group">
<label for="address">Address</label>
<input type="text" class="form-control" ng-model="address" id="address">
</div>
<div class="form-group">
<label for="phone">Phone Number</label>
<input type="text" class="form-control" ng-model="phone" id="phone">
</div>
<button type="button" class="btn btn-primary" ng-click="insertData()" type="submit">Insert</button>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
controller/User.php
<?php
defined('BASEPATH') OR EXIT ('DIRECT ACCESS IS NOT ALLOWED');
class User extends CI_Controller{
public function index(){
$this->load->view('user_view');
}
public function user_list(){
$data = $this->user_model->get_user_list();
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
public function insert_user(){
//$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$_POST = json_decode(file_get_contents('php://input'),true);
$data = $_POST;
$this->user_model->insert_user_data($data);
}
public function delete_user(){
$_POST = json_decode(file_get_contents('php://input'),true);
$email= $_POST['email'];
$this->user_model->delete_user_data($email);
}
}
?>
model/user_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model{
protected $table_name;
public function __construct(){
parent::__construct();
$this->table_name = 'user';
}
public function get_user_list(){
return $this->db->from($this->table_name)->get()->result_array();
}
public function insert_user_data($data){
$this->db->insert($this->table_name, $data);
}
public function delete_user_data($email){
$this->db->where('email',$email);
$this->db->delete('user');
}
}
?>
Network after click on delete.
The thing you are doing a wrong here is, passing email as an argument in function, you are not utilizing it:
$scope.deleteData = function(email) {
$http.post('<?php echo site_url('index.php/user/delete_user');?>',
{'email':email}).error(function(){
console.log("error");
})
}
use double quotes inside single quotes
$http.post('<?php echo site_url("index.php/user/delete_user");?>',
{'email':$scope.email}).error(function(){
console.log("error");
})

Categories