I have problem with my modal, I have modal and inside my modal I have selecoption factory which my select using ajax jQuery like this
$('#fFactory').change(function(e) {
$.ajax({
type: "POST",
url: host + "budget/FFactory",
data: dataString,
cache: false,
success: function(data) {
console.log($("#fFactory").html(data));
}
});
});
But my problem is, my select option wont work inside modal. How do I trigger my select option inside modal??
My html :
<?php
$json = array();
if($data['title']=='additem')
{
$json['title'] = 'Add Item';
}
else
{
$json['title'] = 'Add Item';
}
$json['body'] = '<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="exampleInputEmail1">
Factory
</label>
<select id="fFactory" class="form-control input-sm">
</select>
</div>
<div class="form-group">
<label for="exampleInputPassword1">
Password
</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
</div>
</div>';
$json['footer'] = '<button type="button" class="btn btn-primary btn-o modal-close pull-left" data-dismiss="modal">
close
</button>';
// var_dump($json);
echo json_encode($json);
?>
I'm using json. On jQuery when active modal
$('#addbudget').click(function(){
var code = "";
var modal = $('.bs-modal-lg');
var modalData = jQuery.parseJSON(ajaxPOST(code,'budget/form/additem',null,true));
modal.find('.modal-title').html(modalData.title);
modal.find('.modal-body').html(modalData.body);
modal.find('.modal-footer').html(modalData.footer);
modal.modal('show');
});
UPDATE :
How silly I am, I was wrong on json, I forgot have to add function init: on jQuery now it works. I'm so sorry about silly I am. Thanks for all who helping me again :)
Related
I've got a number of inputs in a form, created dynamically, and I'm trying to send them to the controller as an array using javascript.
Originally it was only one value and it was part of the Entity I pass in the model. Then, as it can be more than one, I added a Transient field to the entity as a List and also created another class in java with just a List. However, I still don't know how to add these values from javascript to the th:object in the form.
<form id="selectform" th:object="${systemIdListForm}" th:action="#{/myController}" method="get">
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function () {
$("#addMore").click(function() {
var html = '<div class="form-group col-md-1"><input class="form-control" name="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/></div>';
$('#fields').append(html);
});
$("#selectform").submit(function(){
var values = $(this).serialize();
});
});
/*]]>*/
</script>
At the moment I can see that the variable values have the right information but nothing is sent to the controller. I realize that the formatting of these values is probably not want I need but I'm not sure what to do.
Any help is much appreciated
What data type have you used in Model ?
Make sure you have taken String [] for that field.
If not taken String [] then use that and let me know whether it works or not.
Also you can take help of below code.It is for your case only.
$("#selectform").submit(function (event) {
// form redirect stop
event.preventDefault();
var status = jbf.form.validate('#selectform');
if (!status) {
return;
}
// get form data
var data = {};
data["enrollmentNumber"] = $("#enrollmentNumber").val();
data["systemIdInput"] = jQuery("#selectform input[name=systemIdInput]").val();
var url = "/yourURL";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
var message = response.message;
//success notification
if(response.success === true){
alert(message);
}else{
error(message);
}
},
error: function (e) {
console.log("ERROR: ", e);
error("Add failed");
}
});
});
I managed to get the list of values from all the inputs in the form using a hidden input. I added a transient field in my entity (systemIds) where I've got all the values.
<form id="selectform" th:object="${myEntiry}" th:action="#{/crops/singlecroplabeloffinsp/list/1}" method="get">
<input class="form-control" id="systemIdList" th:field="*{systemIds}" type="hidden"/>
<div class="box-body">
<label>System Id:</label>
<div id="fields">
<div class="form-group col-md-1">
<input class="form-control" name ="systemIdInput" type="text" style="width: 90%;" maxlength="8" onkeypress="return isNumber(event)"/>
</div>
</div>
<a id="addMore" href="#"><i class="fa fa-plus"></i><span>Add</span></a>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Select</button>
</div>
</form>
...
$("#selectform").submit(function(){
//get all the system ids
var x = document.getElementsByName("systemIdInput");
var systemIds = [];
for (i = 0; i < x.length; i++ ) {
if (x[i].type ='text') {
systemIds.push(x[i].value);
}
}
$("#systemIdList").val(systemIds);
this.submit();
});
Added to the entity with getter & setter:
#Transient
private List<Integer> systemIds;
Aim: Continue to display any form validation errors through json callback
Problem: When I submit on the form with invalid input it shows an error message in a div element. If all inputs are valid it will process the ajax request and show a success message in a div element. After which, the form resets but the modal remain open. When I try to again validate the input in doesn't show any error message. When I try to test the valid input still the same no message shown.
In short: Ajax success function not working on the second time.
Here's my code:
Bootstrap Modal (where my form inputs placed)
<div class="modal fade" id='frmModal'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class='close' data-dismiss='modal'>×</button>
<h4 class='title'>Add new data</h4>
</div>
<div class="modal-body">
<?php echo form_open('Employee/save',array('id'=>'frm', 'class'=>'form-horizontal')); ?>
<div id="message"></div>
<div class="form-group">
<label for='fname' class='col-md-3 control-label'>First Name:</label>
<div class="col-md-9">
<input type="text" name="fname" id='fname' class='form-control' placeholder='First Name...'>
</div>
</div>
<div class='form-group'>
<label for='lname' class='col-md-3 control-label'>Last Name:</label>
<div class="col-md-9">
<input type="text" name="lname" id='lname' class='form-control' placeholder='Last Name...'>
</div>
</div>
<div class='form-group'>
<label for='age' class='col-md-3 control-label'>Age:</label>
<div class="col-md-9">
<input type="text" name="age" id='age' class='form-control' placeholder='Age...'>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary action" type='submit'><i class='glyphicon glyphicon-floppy-disk'></i> Save Data</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
Jquery Code:
$(document).on('submit','#frm',function(e){
e.preventDefault();
var form = $('#frm');
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: 'json',
encode: true,
data: form.serialize(),
success: function(data) {
if (!data.success) {
if (data.errors) {
$('#message').html(data.errors).addClass('alert alert-danger');
}
} else {
reloadData();
$('#message').html("<span class='glyphicon glyphicon-ok'></span> " + data.message).removeClass('alert alert-danger').addClass('alert alert-success');
setTimeout(function() {
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
$('#frm')[0].reset();
}
}
});
});
CodeIgniter Controller:
$this->form_validation->set_rules('fname','First Name', 'required|trim');
$this->form_validation->set_rules('lname','Last Name', 'trim|required');
$this->form_validation->set_rules('age','Age', 'trim|numeric|required');
if($this->form_validation->run()===FALSE)
{
$info['success'] = false;
$info['errors'] = validation_errors();
}
else
{
$info['success'] = true;
$data = array(
"firstname" => $this->input->post('fname'),
"lastname" => $this->input->post('lname'),
"age" => $this->input->post('age'),
);
$this->Employee_model->save('ci_table', $data);
$info['message'] = 'Successfully saved data';
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
I think I understand... The form still works but the messages do not appear? If so then try the below...
You are removing the #message element instead of clearing it... try:
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).empty();
This way you are emptying the #message element instead of removing it completely..
Been struggling with this for about few hours. I'm attempting to have a modal drop down (Twitter bootstrap modal) that contains a form to choose a category of user. This is built in CodeIgniter. But when i try to save form's value using AJAX, the SUCCESS function won't run without alert(). I'm sorry for my bad grammar, i hope you can understand what i mean.
i need for your help...
view (kasir_halaman.php):
<div id="editModal" class="modal fade" role="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Ubah Kasir</h3>
</div>
<div class="modal-body">
<form action="#" id="editform" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label> <span class="error" id="report1"></span>
<input type="text" id="editnama" name="nama" class="form-control" maxlength="100" required>
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="editemail" name="email" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label>Kategori</label>
<select class="form-control" name="kategoripetugas" id="editkategori" required>
<option value=""> -- Pilih Kategori -- </option>
<option value="1">Admin</option>
<option value="2">Kasir</option>
</select>
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Simpan</button>
</form>
</div>
</div>
</div>
</div>
controller (kasir.php):
public function updatePetugas($id)
{
$nama_petugas = $this->input->post('nama');
$email_petugas = $this->input->post('email');
$kategori_petugas = $this->input->post('kategoripetugas');
$data = array('nama'=>$nama_petugas, 'email'=>$email_petugas, 'kategori'=>$kategori_petugas);
$update = $this->Crud->update(array('idpetugas'=>$id), 'petugas', $data);
if($update){
echo 1;
}else{
echo 2;
}
}
javascript (petugas.js) :
$(document).ready(function(){
var check1=0; var id;
$("#nama").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'kasir/cekData/kasir/nama/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*nama petugas sudah terpakai");
check1=0;
}
}
});
});
$(".edit").click(function(){
id = $(this).attr('id');
$.ajax({
url:'kasir/getData/'+id,
data:{send:true},
success:function(data){
$("#editnama").val(data['nama']);
$("#editemail").val(data['email']);
$("#editkategori").val(data['kategori']);
}
});
});
$("#editform").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:'kasir/updatePetugas/'+id,
data:formData,
type:'POST',
contentType: false,
processData: false,
success:function(data){
if(data==1){
$("#editModal").hide();
window.location.reload(true);
}else if(data==2){
alert('gagal');
}
}
});
alert("success!"); // if i remove this alert, the success function won't run or executed
});
});
you can solve this a few ways, what is actually happening is that you are submitting the data via ajax as well as submitting the form itself.
using e or the event
$("#editform").submit(function(e){
e.preventDefault();
or by returning false on submit
});
//alert("success!"); we can comment this out because it will work now without the alert holding the page
return false;
});
in either case you can remove your alert.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I had created website that has modal through which i can submit form using ajax. I am not very good with jquery and javascript so i need some help cause things are not working so well.
This is my form code in modal body. Here everything works fine as i can see.
<form action="inc/queries.php" method="post" class="insert-movie">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="InputTitle" id="InputTitle" placeholder="Enter title">
</div>
<div class="form-group">
<label for="year">Year</label>
<input type="date" class="form-control" name="InputYear" id="InputYear" placeholder="Year">
</div>
<div class="form-group">
<label for="year">Duration</label>
<input type="time" class="form-control" name="InputDuration" id="InputDuration" placeholder="Duration">
</div>
<div class="form-group">
<label for="year">Gender</label></br>
<select name="InputGender">
<?php
$pdo = connect();
// display the list of all members in table view
$sql = "SELECT * FROM zanr";
$query = $pdo->prepare($sql);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
?>
echo'
<option name="InputGender" value="<?php echo $rs['id'] ?>"><?php echo $rs['naziv'] ?> </option>'
<?php } ?>
echo'
</select>
</div>
<div class="form-group">
<label for="year">Description</label>
<textarea class="form-control" name="InputDescription" placeholder="Description" rows="3"></textarea>
</div>
<div class="form-group">
<label for="image">Image upload</label>
<input type="file" id="InputImage">
<p class="help-block">Select image of movie.</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success" value="Submit">
</div>
</form>
This is javascript code:
$('.insert-movie').on('submit', function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
and last, code that manipulates given variables and inserts into database.
<?php
include 'config.php';
if(isset($_POST['InputTitle'], $_POST['InputYear'], $_POST['InputDuration'], $_POST['InputDescription'], $_POST['InputGender'])) {
$pdo = connect();
$InputTitle = $_POST['InputTitle'];
$InputYear = $_POST['InputYear'];
$InputDuration = $_POST['InputDuration'];
$InputDescription = $_POST['InputDescription'];
$InputGender = $_POST['InputGender'];
$sql = $pdo->prepare("INSERT INTO filmovi(naslov,godina,trajanje,opis,id_zanr) VALUES(:field1,:field2,:field3,:field4,:field5)");
$sql->execute(array(':field1' => $InputTitle, ':field2' => $InputYear, ':field3' => $InputDuration, ':field4' => $InputDescription, ':field5' => $InputGender));
$affected_rows = $sql->rowCount();
}
What is the problem, problem is when i open modal and enter data. I press submit and it takes me on query.php page witch is empty, in another words it isn't working properly. Data from form are stored in DB but something is wrong and i don't know what.
You have type: type, which is an error.
Change to:
$('.insert-movie').on('submit', function(e) {
e.preventDefault();
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: 'POST',
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
You need to prevent the default action of the submit event -
$('.insert-movie').on('submit', function(event) { // pass the event to the function
event.preventDefault(); // prevents the default action, keeping the browser on the same page
I have a JSON returned data from a pho function that looks as follows:
[{"id":"15","activity_type":"call","activity_title":"Call to check "}]
Here the script that initiates the request (actvitiy.js)(Edited)
$(document).on("click", ".view_contact_activity", function () {
var this_activity_id = $(this).closest('.feeds').find('#this_activity_id').val();
$('#view-contact-activity').modal('show');
$.ajax({
url: '../includes/functions/contact-functions.php',
data: {view_activity_id:this_activity_id},
dataType:'json',
Success: function(response){
$('#activity_id').val(response[0].id);
$('#activity_type').val(response[0].activity_type);
}
});
});
The modal where i need the values to show:
<div class="modal fade" id="view-contact-activity" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div class="portlet-body form">
<form class="form-horizontal" role="form" id="view-contact-activity-form" method="post">
<div class="form-group">
<label class="col-sm-3 control-label col-lg-3"> Activity Title</label>
<input type="text" name="activity_id" id="activity_id" value="">
<label class="col-sm-3 control-label col-lg-3"> Activity Type</label>
<input type="text" name="activity_type" id="activity_type" value="">
<div class="modal-footer">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" name="create-new-account" class="btn btn-danger" id="edit">Edit Activity</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
The modal shows but no data is passed into the modal. Any ideas what i might be doing wrong here.
EDIT: Adding PHP function that returns the JSON
function view_activity(){
global $connection;
$activity_id = $_POST['view_activity_id'];
$get = "SELECT * FROM contact_activities WHERE activity_id = '$activity_id' "
or die("Error: ".mysqli_error($connection));
$query = mysqli_query($connection, $get);
$activitiy_field = array();
while ($activity_array = mysqli_fetch_array($query)){
$activity = array(
'id' => $activity_array['activity_id'],
'activity_type' => $activity_array['activity_type'],
'activity_title'=>$activity_array['activity_title'],
'activity_details'=>$activity_array['activity_details'],
'activity_status'=>$activity_array['activity_status'],
'activity_details'=>$activity_array['activity_details'],
'activity_details'=>$activity_array['activity_details'],
);
$activitiy_field[] = $activity;
}
echo json_encode($activitiy_field);
}
if (isset($_POST['view_activity_id'])) {
view_activity();
}
Thank you.
Use .val() instead of .html().
$('#activity_id').val(response.id);
$('#activity_type').val(response.activity_type);
Modified: Your javascript should look like this:
$(document).on("click", ".view_contact_activity", function () {
var this_activity_id = $(this).closest('.feeds').find('#this_activity_id').val();
$('#view-contact-activity').modal('show');
$.ajax({
url: '../includes/functions/contact-functions.php',
data: {view_activity_id:this_activity_id},
dataType:'json',
Success: function(response){
$('#activity_id').val(response[0].id);
$('#activity_type').val(response[0].activity_type);
}
});
});
After digging on multiple sites. i found a similar question that could help.
$(document).on("click", ".view_contact_activity", function () {
var this_activity_id = $(this).closest('.feeds').find('.id #this_activity_id').val();
$('#view-contact-activity').modal('show')
$('#view-contact-activity').on('show.bs.modal', function() {
$modal = $(this);
$.ajax({
url: '../includes/functions/contact-functions.php',
data: {view_activity_id:this_activity_id},
dataType:'json',
success: function(response){
// Find the elements in the modal
$modal.find('#activity_id').val(response[0].id);
$modal.find('#activity_type').val(response[0].activity_type);
}
});
});
});