ajax response not proper binding in select option value jQuery - javascript

I'm trying to get value from ajax to HTML but it's not correctly binding in the dropdown even I tried in the textbox it's not showing. I tried to add some static value it's also not showing.
Ajax response is properly getting in the console but when I am trying to bind in the HTML its not show proper.
HTML code:
<div class="modal fade" id="largeModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title1" id="defaultModalLabel"></h4>
</div>
<div class="modal-body">
<form method="POST" action="" accept-charset="UTF-8" >
<label>Room Type</label>
<h1 class="modal-title1" ></h1>
<!-- <input type="text" class="apple"> -->
<select class="apple" tabindex="-98">
<option>-Select Room type-</option>
</select>
<div class="modal-footer">
<input class="btn btn-lg bg-indigo waves-effect" type="submit" value="SAVE">
<button class="btn btn-lg bg-black waves-effect" data-dismiss="modal" type="button">CLOSE</button>
</div>
</form>
</div>
</div>
</div>
</div>
JQuery code:
$(document).off('click', '.hotel_add').on('click', '.hotel_add', function () {
var id = $(this).attr('id');
var pos = $(this).closest('.hotel-result').data('pos-id');
$.get("<?php echo base_url('hotel/hotelDataGet') ?>/" + id + '/' + pos, function (result) {
var data = JSON.parse(result)
$.each(data,function(index,value){
console.log(value);
$('#defaultModalLabel').html(value.hotel_name);
$('.apple').append('
<option value="'+value['roomtype']+'">'+value['roomtype']+'</option>
');
});
$("#largeModal").modal();
//debugger;
});
});
AJAX response
[
{
"id": "1",
"hotel_name": "Hotel Bharat",
"room_type": "4,1,2",
"cp_price": "98"
},
{
"roomtype": "Deluxe Room"
},
{
"roomtype": "Luxury Room"
},
{
"roomtype": "Family room"
}
]

hotel_name only exists on the first object of your response, and the roomtype does not exist in your fist object, so you can change to this:
$.each(data,function(index,value){
//check to see if this object has the property "hotel_name"
if(value.hasOwnProperty("hotel_name"){
$('#defaultModalLabel').html(value.hotel_name);
}
//check to see if this object has the property "roomtype"
if(value.hasOwnProperty("roomtype") {
$('.apple').append(
'<option value="' +
value['roomtype'] +
'">' +
value['roomtype'] +
'</option>'
);
}
});

Related

Load DataTable data to a Edit Modal

I am trying to create an edit function for my data table. The data table is created using Yajra Data tables. Everything working fine unless when I try to load existing data into the edit modal it fails. No error is showing but the modal does not launch. I have only included a little portion of my code here for easy reference.
Modal:
<!-- Update Status Model Box -->
<div id="updateStatusModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content bg-default">
<div class="modal-body">
<form class="form-horizontal" id="updateStatus">
#csrf
#method('PUT')
<div class="row">
<div class="col">
<div class="form-group text-center">
<h6 class="font-weight-bold">Stage 1</h6>
<label for="stage_1" class="switch">
<input type="checkbox" class="form-control" id="stage_1">
<div class="slider round"></div>
</label>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<div class="col-md">
<label for="firstname">Coding</label>
<input type="text" class="form-control" id="first_name" value="" placeholder="Enter Completed Page Count">
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer justify-content-between">
<button type="button" name="update_btn" id="update_btn" class="btn btn-outline-warning">Update</button>
</div>
</div>
</div>
</div>
jquery funtion:
// Edit action
$(document).on('click', '.updateStatus', function(){
$tr = $(this).closest('tr');
var data = $tr.clidren("td").map(function(){
return $(this).text();
}).get();
console.log(data);
$('#id').val(data[0]);
$('#job_id').val(data[2]);
$('#stage_1').val(data[3]);
$('#conversion').val(data[4]);
$('#updateStatusModal').modal('show');
});
I tried this method I found but this is not working. Can anyone provide me any pointers here?
I've just didn't seen your front scripts (also back-end codes), but instead I can share my implementation for that you need. It works perfectly like showed in this (screenshot).
Here I'll put front and back codes. There is functionality for editing existsing Datatable record, also record deletion.
FRONT
<!--HERE ATTACH NECESSARY STYLES-->
<!--VIEW end-->
<link rel="stylesheet" type="text/css" href="{{ asset('css/admin/datatables.min.css') }}"/>
<table id="yajra_datatable" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Options</th>
</tr>
</thead>
</table>
<div class="modal modal-danger fade" id="modal_delete">
<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">Delete Language</h4>
</div>
<div class="modal-body">
<p>Are You sure You want to delete this Language?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
<button id="delete_action" type="button" class="btn btn-outline">Submit</button>
</div>
</div>
</div>
</div>
<div class="modal modal-warning fade" id="modal_edit">
<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">Edit Language</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="language_name">Language Name</label>
<input name="language_name" id="language_name" type="text" value="" class="form-control" placeholder="Language Name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Cancel</button>
<button id="edit_action" type="button" class="btn btn-outline">Submit</button>
</div>
</div>
</div>
</div>
<input type="hidden" id="item_id" value="0" />
<!--VIEW end-->
<!--HERE ATTACH NECESSARY SCRIPTS-->
<!--SCRIPTS start-->
<script src="{{ asset('js/admin/jquery.dataTables.min.js') }}"></script>
<script type="text/javascript">
var YajraDataTable;
function delete_action(item_id){
$('#item_id').val(item_id);
}
function edit_action(this_el, item_id){
$('#item_id').val(item_id);
var tr_el = this_el.closest('tr');
var row = YajraDataTable.row(tr_el);
var row_data = row.data();
$('#language_name').val(row_data.name);
}
function initDataTable() {
YajraDataTable = $('#yajra_datatable').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('admin.book_languages.ajax') }}",
"columns":[
{
"data": "name",
"name": "name",
},
{
"data": "",
"name": ""
},
],
"autoWidth": false,
'columnDefs': [
{
'targets': -1,
'defaultContent': '-',
'searchable': false,
'orderable': false,
'width': '10%',
'className': 'dt-body-center',
'render': function (data, type, full_row, meta){
return '<div style="display:block">' +
'<button onclick="delete_action(' + full_row.id + ')" type="button" class="delete_action btn btn-danger btn-xs" data-toggle="modal" data-target="#modal_delete" style="margin:3px"><i class="fa fa-remove"></i> Delete</button>' +
'<button onclick="edit_action(this, ' + full_row.id + ')" type="button" class="edit_action btn btn-warning btn-xs" data-toggle="modal" data-target="#modal_edit" style="margin:3px"><i class="fa fa-edit"></i> Edit</button>' +
'</div>';
}
}
],
});
return YajraDataTable;
}
$(document).ready(function() {
var YajraDataTable = initDataTable();
$('#delete_action').on('click', function (e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.book_languages.delete') }}",
data: {
'item_id': $('#item_id').val(),
'_token': "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
$('#modal_delete').modal('hide');
YajraDataTable.ajax.reload(null, false);
console.log(data.message);
}
})
});
$('#edit_action').on('click', function (e) {
e.preventDefault();
$.ajax({
url: "{{ route('admin.book_languages.edit') }}",
data: {
'item_id': $('#item_id').val(),
'language_name': $('#language_name').val(),
'_token': "{{ csrf_token() }}"
},
type: "POST",
success: function (response) {
$('#modal_edit').modal('hide');
YajraDataTable.ajax.reload(null, false);
console.log(data.message);
}
})
});
$('#modal_delete').on('hidden.bs.modal', function () {
$('#item_id').val(0);
});
$('#modal_edit').on('hidden.bs.modal', function () {
$('#item_id').val(0);
$('#language_name').val("");
});
});
</script>
<!--SCRIPTS end-->
BACK
public function index() {
return view('admin.book-languages.index');
}
public function ajax() {
$items = BookLanguage::latest('id');
return DataTables::of($items)->make(true);
}
public function delete(Request $request) {
$item_id = $request->get('item_id');
$item = BookLanguage::find($item_id);
if(empty($item)) {
return response()->json([
'success' => false,
'message' => 'Item not found!',
], 200); // 404
} else {
$item->delete();
return response()->json([
'success' => true,
'message' => 'Item successfully deleted.',
], 200);
}
}
public function update(Request $request) {
$item_id = $request->get('item_id');
$item = BookLanguage::find($item_id);
if(empty($item)) {
return response()->json([
'success' => false,
'message' => 'Item not found!',
], 404);
} else {
$item->name = $request->get('language_name');
$item->save();
return response()->json([
'success' => true,
'message' => 'Item successfully updated.',
], 200);
}
}
ROUTES
// ...
// book_languages
Route::group(['prefix' => 'book-languages', 'as' => 'admin.book_languages.',], function () {
Route::get('all', 'BookLanguageController#index')->name('index');
Route::get('ajax', 'BookLanguageController#ajax')->name('ajax');
Route::post('update', 'BookLanguageController#update')->name('edit');
Route::post('delete', 'BookLanguageController#delete')->name('delete');
});
// ...
I think this can help you and others to build wanted functionality. Here this could be also with more hint-comments, but as it not small, I can answer later via post comments.
i am building a Laravel ERP-like web application and am implementing a CRUD function modal like you. I have made mine a server-side processing application with resource APIs in Laravel. Well, please be reminded that i have cut the #extends(layout.app) & #section('stylesheet') parts to go right into the answer. You should extend them in your own application to make everything work.
View.blade script
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('#customertable').DataTable({
processing: true,
serverSide: true,
dom: 'B<"top"frli>tp',
ajax: {
url: "{{ route('customer.index') }}", //Accessing server for data
columns: [
{data: 'id'}, //data refers to DB column name
{data: 'name'},
{data: 'chiname'},
{data: 'type'},
{data: 'action'}, //this is an addColumn item from Controller
]
});
$('#createNewcustomer').click(function () {
$('#saveBtn').val("create customer");
$('#customerid').val('');
$('#customerForm').trigger("reset");
$('#modelHeading').html("Create New Customer");
$('#customermodal').modal('show');
});
//Control the modal behavior when clicking the edit button.
$('body').on('click', '.editcustomer', function () {
var customerid = $(this).data('id');
$.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
$('#modelHeading').html("Edit Customer");
$('#saveBtn').val("edit-user");
$('#customermodal').modal('show');
$('#customerid').val(data.id);
$('#name').val(data.name);
$('#chiname').val(data.chiname);
$('#type').val(data.type);
})
});
//Create a brand-new record
$('#createNewcustomer').click(function () {
$('#saveBtn').val("create customer");
$('#customerid').val('');
$('#customerForm').trigger("reset");
$('#modelHeading').html("Create New Customer");
$('#customermodal').modal('show');
});
//Update
$('body').on('click', '.editcustomer', function () {
var customerid = $(this).data('id');
$.get("{{ route('customer.index') }}" +'/' + customerid +'/edit', function (data) {
$('#modelHeading').html("Edit Customer");
$('#saveBtn').val("edit-user");
$('#customermodal').modal('show');
$('#customerid').val(data.id);
$('#name').val(data.name);
$('#chiname').val(data.chiname);
$('#type').val(data.type);
})
});
//Save
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#customerForm').serialize(),
url: "{{ route('customer.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#customerForm').trigger("reset");
$('#customermodal').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Error');}
});
});
//Delete
$('body').on('click', '.deletecustomer', function () {
var id = $(this).data("id");
confirm("Are You sure?");
$.ajax({
type: "DELETE",
url: "{{ route('customer.store') }}"+'/'+id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
</script>
View.blade html-table & modal part
#section('content')
<div class="container">
<div class="card-header border-left"><h3><strong> Customer overview</strong></h3></div>
<br>
<div class="row">
<div class="col-md text-right">
<button type="button" class="btn btn-success" data-toggle="modal" href="javascript:void(0)" id="createNewcustomer">Create Record</button>
</div>
</div>
{{-- Modal --}}
<div id="customermodal" class="modal fade" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times</span></button></div>
<div class="modal-body">
<form id="customerForm" name="customerForm" class="form-horizontal">
<input type="hidden" name="customerid" id="customerid">
<div class="form-group">
<label for="name" class="col-sm-6 control-label">Customer Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Customer Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="chiname" name="chiname" placeholder="Customer Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">Contract type</label>
<div class="col-sm-12">
<select name="type" id="type" class="form-control">
<option value="" disabled>Type</option>
<option value="Government">Government Contract</option>
<option value="Private">Private Contract</option>
</select>
</div></div>
<br>
<div class="col-sm text-right">
<button type="submit" class="btn btn-outline-secondary" id="saveBtn" value="create">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
{{-- Table --}}
<br>
<div class="row">
<br/>
<br/>
<div class="form-group col-md-12 align-content-center">
<table class="table-fluid center-block" id="customertable">
<thead>
<tr>
<th>id</th>
<th>ChiName</th>
<th>Name</th>
<th>Type</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
#endsection
CustomerController
public function index(Request $request)
{
$customers = Customer::all();
}
return Datatables::of($customers)
->addColumn('action', function($customer){
$btn = 'Edit';
$btn = $btn.' Delete';
return $btn;})
->rawColumns(['action'])
->make(true);
}
return view('customer.Customer'); //my view blade is named Customer under customer dir. put your blade destination here.
}
public function store(Request $request)
{
Customer::updateOrCreate(['id' => $request->customerid],
['name' => $request->name, 'chiname' => $request->chiname,'type' =>$request->type]);
return response()->json(['success'=>'Product saved successfully.']);
}
public function edit($id)
{
$customer = Customer::findorfail($id);
return response()->json($customer);
}
public function destroy($id)
{
Customer::findorfail($id)->delete();
return response()->json(['success'=>'Product deleted successfully.']);
}
Model (pick either A.) $guarded = [] OR B.) $fillable = ['fields','fields'] as you like)
class Customer extends Model
{
protected $fillable = ['name','chiname','type'];
}
web.api (route setting)
Route::resource('customer', 'CustomerController')->middleware('auth');
Migration / DB schema structure
class CreateCustomersTable extends Migration
{
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('chiname');
$table->string('type');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('customers');
}
I have not included any protection in it like gate, auth or so. But basically this is the skeleton of doing CRUD with dataTable in Laravel framework with both JS, Ajax, Jquery, PHP all in one. Kindly be reminded that the queries for such CRUD actions are directly linked to the Database server. If you want to show data processed by the DataTable, use your own jquery function to fetch and show them on the modal. My answer is not the best but i hope it helps you >:)
(I could not post a picture to show you here as i dont have enough reputation lol. gg)

Laravel upload image through modal not working

Im making an inventory system in laravel and I want to upload an image every products that I have. My problem is I cant upload an image. I tried my old code in uploading photo and it is not working in my current project. The upload code you see in the controller is in a laravel collective form. But now, I am using a modal and an ajax request to save the inputs into the database. Can someone know what should I do about this? Btw, my modal doesnt have a form tag because I thought forms will not work in modals. Thanks in advance!
Modal Create.
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Register New Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p style="font-weight: bold;">Name </p>
<input type="text" class="form-control" id="product_name"/>
<p style="font-weight: bold;">Description </p>
<input type="text" class="form-control" id="description"/>
<p style="font-weight: bold;">Price </p>
<input type="text" class="form-control" id="currentprice"/>
{{-- <input style="text-transform:uppercase" type="text" class="form-control" id="supplier_id"/> --}}
<p style="font-weight: bold;">Supplier </p>
<select class="form-control" id="supplier_id" >
#foreach ($suppliers as $supplier)
<option value="{{$supplier->id}}">{{$supplier->name}}</option>
#endforeach
</select>
<p style="font-weight: bold;">Picture </p>
<input type="file" class="form-control" id="picture"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="add_product">Add</button>
</div>
</div>
</div>
</div>
Controller
public function store(Request $request)
{
$data = $request->all();
$data['product_name'] = ($data['product_name']);
$data['description'] = ($data['description']);
$data['supplier_id'] = ($data['supplier_id']);
$data['price'] = ($data['price']);
if ($request->hasFile('image')){
//Add new photo
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('img/' . $filename);
Image::make($image)->resize(300,300)->save($location);
$oldFilename = $products->image;
//Update DB
$products->image = $filename;
//Delete the old photo
// Storage::delete($oldFilename);
}
Product::create($data);
return response()->json($data);
}
Ajax
$(document).ready(function(){
//add
$('#add_product').click(function(e){
e.preventDefault();
var name = $('#product_name').val();
var description = $('#description').val();
var price = $('#currentprice').val();
var supplier_id = $('#supplier_id').val();
var image = $('#picture').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ url('/product') }}",
method: 'post',
data:{
product_name: name,
description: description,
price: price,
supplier_id: supplier_id,
image: image,
},
success: function (res){
console.log(res);
window.location.href = '{{route("products")}}'
}
});
});
//add
Model
class Product extends Model
{
use SoftDeletes;
protected $fillable = [
'product_name', 'quantity', 'description' ,'supplier_id', 'price', 'image',
];
public function supplier()
{
return $this->hasOne('App\Supplier');
}
}
I Can’t add a comment, that is dumb ...
Your also going to likely need to encode the image data in the json.
See How do you put an image file in a json object?
(Fixed wording)

Why can't the edit-modal fetch the data(of the selected row) from my database?

So this is my brand.php file
And it portrays the edit part of the brand
so in this part we can probably see how the thing will look like
<!-- edit brand -->
<div class="modal fade" id="editBrandModel" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" id="editBrandForm" action="php_action/editBrand.php" method="POST">
<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"><i class="fa fa-edit"></i> Edit Brand</h4>
</div>
<div class="modal-body">
<div id="edit-brand-messages"></div>
<div class="modal-loading div-hide" style="width:50px; margin:auto;padding-top:50px; padding-bottom:50px;">
<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
<span class="sr-only">Loading...</span>
</div>
<div class="edit-brand-result">
<div class="form-group">
<label for="editBrandName" class="col-sm-3 control-label">Brand Name: </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="editBrandName" placeholder="Brand Name" name="editBrandName" autocomplete="off">
</div>
</div> <!-- /form-group-->
<div class="form-group">
<label for="editBrandStatus" class="col-sm-3 control-label">Status: </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<select class="form-control" id="editBrandStatus" name="editBrandStatus">
<option value="">~~SELECT~~</option>
<option value="1">Available</option>
<option value="2">Not Available</option>
</select>
</div>
</div> <!-- /form-group-->
</div>
<!-- /edit brand result -->
</div> <!-- /modal-body -->
<div class="modal-footer editBrandFooter">
<button type="button" class="btn btn-default" data-dismiss="modal"> <i class="glyphicon glyphicon-remove-sign"></i> Close</button>
<button type="submit" class="btn btn-success" id="editBrandBtn" data-loading-text="Loading..." autocomplete="off"> <i class="glyphicon glyphicon-ok-sign"></i> Save Changes</button>
</div>
<!-- /modal-footer -->
</form>
<!-- /.form -->
</div>
<!-- /modal-content -->
</div>
<!-- /modal-dailog -->
</div>
<!-- / add modal -->
<!-- /edit brand -->
> --this one is the end part
And this is the fetching part, wherein once you click the button from the row(example row 1), a modal(Edit Modal will likely appear), but the thing is, once the modal appear, the data that is supposed to be fetched from the row is not on that modal ;-;
<?php
require_once '../../includes/connection.php';
$brandId = $_POST['brandId'];
$sql = "SELECT brand_id, brand_name, brand_active, brand_status FROM brands WHERE brand_id = $brandId";
$result = $connect->query($sql);
if($result->num_rows > 0) {
$row = $result->fetch_array();
} // if num_rows
$connect->close();
echo json_encode($row);
?>
Now the JScript part
This part is the filler part(like getting the data and now portraying the data and filling the input boxes etc..)
function editBrands(brandId = null) {
if(brandId) {
// remove hidden brand id text
$('#brandId').remove();
// remove the error
$('.text-danger').remove();
// remove the form-error
$('.form-group').removeClass('has-error').removeClass('has-success');
// modal loading
$('.modal-loading').removeClass('div-hide');
// modal result
$('.edit-brand-result').addClass('div-hide');
// modal footer
$('.editBrandFooter').addClass('div-hide');
$.ajax({
url: 'fetchSelectedBrand.php',
type: 'post',
data: {brandId : brandId},
dataType: 'json',
success:function(response) {
// modal loading
$('.modal-loading').addClass('div-hide');
// modal result
$('.edit-brand-result').removeClass('div-hide');
// modal footer
$('.editBrandFooter').removeClass('div-hide');
// setting the brand name value
$('#editBrandName').val(response.brand_name);
// setting the brand status value
$('#editBrandStatus').val(response.brand_active);
// brand id
$(".editBrandFooter").after('<input type="hidden" name="brandId" id="brandId" value="'+response.brand_id+'" />');
// update brand form
$('#editBrandForm').unbind('submit').bind('submit', function() {
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
var brandName = $('#editBrandName').val();
var brandStatus = $('#editBrandStatus').val();
if(brandName == "") {
$("#editBrandName").after('<p class="text-danger">Brand Name field is required</p>');
$('#editBrandName').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#editBrandName").find('.text-danger').remove();
// success out for form
$("#editBrandName").closest('.form-group').addClass('has-success');
}
if(brandStatus == "") {
$("#editBrandStatus").after('<p class="text-danger">Brand Name field is required</p>');
$('#editBrandStatus').closest('.form-group').addClass('has-error');
} else {
// remove error text field
$("#editBrandStatus").find('.text-danger').remove();
// success out for form
$("#editBrandStatus").closest('.form-group').addClass('has-success');
}
if(brandName && brandStatus) {
var form = $(this);
// submit btn
$('#editBrandBtn').button('loading');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success == true) {
console.log(response);
// submit btn
$('#editBrandBtn').button('reset');
// reload the manage member table
manageBrandTable.ajax.reload(null, false);
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
$('#edit-brand-messages').html('<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
'</div>');
$(".alert-success").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
} // /if
}// /success
}); // /ajax
} // /if
return false;
}); // /update brand form
} // /success
}); // ajax function
} else {
alert('error!! Refresh the page again');
}
} // /edit brands function
Can you check the Network tab to see the result from server? You can debug your app by seeing that result.
By the way, there're two things that you may need to edit:
1/ If brandId is interger, you need to get it from $_GET by intval($_POST['brandId']) to prevent SQL Injection.
2/
if($result->num_rows > 0) {
$row = $result->fetch_array();
}
else {
$row = array();
}
your code need to return empty array if sql result is empty to avoid Undefined variable error.

How do I detect the id of a currently displayed element using Javascript?

I am basically using Gmail API to create send and reply to functionalities for myself. The problem is in the reply section. I am using jQuery to dynamically create divs for every message that appears in my inbox (max-count:10) and a separate set of divs (any single one to appear on clicking a mail link) wherein for each div, I am having the modal-header div for the subject, reply and close buttons whereas a modal-body div with an iframe for displaying the content.
var message1;
function appendMessageRow(message) {
$('.table-inbox tbody').append(
'<tr>\
<td>' + getHeader(message.payload.headers, 'From') + '</td>\
<td>\
<a href="#message-modal-' + message.id +
'" data-toggle="modal" id="message-link-' + message.id + '">' +
getHeader(message.payload.headers, 'Subject') +
'</a>\
</td>\
<td>' + getHeader(message.payload.headers, 'Date') + '</td>\
</tr>'
);
$('body').append(
'<div class="modal fade" id="message-modal-' + message.id +
'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">\
<div class="modal-dialog modal-lg">\
<div class="modal-content">\
<div class="modal-header">\
<h4 class="modal-title" id="myModalLabel">' +
getHeader(message.payload.headers, 'Subject') +
'</h4>\
<button type="button"\
class="close"\
data-dismiss="modal"\
aria-label="Close" style="float:right;">\
<span aria-hidden="true">×</span></button>\
<span></span>\
<a data-toggle="modal" href="#reply-modal" id="reply-button" class="btn btn-primary">Reply</a>\
</div>\
<div class="modal-body">\
<iframe id="message-iframe-' + message.id + '" srcdoc="<p>Loading...</p>">\
</iframe>\
</div>\
</div>\
</div>\
</div>'
);
$('#message-link-' + message.id).on('click', function() {
var ifrm = $('#message-iframe-' + message.id)[0].contentWindow.document;
$('body', ifrm).html(getBody(message.payload));
message1 = message;
});
$('#reply-button).on('
click ',function(){
$("#reply-to").val(getHeader(message1.payload.headers, 'From')); $("#reply-subject").val('RE: ' + getHeader(message1.payload.headers, 'Subject')); $("#message-modal-" + message1.id).fadeOut(); $('div.modal-backdrop.fade.in').fadeOut();
});
}
I intend to use the Reply button to call a function which will fill the 'To' and 'Subject' field in the reply-modal(Reply button is an a tag with href=#reply-modal) that'd be visible after the message-modal-message.iddiv fades out. The problem is I am unable to get the id of this div which I need to fade out (along with that greyish background).
Also if you can see I need the whole message object and just not the message.id of the clicked message link so that I can transfer 'To' and 'Subject' to the newly appeared reply-modal div. But it just doesn't get the message.id of the clicked-on message but the last one in the list of mails displayed on the inbox page and so the #message-modal-message.id does not fade out as the message.id is not correct. Similarly, the 'To' and 'From' fields in the reply-modaldiv also contain information of the last mail in the list - doesn't matter which mail you've opened. Also as the message-modal-message.id div does not disappear, the reply-modal div appears behind it and I have to close the it div to see the reply-modal div.
I even tried having a JS function on the outside instead of the jQuery selector method $('#reply-modal').on('click',.. but couldn't do it.
Basically,
How do I get the message object after a message has been opened to view?
This is what exactly I was talking about. Sorry I couldn't paste the whole code in the questions too if that created some sort of confusion while trying to understand the question.
'Reply' button needs to be there for every message we add as divs to the display page, which also uses the two critical variables reply-to and reply-subject to pass the required data to the new reply form that opens up.
The closing of the 'Show message' div which was not possible earlier, was also linked to the message-id, which now becomes accessible.
Everything else is pretty neat; the functions required to send the reply are the same as sending a new email and are present at the very end of the code.
What I was unable to do was capture the message id of the currently displayed message on the click of "Reply" button. This is a "better" solution than a workaround, but man would it be shorter if I could have done what I'd have had wanted!
<!doctype html>
<html>
<head>
<title>Gmail API demo</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<style>
iframe {
width: 100%;
border: 0;
min-height: 80%;
height: 600px;
display: flex;
}
</style>
</head>
<body>
<div class="container">
<h1>Gmail API demo</h1>
<button id="authorize-button" class="btn btn-primary hidden">Authorize</button>
Compose
<table class="table table-striped table-inbox hidden">
<thead>
<tr>
<th>From</th>
<th>Subject</th>
<th>Date/Time</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="modal fade" id="compose-modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<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">Compose</h4>
</div>
<form onsubmit="return sendEmail();">
<div class="modal-body">
<div class="form-group">
<input type="email" class="form-control" id="compose-to" placeholder="To" required />
</div>
<div class="form-group">
<input type="text" class="form-control" id="compose-subject" placeholder="Subject" required />
</div>
<div class="form-group">
<textarea class="form-control" id="compose-message" placeholder="Message" rows="10" required></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="send-button" class="btn btn-primary">Send</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="reply-modal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<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">Reply</h4>
</div>
<form onsubmit="return sendReply();">
<div class="modal-body">
<div class="form-group">
<input type="email" class="form-control" id="reply-to" required disabled/>
</div>
<div class="form-group">
<input type="text" class="form-control" id="reply-subject" required />
</div>
<div class="form-group">
<textarea class="form-control" id="reply-message" placeholder="Message" rows="10" required></textarea>
</div>
</div>
<input type="hidden" id="reply-message-id" />
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="reply-button" class="btn btn-primary">Send</button>
</div>
</form>
</div>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="withinViewport.js"></script>
<script src="jquery.withinviewport.js"></script>
<script type="text/javascript">
var clientId = 'YOUR_CLIENT_ID.apps.googleusercontent.com';
var apiKey = 'YOUR_API_KEY';
var scopes = 'https://www.googleapis.com/auth/gmail.readonly';
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth, 1);
}
function checkAuth() {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: true
}, handleAuthResult);
}
function handleAuthClick() {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: false
}, handleAuthResult);
return false;
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
loadGmailApi();
$('#compose-button').removeClass("hidden");
$('#authorize-button').remove();
$('.table-inbox').removeClass("hidden");
} else {
$('#authorize-button').removeClass("hidden");
$('#authorize-button').on('click', function() {
handleAuthClick();
});
}
}
function loadGmailApi() {
gapi.client.load('gmail', 'v1', displayInbox);
}
function displayInbox() {
var request = gapi.client.gmail.users.messages.list({
'userId': 'me',
'labelIds': 'INBOX',
'maxResults': 10
});
request.execute(function(response) {
$.each(response.messages, function() {
var messageRequest = gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': this.id
});
messageRequest.execute(appendMessageRow);
});
});
}
function appendMessageRow(message) {
var reply_to = (getHeader(message.payload.headers, 'Reply-to') !== '' ? getHeader(message.payload.headers, 'Reply-to') : getHeader(message.payload.headers, 'From')).replace(/\"/g, '"');
var reply_subject = 'Re: ' + getHeader(message.payload.headers, 'Subject').replace(/\"/g, '"');
$('.table-inbox tbody').append(
'<tr>\
<td>' + getHeader(message.payload.headers, 'From') + '</td>\
<td>\
<a href="#message-modal-' + message.id +
'" data-toggle="modal" id="message-link-' + message.id + '">' +
getHeader(message.payload.headers, 'Subject') +
'</a>\
</td>\
<td>' + getHeader(message.payload.headers, 'Date') + '</td>\
</tr>'
);
$('body').append(
'<div class="modal fade" id="message-modal-' + message.id +
'" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">\
<div class="modal-dialog modal-lg">\
<div class="modal-content">\
<div class="modal-header">\
<h4 class="modal-title" id="myModalLabel">' +
getHeader(message.payload.headers, 'Subject') +
'</h4>\
<button type="button"\
class="close"\
data-dismiss="modal"\
aria-label="Close" style="float:right;">\
<span aria-hidden="true">×</span></button>\
<span></span>\
</div>\
<div class="modal-body">\
<iframe id="message-iframe-' + message.id + '" srcdoc="<p>Loading...</p>">\
</iframe>\
<div class="modal-footer">\
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>\
<button type="button" class="btn btn-primary reply-button" data-dismiss="modal" data-toggle="modal" data-target="#reply-modal"\
onclick="fillInReply(\'' + reply_to + '\',\'' + reply_subject + '\',\'' + getHeader(message.payload.headers, 'Message-ID') + '\');">Reply</button>\
</div> \
</div>\
</div>\
</div>\
</div>'
);
$('#message-link-' + message.id).on('click', function() {
var ifrm = $('#message-iframe-' + message.id)[0].contentWindow.document;
$('body', ifrm).html(getBody(message.payload));
});
}
function getHeader(headers, index) {
var header = '';
$.each(headers, function() {
if (this.name === index) {
header = this.value;
}
});
return header;
}
function getBody(message) {
var encodedBody = '';
if (typeof message.parts === 'undefined') {
encodedBody = message.body.data;
} else {
encodedBody = getHTMLPart(message.parts);
}
encodedBody = encodedBody.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
return decodeURIComponent(escape(window.atob(encodedBody)));
}
function getHTMLPart(arr) {
for (var x = 0; x <= arr.length; x++) {
if (typeof arr[x].parts === 'undefined') {
if (arr[x].mimeType === 'text/html') {
return arr[x].body.data;
}
} else {
return getHTMLPart(arr[x].parts);
}
}
return '';
}
function sendEmail() {
$('#send-button').addClass('disabled');
sendMessage({
'To': $('#compose-to').val(),
'Subject': $('#compose-subject').val()
},
$('#compose-message').val(),
composeTidy
);
return false;
}
function sendMessage(headers_obj, message, callback) {
var email = '';
for (var header in headers_obj)
email += header += ": " + headers_obj[header] + "\r\n";
email += "\r\n" + message;
var sendRequest = gapi.client.gmail.users.messages.send({
'userId': 'me',
'resource': {
'raw': window.btoa(email).replace(/\+/g, '-').replace(/\//g, '_')
}
});
return sendRequest.execute(callback);
}
function fillInReply(to, subject, message_id) {
$('#reply-to').val(to);
$('#reply-subject').val(subject);
$('#reply-message-id').val(message_id);
}
function sendReply() {
$('#reply-button').addClass('disabled');
sendMessage({
'To': $('#reply-to').val(),
'Subject': $('#reply-subject').val(),
'In-Reply-To': $('#reply-message-id').val()
},
$('#reply-message').val(),
replyTidy
);
return false;
}
function replyTidy() {
$('#reply-modal').modal('hide');
$('#reply-message').val('');
$('#reply-button').removeClass('disabled');
}
function composeTidy() {
$('#compose-modal').modal('hide');
$('#compose-to').val('');
$('#compose-subject').val('');
$('#compose-message').val('');
$('#send-button').removeClass('disabled');
}
</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</body>
</html>

Modal displays strangely with bootstrap framework

On a web page who have many tab, i have a input box who do a search via a ajax call.
If there is no result, i would like to display a modal dialog box.
<div role="tabpanel">
<div class="row">
<div class="span12">
<nav role="navigation" class="navbar navbar-default navbar-right">
<form class="navbar-form" role="search">
<div class="checkbox">
<label>
<input type="checkbox" id="inactiveLodger"> Locataire inactif
</label>
</div>
<div class="input-group">
<input type="text" class="form-control" placeholder="Rechercher" name="srch-term" id="srch-term">
<div class="input-group-btn">
<button id="lodgerSearch" type="button" class="btn btn-default"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</nav>
<div class="modal fade" id="modalEmptyResult">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Résultat de recherche</h3>
</div>
<div class="modal-body">
<p>Aucun résultat ne correspondant à votre requête</p>
</div>
<div class="modal-footer">
Fermer
</div>
</div>
</div>
</div>
...
$('#lodgerSearch').on('click', function (e) {
var inactiveLodger = $('#inactiveLodger').is(':checked');
debugger;
var searchParam = $('#srch-term').val();
var url = "http://localhost:8080/lodgers/search";
if (searchParam != "") {
url = url + "?searchTerm=" + searchParam;
}
if (inactiveLodger == true) {
url = url + "?inactiveLodger=true";
}
jQuery.ajax({
type: "GET",
url: url,
success: function (data, status, jqXHR) {
debugger;
if (data.length == 0) {
$("#lodgerSearchResult").empty();
$('#modalEmptyResult').modal('show');
} else {
$("#lodgerSearchResult").empty().append(template(data));
}
},
error: function (jqXHR, status) {
// error handler
alert("error " + jqXHR + " - " + status);
}
});
// e.preventDefault();
});
Like we can see on the picture, we can see the dialog box, but it's seem transparent.
I created a basic example with similar problem.
https://jsfiddle.net/m7eop6k1/
Strange with jquery 1.9.1 that work... but not with latest release of jquery.

Categories

Resources