get values and update in modal popup without page refresh in codeigntier - mysql

guys, I am trying to get values from the modal popup and update the values without page refresh in CodeIgniter can anyone help me how to do that
Here is my modal popup:
<td class='text-center'>
<form method="post" action="" id="emp-update">
<input type="hidden" name="emp_id" value="<?php echo $emp->id; ?>">
<button type="button" href="#updateEmp" onclick="getSummary(36)" class="btn btn-info btn-xs" data-toggle="modal"><i class='fas fa-edit'></i></button>
</form>
</td>
<div class="modal fade" id="updateEmp" tabindex="-1" role="dialog" aria-labelledby="updateEmp" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" id="modal-content">
<form action="" id="emp-create" class="form-horizontal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Update Employee</h4>
</div>
<div class="modal-body" id="modal-body">
<div class="form-group">
<label for="emp_name" class="col-sm-4 control-label">Name : </label>
<div class="col-md-8">
<input type="text" id="emp_name" name="emp_name" class="form-control" placeholder="Name" />
</div>
</div>
<div class="form-group">
<label for="salary" class="col-sm-4 control-label">Salary: </label>
<div class="col-md-8">
<input type="text" id="salary" name="salary" class="form-control" placeholder="Salary" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" value="submit" class="btn btn-primary submit" id="submit">Update</button>
</div>
</form>
</div>
</div>
</div>
Here is my controller:
public function editEmp() {
if ($this->input->post('emp_id')) {
$id = $this->input->post('emp_id');
$data['empName'] = $this->Emp_model->getEmpName($id);
$this->load->view('template/header');
$this->load->view("employee/createemployee", $data);
$this->load->view('template/footer');
}
}
Here is my model:
function getEmpName($id) {
$this->db->select('*');
$this->db->from('employees');
$this->db->where('id', $id);
if ($query = $this->db->get()) {
return $query->result_array();
} else {
return false;
}
}
Can anyone help me how we can do that?

Hope this will help you :
Your model method getEmpName method should be like this :
function getEmpName($id) {
$this->db->select('*');
$this->db->from('employees');
$this->db->where('id', $id);
if ($query->num_rows() > 0 ) {
return $this->db->get()->row();
} else {
return false;
}
}
your mdoel html should be like this :
<div class="modal fade" id="updateEmp" tabindex="-1" role="dialog" aria-labelledby="updateEmp" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" id="modal-content">
<form action="" id="emp-update-form" class="form-horizontal">
<input type="hidden" name="emp_id" value="<?=$empName->id;?>">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Update Employee</h4>
</div>
<div class="modal-body" id="modal-body">
<div class="form-group">
<label for="emp_name" class="col-sm-4 control-label">Name : </label>
<div class="col-md-8">
<input type="text" id="emp_name" name="emp_name" class="form-control" placeholder="Name" value="<?=$empName->emp_name;?>" />
</div>
</div>
<div class="form-group">
<label for="salary" class="col-sm-4 control-label">Salary: </label>
<div class="col-md-8">
<input type="text" id="salary" name="salary" class="form-control" placeholder="Salary" value="<?=$empName->salary;?>" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" value="submit" class="btn btn-primary submit" id="submit">Update</button>
</div>
</form>
</div>
</div>
</div>
Replace Controller_name with your controller name in ajax url
$(function() {
$('#emp-update-form').on('submit',function(e){
var formdata = $(this).serialize();
alert('submit is working');
$.ajax({
type: "POST",
url: "<?=site_url('Controller_name/getEmployeeDetails');?>",
dataType: 'json',
data: formdata,
success: function(res) {
if (res)
{
alert(res.status);
}
},
});
e.preventDefault();
});
});
Your controller method getEmployeeDetails should be like this :
public function getEmployeeDetails()
{
//print_r($this->input->post());
$response['status'] = 'success';
echo json_encode($response);
exit;
}

you can try Ajax on submit your modal popup form
$("#emp-create").on("submit",function(){
var emp_data = $(this).serialize();
$.ajax({
url: 'your controller url to update the popup details',
data: emp_data,
type: 'POST',
success: function(){}
});
});

Related

1 Submit not working out of 3 Submit buttons in a form

Scenario :
Bootstrap 4 form has
1 submit button down the bottom
2 modals with a submit button in each.
Working Submit buttons :
Main submit button works.
Add new contractor modal submit button works.
Make Submit to work :
Add new contractor contact modal submit button not working.
I have put the shorted code in here but the button not working is at the very bottom and you cant see it because the error message cuts it off.
Here is the jsfiddle version.
//Add new contractor
$("#contractor").change(function () {
if ($(this).val() === 'addnewcon') {
$('#addnewconmodal').modal({show: true});
} else if ($(this).val() !== 'addnewcon') {
$('#addnewconmodal').modal({show: false});
}
});
//Add new contractor contact
$("#contact").change(function () {
if ($(this).val() === 'addnewcontact') {
$('#addnewcontactmodal').modal({show: true});
} else if ($(this).val() !== 'addnewcontact') {
$('#addnewcontactmodal').modal({show: false});
}
});
//Ajax call to get selected contractor
$("#contractor").on('change',function() {
var conselected = $(this).val();
if(conselected != "") {
$.ajax({
url:"ajax.php",
data:{consel_id:conselected},
type:'POST',
success:function(response) {
console.log(response);
var resp = $.trim(response);
$("#contact").html(resp);
console.log(resp);
$("#contact").selectpicker('refresh');
}
});
} else {
$("#contact").html("<option value=''>------- Select --------</option>");
}
});
//Ajax add new contractor
$(".cont_add").click(function() {
$(".selectpicker").selectpicker('refresh');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
if(isset($_POST['add_job'])){
$req_fields = array('location','contractor','length', 'groundc' );
validate_fields($req_fields);
if(empty($errors)){
$j_location = remove_junk($db->escape($_POST['location'])); //checked
$j_startdate = remove_junk($db->escape($_POST['startdate'])); //checked
$n_startdate = date('Y-m-d', strtotime($j_startdate));
$j_address = remove_junk($db->escape($_POST['address'])); //checked
$j_contractor = remove_junk($db->escape($_POST['contractor'])); //checked
$j_contractor_contact = remove_junk($db->escape($_POST['contact'])); //checked
$j_length = remove_junk($db->escape($_POST['length'])); //checked
$j_groundc = remove_junk($db->escape($_POST['groundc'])); //checked
$j_jobstatus = remove_junk($db->escape($_POST['jobstatus'])); //checked
$j_driller = remove_junk($db->escape($_POST['driller'])); //checked
$j_boresize = remove_junk($db->escape($_POST['boresize']));
$j_pipesize = remove_junk($db->escape($_POST['pipesize']));
$j_belowinvert = remove_junk($db->escape($_POST['belowinvert']));
$j_grade = remove_junk($db->escape($_POST['grade']));
$j_centers = remove_junk($db->escape($_POST['centers']));
$j_centraliser = remove_junk($db->escape($_POST['centraliser']));
$j_notes = remove_junk($db->escape($_POST['notes']));
$date = make_date();
if(!isset($_POST['startdate']) || empty($_POST['startdate'])) {
$n_startdate = 'NULL';
} else {
$j_startdate = remove_junk($db->escape($_POST['startdate']));
$n_startdate = date('Y-m-d H:i:s', strtotime($j_startdate));
$n_startdate = sprintf("'%s'", $n_startdate);
}
$query = "INSERT INTO job (job_status_id, start_date, date_added, location, address, driller_id, contractor_id, bore_size,
head_id, cutters_id, pipe_size, length, ground_conditions, shield_size, depth, below_invert, grade, centers, hydrant,
hydrant_type, vacuum_hose, centralisers, notes)";
$query .= "VALUES ('{$j_jobstatus}', {$n_startdate}, '{$date}', '{$j_location}', '{$j_address}', '{$j_driller}', '{$j_contractor}', '{$j_boresize}', '{$j_pipesize}', '{$j_length}', '{$j_groundc}', '{$j_belowinvert}', '{$j_centers}', '{$j_centraliser}', '{$j_notes}')";
if($db->query($query)){
$session->msg('s',"Job added ");
redirect('add_job.php', false);
} else {
$session->msg('d',' Sorry failed to added!');
redirect('jobs.php', false);
}
} else{
$session->msg("d", $errors);
redirect('add_job.php',false);
}
} elseif(isset($_POST['add_cont'])){
$req_fields = array('n_contractor_name');
validate_fields($req_fields);
if(empty($errors)){
$name = remove_junk($db->escape($_POST['n_contractor_name']));
$query = "INSERT INTO contractor (";
$query .="Name";
$query .=") VALUES (";
$query .=" '{$name}'";
$query .=")";
if($db->query($query)){
//sucess
$session->msg('s',"New contractor has been creted! ");
redirect('add_job.php', false);
} else {
//failed
$session->msg('d',' Sorry failed to add contractor!');
redirect('add_job.php', false);
}
} else {
$session->msg("d", $errors);
redirect('add_job.php',false);
}
} elseif(isset($_POST['add_new_contact'])){
$req_fields = array('n_contractor_contact_name', 'n_contractor_contact_number', 'n_contractor_contact_id');
validate_fields($req_fields);
if(empty($errors)){
$contact_name = remove_junk($db->escape($_POST['n_contractor_contact_name']));
$contact_number = remove_junk($db->escape($_POST['n_contractor_contact_number']));
$contact_id = remove_junk($db->escape($_POST['n_contractor_contact_id']));
$query = "INSERT INTO contractor_contact (Name, Number, contractor_id)";
$query .="VALUES ('{$contact_name}','{$contact_number}','{$contact_id}')";
if($db->query($query)){
//sucess
$session->msg('s',"New contractor has been creted! ");
redirect('add_job.php', false);
} else {
//failed
$session->msg('d',' Sorry failed to add contractor!');
redirect('add_job.php', false);
}
} else {
$session->msg("d", $errors);
redirect('add_job.php',false);
}
}
?>
<?php include_once('layouts/header.php'); ?>
<div class="row">
<div class="col-md-12">
<?php echo display_msg($msg); ?>
</div>
</div>
<form method="post" action="add_job.php" class="clearfix">
<!-- Buttons At bottom -->
<div class="row" id="addbuttons">
<div class="col-md-12 col-md-offset-1">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<strong>
<span class="glyphicon glyphicon-th"></span>
<span></span>
</strong>
</div>
<div class="row justify-content-center">
<div class="col-md-2">
<button type="button" name="goback" onclick="goBack()" class="btn btn-danger">Back</button>
<button type="submit" name="add_job" class="btn btn-success">Add job</button>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal add new contractor -->
<div id="addnewconmodal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Add new contractor</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form method="post" id="insert_new_contractor">
<input type="hidden" value="add" name="action" id="action">
<div class="col-md-5">
<div class="form-group">
<label for="form_n_contractor_name">Contractor's name</label>
<input id="form_n_contractor_name" type="text" name="n_contractor_name" class="form-control" placeholder="Contractor's name">
<div class="help-block with-errors"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary add_cont" id="add_cont" name="add_cont">Save</button>
</div>
</div>
</div>
</div>
<!-- Modal add new contractor -->
<!-- Modal add new contractor contact -->
<div id="addnewcontactmodal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Add new contact</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form method="post" id="insert_new_contractor_contact">
<input type="hidden" value="add" name="action" id="action">
<div class="col-md-5">
<div class="form-group">
<label for="form_n_contractor_contact_id">Contractor ID</label>
<input id="form_n_contractor_contact_id" type="hidden number" name="n_contractor_contact_id" class="form-control" value="<?php echo $con['ID'] ?>">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label for="form_n_contractor_contact_name">Contractor's name</label>
<input id="form_n_contractor_contact_name" type="text" name="n_contractor_contact_name" class="form-control" placeholder="Contractor's name">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label for="form_n_contractor_contact_number">Contractor's number</label>
<input id="form_n_contractor_contact_number" type="tel" name="n_contractor_contact_number" class="form-control" placeholder="Contractor's number">
<div class="help-block with-errors"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary add_new_contact" id="add_new_contact" name="add_new_contact">Save</button>
</div>
</div>
</div>
</div>
<!-- Modal add new contractor contact -->
</form>
Below is the combination of your two snippets. I surround the first one with script tag and remove the last line });.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
if(isset($_POST['add_job'])){
$req_fields = array('location','contractor','length', 'groundc' );
validate_fields($req_fields);
if(empty($errors)){
$j_location = remove_junk($db->escape($_POST['location'])); //checked
$j_startdate = remove_junk($db->escape($_POST['startdate'])); //checked
$n_startdate = date('Y-m-d', strtotime($j_startdate));
$j_address = remove_junk($db->escape($_POST['address'])); //checked
$j_contractor = remove_junk($db->escape($_POST['contractor'])); //checked
$j_contractor_contact = remove_junk($db->escape($_POST['contact'])); //checked
$j_length = remove_junk($db->escape($_POST['length'])); //checked
$j_groundc = remove_junk($db->escape($_POST['groundc'])); //checked
$j_jobstatus = remove_junk($db->escape($_POST['jobstatus'])); //checked
$j_driller = remove_junk($db->escape($_POST['driller'])); //checked
$j_boresize = remove_junk($db->escape($_POST['boresize']));
$j_pipesize = remove_junk($db->escape($_POST['pipesize']));
$j_belowinvert = remove_junk($db->escape($_POST['belowinvert']));
$j_grade = remove_junk($db->escape($_POST['grade']));
$j_centers = remove_junk($db->escape($_POST['centers']));
$j_centraliser = remove_junk($db->escape($_POST['centraliser']));
$j_notes = remove_junk($db->escape($_POST['notes']));
$date = make_date();
if(!isset($_POST['startdate']) || empty($_POST['startdate'])) {
$n_startdate = 'NULL';
} else {
$j_startdate = remove_junk($db->escape($_POST['startdate']));
$n_startdate = date('Y-m-d H:i:s', strtotime($j_startdate));
$n_startdate = sprintf("'%s'", $n_startdate);
}
$query = "INSERT INTO job (job_status_id, start_date, date_added, location, address, driller_id, contractor_id, bore_size,
head_id, cutters_id, pipe_size, length, ground_conditions, shield_size, depth, below_invert, grade, centers, hydrant,
hydrant_type, vacuum_hose, centralisers, notes)";
$query .= "VALUES ('{$j_jobstatus}', {$n_startdate}, '{$date}', '{$j_location}', '{$j_address}', '{$j_driller}', '{$j_contractor}', '{$j_boresize}', '{$j_pipesize}', '{$j_length}', '{$j_groundc}', '{$j_belowinvert}', '{$j_centers}', '{$j_centraliser}', '{$j_notes}')";
if($db->query($query)){
$session->msg('s',"Job added ");
redirect('add_job.php', false);
} else {
$session->msg('d',' Sorry failed to added!');
redirect('jobs.php', false);
}
} else{
$session->msg("d", $errors);
redirect('add_job.php',false);
}
} elseif(isset($_POST['add_cont'])){
$req_fields = array('n_contractor_name');
validate_fields($req_fields);
if(empty($errors)){
$name = remove_junk($db->escape($_POST['n_contractor_name']));
$query = "INSERT INTO contractor (";
$query .="Name";
$query .=") VALUES (";
$query .=" '{$name}'";
$query .=")";
if($db->query($query)){
//sucess
$session->msg('s',"New contractor has been creted! ");
redirect('add_job.php', false);
} else {
//failed
$session->msg('d',' Sorry failed to add contractor!');
redirect('add_job.php', false);
}
} else {
$session->msg("d", $errors);
redirect('add_job.php',false);
}
} elseif(isset($_POST['add_new_contact'])){
$req_fields = array('n_contractor_contact_name', 'n_contractor_contact_number', 'n_contractor_contact_id');
validate_fields($req_fields);
if(empty($errors)){
$contact_name = remove_junk($db->escape($_POST['n_contractor_contact_name']));
$contact_number = remove_junk($db->escape($_POST['n_contractor_contact_number']));
$contact_id = remove_junk($db->escape($_POST['n_contractor_contact_id']));
$query = "INSERT INTO contractor_contact (Name, Number, contractor_id)";
$query .="VALUES ('{$contact_name}','{$contact_number}','{$contact_id}')";
if($db->query($query)){
//sucess
$session->msg('s',"New contractor has been creted! ");
redirect('add_job.php', false);
} else {
//failed
$session->msg('d',' Sorry failed to add contractor!');
redirect('add_job.php', false);
}
} else {
$session->msg("d", $errors);
redirect('add_job.php',false);
}
}
?>
<?php include_once('layouts/header.php'); ?>
<div class="row">
<div class="col-md-12">
<?php echo display_msg($msg); ?>
</div>
</div>
<form method="post" action="add_job.php" class="clearfix">
<!-- Buttons At bottom -->
<div class="row" id="addbuttons">
<div class="col-md-12 col-md-offset-1">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<strong>
<span class="glyphicon glyphicon-th"></span>
<span></span>
</strong>
</div>
<div class="row justify-content-center">
<div class="col-md-2">
<button type="button" name="goback" onclick="goBack()" class="btn btn-danger">Back</button>
<button type="submit" name="add_job" class="btn btn-success">Add job</button>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal add new contractor -->
<div id="addnewconmodal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Add new contractor</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form method="post" id="insert_new_contractor">
<input type="hidden" value="add" name="action" id="action">
<div class="col-md-5">
<div class="form-group">
<label for="form_n_contractor_name">Contractor's name</label>
<input id="form_n_contractor_name" type="text" name="n_contractor_name" class="form-control" placeholder="Contractor's name">
<div class="help-block with-errors"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary add_cont" id="add_cont" name="add_cont">Save</button>
</div>
</div>
</div>
</div>
<!-- Modal add new contractor -->
<!-- Modal add new contractor contact -->
<div id="addnewcontactmodal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Add new contact</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form method="post" id="insert_new_contractor_contact">
<input type="hidden" value="add" name="action" id="action">
<div class="col-md-5">
<div class="form-group">
<label for="form_n_contractor_contact_id">Contractor ID</label>
<input id="form_n_contractor_contact_id" type="hidden number" name="n_contractor_contact_id" class="form-control" value="<?php echo $con['ID'] ?>">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label for="form_n_contractor_contact_name">Contractor's name</label>
<input id="form_n_contractor_contact_name" type="text" name="n_contractor_contact_name" class="form-control" placeholder="Contractor's name">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label for="form_n_contractor_contact_number">Contractor's number</label>
<input id="form_n_contractor_contact_number" type="tel" name="n_contractor_contact_number" class="form-control" placeholder="Contractor's number">
<div class="help-block with-errors"></div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary add_new_contact" id="add_new_contact" name="add_new_contact">Save</button>
</div>
</div>
</div>
</div>
<!-- Modal add new contractor contact -->
</form>
<script>
//Add new contractor
$("#contractor").change(function () {
if ($(this).val() === 'addnewcon') {
$('#addnewconmodal').modal({show: true});
} else if ($(this).val() !== 'addnewcon') {
$('#addnewconmodal').modal({show: false});
}
});
//Add new contractor contact
$("#contact").change(function () {
if ($(this).val() === 'addnewcontact') {
$('#addnewcontactmodal').modal({show: true});
} else if ($(this).val() !== 'addnewcontact') {
$('#addnewcontactmodal').modal({show: false});
}
});
//Ajax call to get selected contractor
$("#contractor").on('change',function() {
var conselected = $(this).val();
if(conselected != "") {
$.ajax({
url:"ajax.php",
data:{consel_id:conselected},
type:'POST',
success:function(response) {
console.log(response);
var resp = $.trim(response);
$("#contact").html(resp);
console.log(resp);
$("#contact").selectpicker('refresh');
}
});
} else {
$("#contact").html("<option value=''>------- Select --------</option>");
}
});
//Ajax add new contractor
$(".cont_add").click(function() {
$(".selectpicker").selectpicker('refresh');
});
</script>
I'm not familiar with php, so I just write them in test.html and open it with Firefox. If I click on the "Add job" button or the first "Save" button, the page jumps to add_job.php. However, the action of the first "Save" button is not specified. As mentioned in Can you nest html forms?, the modals shall be moved outside the main form.
Unfortunately, it's not the end. After moving modals outside the main form, add action attributes for the other two forms, for example, insert_new_contractor.php and insert_new_contractor_contact.php. Now, you'll find that even the first "Save" button doesn't respond to a click, as a click on "Save" button won't lead to a new page. It seems that a submit button can be outside of a form, but here, which form to be submitted seems unclear (lack a reference on how browser works at this time ... ). Try to move the submit button inside the corresponding form. Surround a modal with the related form tag, all three buttons work. Setting onclick attribution for the "Save" buttons also works.

Dismiss modal view issues

I want to create a button action create with disable/enable button then close model view:
// button: type="submit" class="btn btn-primary" data-dismiss="modal" ng-disabled="!newSong.name" ng-click="saveSong()" >Create
--> Issue: when ng-click done --> view modal did not close
The reason why your code was not working is because of $scope.newSong = {};
in this code:
$scope.saveSong = function () {
$scope.songs.push($scope.newSong);
$scope.newSong = {};
};
Whenever you are trying to submit the form $scope.newSong = {} is making it invalid.
HTML CODE
<div ng-app="myApp", ng-controller ="myController">
<div ng-repeat="id in songs">
<ul>
<li> Name song: {{id.name}} </li>
<li> Name artist: {{id.artist}} </li>
</ul>
</div>
<div class="col-lg-1"> <button type="button" class="btn btn-info glyphicon glyphicon-plus" data-toggle="modal" data-target="#myModal" ng-click="clear()"> Add New </button> </div>
<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"> Create New Song</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" role ="form" name="formName" novalidate>
<div class="form-group" >
<label class="control-label col-sm-2"> Name* </label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name" ng-model="newSong.name" required/>
<div class="custom-error" ng-show="formName.name.$dirty && formName.name.$invalid">
<p ng-show="formName.name.$invalid && !formName.name.$pristine" class="help-block"> name is required.</p>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Artist</label>
<div class="col-sm-10">
<input type="text" class="form-control"ng-model="newSong.artist">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" data-dismiss="modal" ng-disabled="!newSong.name" ng-click="saveSong()" >Create</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
<br/><br/>
Angular CODE
var myApp = angular.module('myApp',[]);
myApp.controller('myController', function($scope){
$scope.songs = [
{
"name": "Everybody",
"artist": "Backstreet Boys.",
"id": 1
},
{
"name": "Feel Like Makin' Love",
"artist": "Bad Company.",
"id": 2
},
{
"name": "Sister of Pearl",
"artist": "Baio.",
"id": 3
}];
$scope.newSong = {};
/* callback ng-click create */
$scope.saveSong = function () {
$scope.songs.push($scope.newSong);
// $scope.newSong = {};
};
$scope.clear = function(){
$scope.newSong = {};
$scope.$setPristine(true);
}
});
WORKING LINK
Hope that works :)

How to pass Bootstrap Modal form data to Spring Boot controller

If I have a pop up, opened using Bootstrap Modal, and in this i have a form where i can put data, how can I pass this data to a Spring controller to update my sql DB?
I had the same issue and i find the solution using ajax, because every time you submit the values your page is refreshed and the modal is closed.
Here is my modal form:
<!-- Modal -->
<div class="modal fade" id="loginModal">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:35px 50px;">
<button type="button" data-dismiss="modal" class="close">×</button>
<h4><span class="glyphicon glyphicon-lock"></span> Iniciar sesion</h4>
</div>
<div class="modal-body" style="padding:40px 50px;">
<form id="login-form" action="${contextPath}/j_spring_security_check" method="POST" name="loginForm">
<div class="form-group">
<label for="usrname" ><span class="glyphicon glyphicon-user"></span> Correo</label>
<input type="text" class="form-control" name="correo" id="correo">
</div>
<div class="form-group">
<label for="psw"><span class="glyphicon glyphicon-eye-open"></span> Contraseña</label>
<input type="password" class="form-control" name="password">
</div>
<div class="checkbox">
<label><input type="checkbox" value="" checked>Remember me</label>
</div>
<div class="form-group">
<button type="submit" id="loginBtn" class="btn btn-success btn-block"><span class="glyphicon glyphicon-off"></span> Iniciar sesion </button>
</div>
</form>
<hr/>
<div id="errorMsg">${error}</div>
</div>
<div class="modal-footer">
<p>¿No tenes cuenta? Registrate</p>
<p>Olvidates tu contraseña?</p>
</div>
</div>
</div>
</div>
Ajax call:
$('#login-form').on('submit', function(event){
var self = this;
var form = $(this);
var errorMsg = $('#errorMsg');
if (form.data('requestRunning')) {
return;
}
form.data('requestRunning', true);
event.preventDefault();
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
data: form.serialize(),
success: function(result){
console.log(result.login);
if(result.login == undefined){
self.submit();
}else{
errorMsg.text(result.login.FAILURE).addClass("alert alert-danger");
agitar('#errorMsg');
}
},
complete: function (e) {
form.data('requestRunning', false);
}
});
});
Here i'm using spring-security to validate my user login, but if you only want to update your DB, in the form action you can put the url that you want to use to call your controller i.e: "/updateDB" and declare a controller i.e:
#RequestMapping("/updateDB", method=RequestMethod.POST)
public String updateDB(#ModelAttribute("dataToUpdate")DataToUpdate dataToUpdate){
//do whathever you want
}
Hope this help!

$scope.Form.field.$dirty = true is not working

I want to set dirty flag for edited cells in the table. When I click the save button I need to check the edited field is dirty is true or not. Because X-editable is updating entire table cell values both edited and unedited cell values.I need to check what are all the edited fields using dirty flag and if that field is dirty then that fields only i have to save in to mongodb.
for that I used this line to set the $dirty:
$scope.Form.username.$dirty = true; // this throwing TypeError:$dirty is undefined error
$scope.Form.$dirty = true;
//it is working
html code:
<form name="profileform">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog" id="myModal">
<!-- Modal content-->
<div class="modal-content" style="margin-top:135px">
<div class="modal-header">
<h4 class="modal-title pull-left"> Add New Role</h4>
<button type="button" class="close pull-right"
data-dismiss="modal" aria-hidden="true">
x
</button>
</div>
<div class="modal-body">
<div class="row" style="margin-bottom:1%">
<div class="col-xs-3">
<h6><strong>Role<span style="color:green;">*</span></strong></h6>
</div>
<div class="col-xs-9">
<input type="text" name="Name" class="form-control" ng-model="Role.RoleName" />
<!--<span class="error" ng-show="profileform.RoleName.$invalid ">Please enter a Role Name</span>-->
</div>
</div>
<div class="row" style="margin-bottom:1%">
<div class="col-xs-3">
<h6><strong> Description</strong></h6>
</div>
<div class="col-xs-9">
<textarea name="Description" style="width: 100%; max-height: 200px; max-width: 100%;"
ng-model="Role.Description" maxlength="255"></textarea>
</div>
</div>
<div class="row" style="margin-bottom:1%">
<div class="col-xs-3">
<h6><strong>IsActive?</strong></h6>
</div>
<div class="col-xs-9">
<input type="checkbox" name="IsActive" class="form-control" ng-model="Role.IsActive" style="width:20px;" />
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="AddRole()" ng-disabled="profileform.$invalid" data-dismiss="modal">Save</button>
<button class="btn btn-primary" data-dismiss="modal" ng-click="deselect()">Cancel</button>
</div>
</div>
</div>
</div>
</form>
controller code:
$scope.AddRole = function () {
debugger;
console.log($scope.profileform.RoleName.$dirty);
console.log($scope.profileform.Description.$dirty);
$http.post('/AddNewRole', $scope.Role).then(function (response) {
//console.log(response);
$notify.success('Success', 'record inserted Successfully');
refresh();
});
};
Because $dirty is not defined in username object,or username is itself not defined, To fix the issue you need to first define the username into the Form object also please make sue Form is also into the $scope.
$scope.Form.username = {};
Then you can add $dirty into the username object like below
$scope.Form.username['$dirty'] = true
$dirty : It will be TRUE, if the user has already interacted with the form or if the field has been modified.
Try this :
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
$scope.FormSubmit = function () {
console.log($scope.form.username.$dirty);
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="form" novalidate class="simple-form">Name:
<input type="text" name="username" ng-model="user.name" required />
<br />
<input type="submit" ng-click="FormSubmit()" value="Save" />
</form>
</div>
Try with names not ng-model.
angular.module('exApp',[]).controller('ctrl', function($scope){
$scope.name="Mani"; $scope.emails = "mani#gmail.com";
$scope.sub = function(){
console.log($scope.frm.yourname.$dirty, $scope.frm.mail.$dirty);
$scope.frm.yourname.$dirty = true;
console.log("I was set '#true': " + $scope.frm.yourname.$dirty);
}
$scope.AddRole = function(){
console.log("Role name dirty check: "+ $scope.profileform.Name.$dirty);
console.log("Description dirty check: "+ $scope.profileform.Description.$dirty);
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.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" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="exApp" ng-controller="ctrl">
<form name="frm" novalidate ng-submit="sub()">
<input type="text" name="yourname" ng-model="name">
<input type="email" name="mail" ng-model="emails" required>
<input type="submit">
</form>
<br><br>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Add role
</button>
<form name="profileform">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog" id="myModal">
<!-- Modal content-->
<div class="modal-content" style="margin-top:135px">
<div class="modal-header">
<h4 class="modal-title pull-left"> Add New Role</h4>
<button type="button" class="close pull-right"
data-dismiss="modal" aria-hidden="true">
x
</button>
</div>
<div class="modal-body">
<div class="row" style="margin-bottom:1%">
<div class="col-xs-3">
<h6><strong>Role<span style="color:green;">*</span></strong></h6>
</div>
<div class="col-xs-9">
<input type="text" name="Name" class="form-control" ng-model="Role.RoleName" />
<!--<span class="error" ng-show="profileform.RoleName.$invalid ">Please enter a Role Name</span>-->
</div>
</div>
<div class="row" style="margin-bottom:1%">
<div class="col-xs-3">
<h6><strong> Description</strong></h6>
</div>
<div class="col-xs-9">
<textarea name="Description" style="width: 100%; max-height: 200px; max-width: 100%;"
ng-model="Role.Description" maxlength="255"></textarea>
</div>
</div>
<div class="row" style="margin-bottom:1%">
<div class="col-xs-3">
<h6><strong>IsActive?</strong></h6>
</div>
<div class="col-xs-9">
<input type="checkbox" name="IsActive" class="form-control" ng-model="Role.IsActive" style="width:20px;" />
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="AddRole()" ng-disabled="profileform.$invalid" data-dismiss="modal">Save</button>
<button class="btn btn-primary" data-dismiss="modal" ng-click="deselect()">Cancel</button>
</div>
</div>
</div>
</div>
</form>
</body>

Create Post and push to firebase with AngularJS not working

I'm new to AngularJS, and I'm trying to figure out how to get a create post form in a modal to work, and push a post to firebase. I'm pulling my hair out.
Originally, "create post" was a link in the navbar that took you to a separate page (addPost.html) with a form on it.
I wanted to move the Create Post form to a bootstrap modal on the same page (welcome.html).
There is an edit form in a modal, and it works fine when editing an already created post. The delete post also works as well.
I can't figure out what I am doing wrong.
This is my welcome.html:
<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="icon" href="http://getbootstrap.com/favicon.ico">
<title>AngularJS & Firebase Web App</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="blog.css" rel="stylesheet">
</head>
<body ng-controller="WelcomeCtrl">
<div class="blog-masthead">
<div class="container">
<nav class="blog-nav">
<a class="blog-nav-item active" href="#/welcome">Home</a>
<a class="blog-nav-item " href="#/addPost">Add Post</a>
</nav>
</div>
</div>
<div class="container">
<div class="page-header">
<h1>AngularJS & Firebase App</h1>
</div>
<p class="lead">Welcome home <b>{{username}}</b> !!</p>
<!-- BUTTON I CREATED TO TRIGGER THE CREATE POST MODAL -->
<p><button class="btn btn-xs btn-info" data-toggle="modal" data-target="#createModal">CREATE</button></p>
<!-- list of articles -->
<div class="list-group" ng-repeat="article in articles">
<a href="#" onclick="return false;" class="list-group-item active">
<h4 class="list-group-item-heading">{{article.title}}</h4>
<p class="list-group-item-text">{{article.post}}</p>
<span class="pull-right">
<button class="btn btn-xs btn-info" ng-click="editPost(article.$id)" data-target="#editModal">EDIT</button>
<button class="btn btn-xs btn-warning" ng-click="confirmDelete(article.$id)" data-target="#deleteModal" >DELETE</button>
</span>
</a>
</div>
</div>
<!-- footer -->
<footer class="footer">
<div class="container">
<p class="text-muted"></p>
</div>
</footer>
<!-- create modal -->
<div class="modal fade" id="createModal" role="dialog" aria-labelledby="createModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="editModalLabel">Create Post</h4>
</div>
<div class="modal-body">
<form ng-submit="AddPost()">
<div class="form-group">
<label for="recipient-name" class="control-label">Title:</label>
<input type="text" ng-model="article.title" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label for="message-text" class="control-label">Post:</label>
<textarea ng-model="article.post" class="form-control" id="message-text"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input id="singlebutton" ng-disabled="!article.title || !article.post" name="singlebutton" class="btn btn-primary" type="submit" value="Publish" />
</form>
</div>
</div>
</div>
</div>
<!-- edit modal -->
<div class="modal fade" id="editModal" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="editModalLabel">Update Post</h4>
</div>
<div class="modal-body">
<form role="form">
<div class="form-group">
<label for="recipient-name" class="control-label">Title:</label>
<input type="text" ng-model="postToUpdate.title" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label for="message-text" class="control-label">Post:</label>
<textarea ng-model="postToUpdate.post" class="form-control" id="message-text"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" ng-click="update()">Publish</button>
</div>
</div>
</div>
</div>
<!-- delete modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" style="text-align:center;">
<h4 class="modal-title" style="color:red;" id="deleteModalLabel">You are going to Delete this post forever !!</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" ng-click="deletePost()">Delete</button>
</div>
</div>
</div>
</div>
</body>
</html>
This is my welcome.js:
'use strict';
angular.module('myApp.welcome', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/welcome', {
templateUrl: 'welcome/welcome.html',
controller: 'WelcomeCtrl'
});
}])
.controller('WelcomeCtrl', ['$scope','$firebase','CommonProp', function($scope,$firebase,CommonProp) {
$scope.username = CommonProp.getUser();
var firebaseObj = new Firebase("https://yyear.firebaseio.com/Articles");
var sync = $firebase(firebaseObj);
$scope.articles = sync.$asArray();
$scope.editPost = function(id) {
var firebaseObj = new Firebase("https://yyear.firebaseio.com/Articles/" + id);
var syn = $firebase(firebaseObj);
$scope.postToUpdate = syn.$asObject();
$('#editModal').modal(); // triggers the modal pop up
};
$scope.update = function() {
var fb = new Firebase("https://yyear.firebaseio.com/Articles/" + $scope.postToUpdate.$id);
var article = $firebase(fb);
article.$update({
title: $scope.postToUpdate.title,
post: $scope.postToUpdate.post,
emailId: $scope.postToUpdate.emailId
}).then(function(ref) {
$('#editModal').modal('hide');
}, function(error) {
console.log("Error:", error);
});
};
$scope.confirmDelete = function(id) {
var fb = new Firebase("https://yyear.firebaseio.com/Articles/" + id);
var article = $firebase(fb);
$scope.postToDelete = article.$asObject();
$('#deleteModal').modal();
};
$scope.deletePost = function() {
var fb = new Firebase("https://yyear.firebaseio.com/Articles/" + $scope.postToDelete.$id);
var article = $firebase(fb);
article.$remove().then(function(ref) {
$('#deleteModal').modal('hide');
}, function(error) {
console.log("Error:", error);
});
};
$scope.AddPost = function(){
console.log("This was called.");
var title = $scope.article.title;
var post = $scope.article.post;
var firebaseObj = new Firebase("https://yyear.firebaseio.com/Articles");
var fb = $firebase(firebaseObj);
fb.$push({ title: title,post: post,emailId: CommonProp.getUser() }).then(function(ref) {
console.log(ref);
//$location.path('/welcome');
}).then(function(ref) {
$('#editModal').modal('hide');
}, function(error) {
console.log("Error:", error);
});
};
}]);
The original Create Post form in addPost.html that works looks like this:
<body ng-controller="AddPostCtrl">
<div class="blog-masthead">
<div class="container">
<nav class="blog-nav">
<a class="blog-nav-item " href="#/welcome">Home</a>
<a class="blog-nav-item active" href="#/addPost">Add Post</a>
</nav>
</div>
</div>
<div class="container" >
<form class="form-horizontal" ng-submit="AddPost()">
<fieldset>
<legend>Create Post</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="txtTitle">Title</label>
<div class="col-md-4">
<input id="txtTitle" name="txtTitle" ng-model="article.title" type="text" placeholder="placeholder" class="form-control input-md">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="txtPost">Post</label>
<div class="col-md-4">
<textarea class="form-control" id="txtPost" ng-model="article.post" name="txtPost" ></textarea>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton"></label>
<div class="col-md-4">
<input id="singlebutton" ng-disabled="!article.title || !article.post" name="singlebutton" class="btn btn-primary" type="submit" value="Publish" />
</div>
</div>
</fieldset>
</form>
</div><!-- /.container -->
The addPost.js file looks like this.
'use strict';
angular.module('myApp.addPost', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/addPost', {
templateUrl: 'addPost/addPost.html',
controller: 'AddPostCtrl'
});
}])
.controller('AddPostCtrl', ['$scope','$firebase','$location','CommonProp',function($scope,$firebase,$location,CommonProp) {
$scope.AddPost = function(){
var title = $scope.article.title;
var post = $scope.article.post;
var firebaseObj = new Firebase("https://yyear.firebaseio.com/Articles");
var fb = $firebase(firebaseObj);
fb.$push({ title: title,post: post,emailId: CommonProp.getUser() }).then(function(ref) {
console.log(ref);
$location.path('/welcome');
}, function(error) {
console.log("Error:", error);
});
}
}]);
I assumed that if I copied the the addPost function from addPost.js to the welcome.js file and then duplicated the edit form in welcome.html and modified it so it was similar to the Create Post form in addPost.html it would work.
Obviously it doesn't, but I don't know what I am doing wrong.
The modal pops up but the publish button doesn't do anything
I figured it out. I had my closing form tag in the wrong spot first of all in my create post modal.
The Create Post modal should be like this:
<div class="modal fade" id="createModal" role="dialog" aria-labelledby="createModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form ng-submit="AddPost()">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="editModalLabel">Create Post</h4>
</div>
<div class="modal-body">
<!-- Text input-->
<div class="form-group">
<label class="control-label" for="txtTitle">Title</label>
<input id="txtTitle" name="txtTitle" ng-model="article.title" type="text" placeholder="placeholder" class="form-control input-md">
</div>
<!-- Textarea -->
<div class="form-group">
<label class="control-label" for="txtPost">Post</label>
<textarea class="form-control" id="txtPost" ng-model="article.post" name="txtPost" ></textarea>
</div>
<!-- Button -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input id="singlebutton" ng-disabled="!article.title || !article.post" name="singlebutton" class="btn btn-primary" type="submit" value="Publish" />
</div>
</form>
</div>
</div>
</div>
My addPost function in welcome.js should be like this:
$scope.AddPost = function(){
console.log("This was called.");
var title = $scope.article.title;
var post = $scope.article.post;
var firebaseObj = new Firebase("https://yyear.firebaseio.com/Articles");
var fb = $firebase(firebaseObj);
fb.$push({ title: title,post: post,emailId: CommonProp.getUser() }).then(function(ref) {
console.log(ref);
//$location.path('/welcome');
}).then(function(ref) {
$('#createModal').modal('hide');
}, function(error) {
console.log("Error:", error);
});
};