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.
Related
I fetched the id from the database and passed it to the modal, and then echo it on another page through ajax but the problem is that it keeps returning the same id
<?php if(mysqli_num_rows($select_invoice_query)>0) {
while($invoice_result = mysqli_fetch_assoc($select_invoice_query)) { ?>
<tr>
<td><i class="fa fa-envelope"></i></td>
</tr>
<?php }} ?>
Bootstrap Modal
<div id="send-invoice-modal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Send Invoice</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="email" id="invoice_to" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="text" id="invoice_subject" class="form-control" placeholder="Subject">
</div>
<div class="form-group">
<textarea class="form-control" id="invoice_message" rows="3" placeholder="Message"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" id="send_invoice_btn">Send</button>
<div class="error_message"></div>
</div>
</div>
</div>
</div>
JS
$('#send_invoice_btn').on('click',function(){
var invoice_id = $('#send_invoice').data('invoiceid'); // this is collecting the id from the anchor tag
var invoice_to = $('#invoice_to').val();
var invoice_subject = $('#invoice_subject').val();
var invoice_message = $('#invoice_message').val();
$.ajax({
url: "includes/send-invoice.inc.php"+invoice_id,
type: 'POST',
data: {invoice_id:invoice_id,invoice_to:invoice_to,invoice_subject:invoice_subject,invoice_message:invoice_message},
success: function(send_invoice_result){
$('.error_message').html(send_invoice_result);
}
})
});
send-invoice.inc.php File
<?php
include 'db-connection.php';
echo $invoice_id = $_GET['invoice_id'];
?>
it keeps returning the same id for some unknown reason. Can anyone tell me what am I doing wrong?
This works for me
$('.send_invoice').on('click',function(){
var invoice_id = $(this).attr('data-invoiceid');
$('#send_invoice_btn').on('click',function(){
var invoice_to = $('#invoice_to').val();
var invoice_subject = $('#invoice_subject').val();
var invoice_message = $('#invoice_message').val();
$.ajax({
url: 'includes/send-invoice.inc.php?invoice_id='+invoice_id,
type: 'POST',
data: {invoice_to:invoice_to,invoice_subject:invoice_subject,invoice_message:invoice_message},
success: function(send_invoice_result){
}
});
});
});
This is a little different from the method of submitting a form via static form value in modal. Using the same method is not working because AJAX not submitting the form value from the shown modal. So,
html
load form
modal
<div class="modal fade" id="xModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="xModalLabel">loading...</h4>
</div>
<div class="modal-body">...</div>
<div class="modal-footer">
<button type="button" class="btn btn-link waves-effect">SAVE CHANGES</button>
<button type="button" class="btn btn-link waves-effect" data-dismiss="modal">CLOSE</button>
</div>
</div>
</div>
</div>
jquery
//clear modal
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
//submit form
$('#xModal').on('shown.bs.modal',function (e) {
e.preventDefault();
var form=$(this).find('form').serialize();
$('#save_btn').on('click',function(){
$.ajax({
url:'inc/data.php',
type:'POST',
data:form,
success : function(data){
console.log(data);
}
});
});
});
data.php
<?
print_r($_POST);
?>
remote_form.html
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="xModalLabel">Reg Form</h4>
</div>
<div class="modal-body">
<form>
<input type="text" name="fname" /><br />
<input type="text" name="lname" /><br />
<input type="text" name="email" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link waves-effect" id="save_btn">SAVE</button>
</div>
</div>
Thanks, any comment is welcome!
Delegate your click event, move the event outside the on('shown.bs.modal') event
$(document).on('click', '#save_btn',function(){
var form=$(this).closest('form').serialize();
$.ajax({
url:'inc/data.php',
type:'POST',
data:form,
success : function(data){
console.log(data);
}
});
});
You can set ids to input fields and then getting data from that id as follows.
<input type="text" name="fname" id="fname"/>
and on the script do like this.
//submit form
$('#xModal').on('shown.bs.modal',function (e) {
e.preventDefault();
$('#save_btn').on('click',function(){
var fname = $("#fname");
$.ajax({
url:'inc/data.php',
type:'POST',
data:{
fname = fname
},
success : function(data){
console.log(data);
}
});
});
});
I'm having an issue passing input and textarea values from a form in modal to AJAX so I can pass them to php.
The input field and textarea values are coming up blank when I submit the form in modal and jquery is not displaying any errors. It simply POST an empty (blank) string for each element.
for example, it shows something like this.
subject=&content=
in the dialog box, I load a name and an ID and both POST successfully but the input values which are not loaded with the form, are not being sent. I understand that the name and ID do POST because they are loaded on DOM along with the form but I do not know how to pass values that are not loaded along with the form in modal.
This is a sample of the form.
<?php while($row = mysqli_fetch_array($res)){
//row data for each post
$r_id = $row['r_id'];
$name = $row['name'];
?>
<div id="m_f_box" class="modal fade msg-box-custom" tabindex="-1" data-width="400">
<div class="modal-header-custom">
<h5 class="modal-title">Send to <span><?php echo $name ?></span></h5>
</div>
<form id="user_m_form" name="user_m_form" action="#" method="POST">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div id="s_row" class="col_full">
<h5>Asunto</h5>
<input id="m_subject" name="m_subject" class="required sm-form-control" type="text" maxlength="40"></input>
</div>
<div id="m_row" class="col_full">
<h5>Mensaje</h5>
<textarea id="m_content" name="m_content" class="required sm-form-control" type="text"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="send_m" name="user_m_form" class="button button-mini button-blue" value="<?php echo $r_id ?>">Send</button>
<button type="button" id="can_m" name="can_m" data-dismiss="modal" class="button button-mini button-blue">Cancel</button>
</div>
</form>
</div>
<?php } ?>
This is a sample of the jquery/ajax call.
<script type="text/javascript">
$(document).on('click', '#send_m', function(e){
e.preventDefault();
var r_id = $('#send_m').val();
var subject = $('#m_subject').val();
var content = $('#m_content').val();
//var form_data = $('#user_m_form').serialize(); test with serialized form data.
//alert(subject); test what is being sent as an alert
//console.log(subject); test what is being sent to view in console
$.ajax({
type:'POST',
url:'test_file.php',
data: { r_id : recipient_id,
subject : subject,
content : content,
},
cache: false,
success:function(res){
//do some stuff
}
});
return false;
});
</script>
Any ideas on why and/or how to POST these values?
Thanks in advance,
Note: Excuse the formatting for the HTML portion. It's hard to properly format everything using a phone.
Note: If you are trying to define multiple modal using while loop,
Your HTML
<div id="m_f_box" class="modal fade msg-box-custom" tabindex="-1" data-width="400">
<div class="modal-header-custom">
<h5 class="modal-title">Send to <span><?php echo $name ?></span></h5>
</div>
<form id="user_m_form" name="user_m_form" action="#" method="POST">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div id="s_row" class="col_full">
<h5>Asunto</h5>
<input id="m_subject_<?php echo $row['r_id']; ?>" name="m_subject" class="required sm-form-control" type="text" maxlength="40"></input>
</div>
<div id="m_row" class="col_full">
<h5>Mensaje</h5>
<textarea id="m_content_<?php echo $row['r_id']; ?>" name="m_content" class="required sm-form-control" type="text"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="<?php echo $row['r_id']; ?>" name="user_m_form" class="button button-mini button-blue send" value="<?php echo $r_id ?>">Send</button>
<button type="button" id="can_m" name="can_m" data-dismiss="modal" class="button button-mini button-blue">Cancel</button>
</div>
</form>
</div>
<?php } ?>
Your Script
<script type="text/javascript">
$(document).on('click', '.send', function(e){
var r_id = (this).attr('id');
var subject = $('#m_subject'+id).val();
var content = $('#m_content'+id).val();
//......
//.......
});
</script>
Note: You just need to understand the JQuery selector (ID and Class). See the difference between #ID and .Class selectors in Jquery.
You are generating multiple Modal with same ID and try to get those field values using IDs (selector). But the IDs for each modal input fields must be unique to get the value. and for on click operation the button must have unique ID or you just need to define class as above code has.
See how I have defined class for click button and getting ID for each modal. Modal must be unique in the sense of their field.
Example done POST request with Ajax call on ModalBox
My View page code:
<div class="panel panel-default">
<div class="panel-body">
<p class="text-danger">There are total <span class="text-bold">{{ sizeof($data) }}</span> Departments.</p>
<table class="table" id="department-data">
<tr>
<th>#</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
<th>Manage</th>
</tr>
<?php $order = 0; ?>
#foreach($data as $key)
<tr>
<td>{{ ++$order }}</td>
<td id="department_name">{{ $key->title }}</td>
<td>
<a href="#">
<button class="btn btn-default edit-department" data-toggle="modal" data-target="#updateDepartmentModel" id="{{ $key->id }}"><i class="fa fa-pencil"></i></button>
</a>
</td>
<td>
<button id="{{ $key->id }}" class="btn btn-danger delete-btn" data-toggle="modal" data-target="#delete-department"><i class="fa fa-trash"></i></button>
</td>
<td>
<a href='program/{{ $key->id }}' id="delete-id">
<button class="btn btn-primary"><i class="fa fa-cog"></i></button>
</a>
</td>
</tr>
#endforeach
</table>
</div>
</div>
Modals on the same page:
<!-- Add New Department Modal -->
<div class="modal fade" id="newDepartmentModel" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add New Department</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="{{ url('department/create') }}" method="POST">
{{ csrf_field() }}
<div class="modal-body">
<div class="form-group">
<label for="title">Department Name:</label>
<input type="text" class="form-control" id="title" name="title">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Add</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<!-- ./Model -->
<!-- Update Department Modal -->
<div class="modal fade" id="updateDepartmentModel" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Update a Department</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div class="modal-body">
<div class="form-group">
<label for="old-title">Department Name:</label>
<input type="text" class="form-control" id="old-title" name="title">
</div>
</div>
<div class="modal-footer">
<button type="submit" id="edit-dept" class="btn btn-primary edit-dept">Edit</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<!-- ./Model -->
Here is Script:
<script type="text/javascript">
var token = '{{ Session::token() }}';
var url = '{{ route('department/edit') }}';
var dept_id = '';
// Setup Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Update the department
$(document).on('click', '.edit-department', function () {
var department_id = $(this).attr('id');
console.log(department_id);
dept_id = department_id;
$.get('department/'+department_id, function (data) {
$('#old-title').val(data.title);
console.log(data);
});
});
// Handle Post Request (Edit Department)
$(document).ready(function () {
$('#edit-dept').click(function () {
$.ajax({
method: 'POST',
url: url,
data: { id: dept_id, title: $('#old-title').val(), _token: token},
dataType: 'JSON'
}).done(function (data) {
//console.log(data);
});
});
});
</script>
Routes is:
Route::post('department/edit', function (\Illuminate\Http\Request $request){
$id = $request->input('id');
$title = $request->input('title');
DB::table('departments')->where('id', $id)->update(array('title' => $title));
return redirect('department')->with('alert_info', 'Department was successful Update!');})->name('department/edit');
Put this line on page Head:
<!-- csrf for meta -->
<meta name="csrf-token" content="{{ csrf_token() }}" />
And in Controller Create and Get routes:
Route::post('department/create', 'DepartmentController#store');
Route::get('department/{id}', 'DepartmentController#showById');
And these definitions:
public function store(StoreDepartmentPostRequest $request)
{
$department = new Department;
$department->title = $request->input('title');
$department->timestamps = time();
$department->save();
return redirect('department')->with('alert_success', 'Department was successful added!');
}
public function showById($id){
$data = Department::findOrFail($id);
return response()->json($data);
}
So i have table and trying to do C.R.U.D.
I make for edit form with modal. As my table populate inside of foreach i put my modal inside in table to get correct id of row.
This is my ajax function
$("#uin").click(function(){
var mydata = $("form#update-interview").serialize();
var id = $("#jsonid").val();
console.log(mydata); // it's only for test
$.ajax({
type: "POST",
url: "vacancy/interview/" + id , //process
data: { user_submission_token: $("#session_token").val(),mydata },
dataType: "json",
success: function(msg){
alert("Succeess");
$("#form-content").modal('hide'); //hide popup
},
error: function(){
alert("failure");
}
});
});
From this Ajax Submit im getting output like:
candidate_id=120&vacancy_id=48&stage=Interview&date=&candidate_id=120&vacancy_id=49&stage=Interview&date=&candidate_id=120&vacancy_id=53&stage=Interview&date=&candidate_id=120&vacancy_id=54&stage=Interview&date=&candidate_id=120
and this continues until last ID, so i need to get only 1 candidate_id ,vacancy_id and stage with date.
Its getting all of them because is inside in foreach but if i put my form outside of foreach then how i will get my row ID?
this is my function in controller
public function interview($i)
{
$type=$this->input->post();
$test= json_encode($data= array(
"status" => 1,
"candidate_id" => $this->input->post('candidate_id'),
"vacancy_id" => $this->input->post('vacancy_id'),
"date" => $this->input->post('date'),
"stage" => $type[3],
)
);
var_dump($test);
die();
$this->vacancies->update_interview($data, array("vacancy_id" => $i));
}
from this controller var_dump i got this output {"status":1,"candidate_id":false,"vacancy_id":false,"date":false,"stage":null}
seems my function is not correct also, can i get some advice?
and model side is just this
public function update_interview($i)
{
$this->db->insert("interviews", $i);
}
For any case this is my form its little-bit long
<!-- Update Interview-->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<form class="no-error-margin" id="update-interview">
<div class="modal-content">
<div class="modal-body">
<div class="form-group">
<input type="hidden" name='candidate_id' value="<?= $candidate_id; ?>" />
<input type="hidden" name='vacancy_id' id="jsonid" value="<?= $row['id']; ?>" />
</div>
<div class="form-group">
<label class="control-label">Type:</label>
<select id="classinput" tabindex="1" name="stage" class="form-control required">
<option value="Interview">Interview</option>
<option value="Final Interview">Final Interview</option>
<option value="">Rejected</option>
</select>
</div>
<!-- Using DatePicker-->
<div class="date-form">
<div class="control-group">
<label class="control-label" style="margin: 0 30%;padding: 7px;">When The Interview Will Be?</label>
<div class="container">
<div class="row">
<div class='col-sm-6 col-md-offset-3'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input name="date" type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button id="uin" type="submit" data-dismiss="modal" class="btn btn-warning btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Update</button>
</div>
</div>
<?php echo form_close();?>
</div>
</div>
<!-- End Interview-->
UPDATE:
Okay thanks to Niranjan N Raju
Now i'm getting just 1 result in POST and its correct which is looks like
candidate_id=126&vacancy_id=46&stage=Interview&date=12/03/2015+12:00+AM
So now how to insert this into database? Into candidate_id , vacancy_id , stage and date columns with their values?
this is wrong,
data: { user_submission_token: $("#session_token").val(),mydata },
It should be
data: { user_submission_token: $("#session_token").val(),mydata:mydata },
^ ^
data is always is passed as {key:value,key:value}
But you are passing only key.
$("#uin").click(function(){
var mydata = $("form#update-interview").serialize();
var id = $("#jsonid").val();
mydata.push({user_submission_token: $("#session_token").val()
});
$.ajax({
type: "POST",
url: "vacancy/interview/" + id ,
data: mydata,
dataType: "json",
success: function(msg){
alert("Succeess");
$("#form-content").modal('hide');
},
error: function(){
alert("failure");
}
});
});
i have tried all my possible best and searched every where but to no avail that is why i have decided to do this after about 4years of learning from this website.
i noticed that my modal pop up window is not waiting for my ajax that sends the value retrived from the anchor tag which is then sent to the PHP file here by casuing the php to give an index undefined error. but if i just use the alert() on success: function() i see the values been retrived from the anchor tag. now this is my code the html link <a href="#" class="btn btn-info btn-sm" id="editr" data-id="<?php echo $postID; ?>" data-owner="<?php echo $op; ?>" data-toggle="modal" data-target="#modal-form" >Edit Page</a>
$(function(){
$("#editr").click(function(e) {
e.preventDefault();
var id = $(this).attr("data-id");
var owner = $(this).attr("data-owner");
var dataString = 'id=' + id + '&user=' + owner;
$.ajax({
url: "../config/edit.php",
type: "POST",
data : dataString,
cache: false,
success: function(data){
alert(data);
}
});
});
});
this is the modal part
<div class="modal fade" id="modal-form" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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="myModalLabel">Form in moadl</h4>
</div>
<div class="modal-body">
<form role="form">
<div class="form-group">
<label for="exampleInputEmail1"> Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</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">Save changes</button>
</div>
</div>
</div>
</div>
You need to wait for the promise to return and then continue on with what you were trying to do.
$(function(){
$("#editr").click(function(e) {
e.preventDefault();
var id = $(this).attr("data-id");
var owner = $(this).attr("data-owner");
var dataString = 'id=' + id + '&user=' + owner;
var promise = $.ajax({
url: "../config/edit.php",
type: "POST",
data : dataString,
cache: false
});
promise.then(function(data){
//show modal with data (in place of alert)
alert(data);
});
});
});