I have a button
<span class="btn btn-primary" id="open-label"><i class="icon-plus icon-white"></i> Add label</span>
which open modal window (http://twitter.github.com/bootstrap/javascript.html#modals)
<div id="ajax-labels"></div>
<div id="labels-modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="header">Add label</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" id="name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="color">Color</label>
<div class="controls">
<input type="text" id="color" name="color" value="#a5f3d4" size="6" class="iColorPicker" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="submit-label"><i class="icon-ok icon-white"></i> Add label</button>
</div>
</div>
<script>
function append_labels() {
$("#ajax-labels").empty();
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "get_labels"
},
success: function (html) {
labels = $.parseJSON(html);
$.each(labels, function () {
$("#ajax-labels").append('<span class="label" id="' + this.id + '" style="background-color: ' + this.color + '">' + this.name + '<i id="edit-label" class="icon-pencil icon-white"></i></span> ');
});
}
});
}
$('span#open-label').click(function () {
$('#labels-modal').modal('show');
$('#labels-modal #submit-label').click(function () {
$('#labels-modal #submit-label').prop('disabled', true);
var name = $('#labels-modal #name').val().trim();
var color = $('#labels-modal #color').val().trim();
if (name != '' || color != '') {
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "add_label",
name: name,
color: color
},
success: function () {
$('#labels-modal').modal('hide');
append_labels();
}
});
} else {
return false;
}
});
});
</script>
After filling labels, user click on "Add label" and jquery send request, after sending, script close modal and refresh (on ajax) labels list. Question - if user quick clicks on "Add label", script send form repeatedly and i responce doubles in database. How I Can prevent this?
Try using one
$('span#open-label').one('click', function () { //...
This will guarantee your modal/ajax function will execute only once.
Disable the form and button on the first click so that the UI does not allow additional clicks. You can do this manually, or use the jQuery Block UI plugin.
Here is another post on how to do this: jquery disable submit button on form submission
Edit:
You are defining a event handler inside of a click handler. So what jQuery is doing is assigning that event handler each time the containing click is fired. So depending on how many times the top level click was executed, will be how many times your AJAX call will fire. Even though it is only 1 click of your button, the previous clicks are the culprit. Extract that click handler definition to outside of the other and you should be good to go.
$('span#open-label').click(function () {
$('#labels-modal').modal('show');
});
$('#labels-modal #submit-label').click(function () {
$('#labels-modal #submit-label').prop('disabled', true);
var name = $('#labels-modal #name').val().trim();
var color = $('#labels-modal #color').val().trim();
if (name != '' || color != '') {
$.ajax({
url: "/ajax",
type: "POST",
cache: false,
data: {
type: "add_label",
name: name,
color: color
},
success: function () {
$('#labels-modal').modal('hide');
append_labels();
}
});
} else {
return false;
}
});
Add this to the click handler
$('span#open-label').click(function () {
if( ($(this).attr('clicked') == '1') ) {
/* do something else then */
return;
}
$(this).attr('clicked', '1');
$('#labels-modal').modal('show');
This way, the next time you click you could show an alert.
If you want to "re-activate" the "open-label", you just do this :
$('span#open-label').attr('clicked', '0');
Related
I use the Modal display field in the Partial View to input data for the User, and use data-url=#url.action("Create") in the main screen to call Modal.
And wrote Autocomplete JavaScript in Partial View.
It works perfectly before using Ajax Post.
But after going through Ajax, the JavaScript cannot be used when it returns because of an error.
How can I make corrections?
Main View
<div id="PlaceHolderHere" data-url="#Url.Action("Create")"></div>
Ajax Code
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
});
});
PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = new FormData(form.get(0));
console.log(sendData);
$.ajax({
url: actionUrl,
method: 'post',
data: sendData,
processData: false,
contentType: false,
cache: false,
success: function (redata) {
console.log(redata);
if (redata.status === "success") {
PlaceHolderElement.find('.modal').modal('hide');
}
else {
var newBody = $('.modal-body', redata);
var newFoot = $('.modal-footer', redata);
PlaceHolderElement.find('.modal-body').replaceWith(newBody);
PlaceHolderElement.find('.modal-footer').replaceWith(newFoot);
}
},
error: function (message) {
alert(message);
}
})
})
})
Partial View of JavaScript part
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script src="~/bootstrap-autocomplete/dist/latest/bootstrap-autocomplete.min.js"></script>
$('#BossName').autoComplete({
resolver: 'custom',
minLength: 2,
formatResult: function (item) {
return {
value: item.value,
text: "[" + item.value + "] " + item.text,
}
},
noResultsText:'There is no matching data, please confirm whether there is data in the company field',
events: {
search: function (qry, callback) {
// let's do a custom ajax call
$.ajax(
'#Url.Action("GetRolesByAutoComplete","Roles")',
{
data: {
'q': qry,
'key': document.getElementById('CompanyCode').value
}
}
).done(function (res) {
callback(res)
});
}
}
});
$('#BossName').on('autocomplete.select', function (evt, item) {
console.log(item);
$('#BossID').val(item.value);
$('#BossName').val(item.text);
});
Partial View of Modal
<div class="modal fade" id="AddEditRoles" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="AddEditRolesLabel">Add New Roles</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form asp-action="Create" id="Edit">
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.RolesCode)</span>
#if (Model != null && Model.RolesCode != null)
{
<input asp-for="RolesCode" class="form-control" readonly />
}
else
{
<input asp-for="RolesCode" class="form-control" autocomplete="off" />
}
<span asp-validation-for="RolesCode" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.Title)</span>
<input asp-for="Title" class="form-control" autocomplete="off" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.CompanyCode)</span>
<input type="text" asp-for="CompanyCode" class="form-control col-md-3" readonly />
<input type="text" id="CompanyName" class="form-control" autocomplete="off"
placeholder="Please type Key word" />
<span asp-validation-for="CompanyCode" class="text-danger"></span>
</div>
<div class="input-group">
<span class="input-group-text">#Html.DisplayNameFor(m => m.BossID)</span>
<input asp-for="BossID" type="text" class="form-control col-md-3" readonly />
<input id="BossName" type="text" class="form-control" autocomplete="off"
placeholder="Please type Key word" />
<span asp-validation-for="BossID" class="text-danger"></span>
</div>
</form>
</div>
<div class="modal-footer">
<div class="text-danger">#Html.ValidationMessage("error")</div>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button id="Save" type="button" class="btn btn-primary" data-save="modal">Save changes</button>
</div>
</div>
</div>
</div>
You send data to the server, but when it fails you replace modal contents.
Replacing HTML destroys everything that was already there, so you wipe everything that was done by your autocomplete plugin.
All you need to do is to initialize autocomplete again:
success: function (redata) {
if (redata.status === "success") {
} else {
var newBody = $('.modal-body', redata);
var newFoot = $('.modal-footer', redata);
PlaceHolderElement.find('.modal-body').replaceWith(newBody);
PlaceHolderElement.find('.modal-footer').replaceWith(newFoot);
// INITIALIZE AUTOCOMPLETE HERE
}
},
When a click event fires, a modal will be presented to end-user and pre-populated with checkboxes.
The issue I am encountering is that at the first click of the button, the pre-populated checkboxes do not render on the modal.
If I exit out of the modal and click the button again, the modal then properly displays the checkboxes.
Why is this happening?
(".changeCheckBoxList").click(buttonClickHandler);
function buttonClickHandler() {
var button = $(this);
swal({
html: true,
title: ""
text: $('#chkbox')
},
function(isConfirm)){
if (isConfirm)
{
$.post({
type: 'POST',
url: '/SomeController/AddCheckboxesData',
datatype: 'json',
data: {
//
}
}).done (function(results) {
});
}
};
$.ajax({
type: 'GET',
datatype: 'html',
url: '/SomeController/SomeActionResult' //This is getting back the correcting data
}).done(function (results) {
//dynamically generating the checkboxes below
$.each(results, function(key, value) {
var div = $('<div><input type="checkbox" value="someValue" + <label for= key></label></div>');
div.find('label').text(results[key].Name);
$('#chkbox').append(div);
});
}
}
<button class="btn btn-default changeCheckBoxList" type="button" data-id="">n</button>
<div class="modal-body">
<form id="chkbox">
<div>
<label for="examplecheckbox"> Click a checkbox</label>
<input type="text" id="">
</div>
</form>
</div>
**Hi, a newbie here on Stack overflow. Uhm my submit button does not read the java script file i created and goes straight to the php file instead of validating the input fields first on the java script file. I'm not quite sure what's wrong i've been stuck here for hour.
I created the files separately. And i put the link to my javascript file at the end of my html file.
Here is my html code:
<!-- Add Student Modal-->
<div class="modal fade" id="addUserModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<form class="form-horizontal" id="submitUserForm" action="action/createUser.php" method="POST">
<div class="modal-header">
<div class="div-action pull pull-right" >
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div> <!-- /div-action -->
<h4 class="modal-title"> Add User</h4>
</div>
<div class="modal-body" style="max-height:650px; overflow:auto;">
<div id="add-user-messages"></div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control" id="full_name" name="full_name" placeholder="Full Name" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<input type="password" class="form-control" onCopy="return false" onCut="return false" id="new_password" name="new_password" placeholder="Password" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<input type="password" class="form-control" onCopy="return false" onCut="return false" id="confirm_password" name="confirm_password" placeholder="Confirm Password" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<select class="form-control" name="level" id="level">
<option value="">~~Level~~</option>
<option value="Admin">Admin</option>
<option value="User">User</option>
</select>
</div>
</div> <!-- /form-group-->
</div> <!-- /modal-body -->
<div class="modal-footer">
<button type="submit" id="createUserBtn" name="createUserBtn" data-loading-text="Loading..." class="btn btn-success"><i class="fa fa-check"></i> Save</button>
<button type="reset" class="btn btn-danger" onClick="resetUserForm()"><i class="fa fa-eraser"></i> Reset Form</button>
</div>
<!-- /modal-footer -->
</form>
<!-- /.form -->
</div>
<!-- /modal-content -->
</div>
<!-- /modal-dailog -->
</div>
<!-- / add modal -->
My Javascript Code:
$("#addUserModalBtn").unbind('click').bind('click', function() {
$("#submitUserForm")[0].reset();
// remove text-error
$(".text-danger").remove();
// remove from-group error
$(".form-group").removeClass('has-error').removeClass('has-success');
$("#submitUserForm").unbind('submit').bind('submit', function() {
// remove text-error
$(".text-danger").remove();
// remove from-group error
$(".form-group").removeClass('has-error').removeClass('has-success');
var full_name = $("#full_name").val();
var username = $("#username").val();
var level = $("#level").val();
var new_password = $("#new_password").val();
var confirm_password = $("#confirm_password").val();
const pasteBox = document.getElementById("#confirm_password");
pasteBox.onpaste = e => {
e.preventDefault();
return false;
};
if(full_name == "") {
$("#full_name").after('<p class="text-danger">Full name field is required.</p>');
$('#full_name').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#full_name").find('.text-danger').remove();
// success out for form
$("#full_name").closest('.form-group').addClass('has-success');
} // /else
if(username == "") {
$("#username").after('<p class="text-danger">Username field is required.</p>');
$('#username').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#username").find('.text-danger').remove();
// success out for form
$("#username").closest('.form-group').addClass('has-success');
} // /else
if(level == "") {
$("#level").after('<p class="text-danger">Please select user level.</p>');
$('#level').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#level").find('.text-danger').remove();
// success out for form
$("#level").closest('.form-group').addClass('has-success');
} // /else
if(new_password == "") {
$("#new_password").after('<p class="text-danger">Password field is required.</p>');
$('#new_password').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#new_password").find('.text-danger').remove();
// success out for form
$("#new_password").closest('.form-group').addClass('has-success');
} // /else
if(confirm_password == "") {
$("#confirm_password").after('<p class="text-danger">Confirm password field is required.</p>');
$('#confirm_password').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#confirm_password").find('.text-danger').remove();
// success out for form
$("#confirm_password").closest('.form-group').addClass('has-success');
} // /else
if(full_name && level && username && new_password) {
var form = $(this);
var formData = new FormData(this);
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success:function(response) {
if(response.success == true) {
// submit loading button
$("#createUserBtn").button('reset');
$("#submitUserForm")[0].reset();
$("html, body, div.modal, div.modal-content, div.modal-body").animate({scrollTop: '0'}, 100);
setTimeout(function(){window.location = window.location}, 1000);
// shows a successful message after operation
$('#add-user-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>');
// remove the mesages
$(".alert-success").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
// reload the manage student table
manageUsersTable.ajax.reload(null, true);
// remove text-error
$(".text-danger").remove();
// remove from-group error
$(".form-group").removeClass('has-error').removeClass('has-success');
} else if(response.success == false) {
// reload the manage member table
manageUsersTable.ajax.reload(null, true);
// reset the form text
$("#submitUserForm")[0].reset();
$("html, body, div.modal, div.modal-content, div.modal-body").animate({scrollTop: '0'}, 100);
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
$('#add-user-messages').html('<div class="alert alert-danger">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
'</div>');
$(".alert-danger").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
} // if
} // /success function
}); // /ajax function
} // /if validation is ok
return false;
}); // /submit product form
}); // /add product modal btn clicked
And my PHP code:
<?php
require_once 'core.php';
$valid['success'] = array('success' => false, 'messages' => array());
if($_POST) {
$full_name = $_POST['full_name'];
$username = $_POST['username'];
$new_password = md5($_POST['new_password']);
$confirm_password = md5($_POST['confirm_password']);
$level = $_POST['level'];
$status = "0";
if($new_password == $confirm_password) {
$sql = "INSERT INTO `users`(`full_name`, `username`, `password`, `level`, `status`) VALUES ('$full_name','$username','$new_password','$level', $status)";
if($connect->query($sql) === TRUE) {
$valid['success'] = true;
$valid['messages'] = "Successfully added user account.";
}else{
return false;
}
}else{
return false;
}
$connect->close();
echo json_encode($valid);
} // /if $_POST
?>
You can use one of two solutions here:
1 Prevent default
You can prevent the submit button from executing the default event action. Instead of doing this:
$("#submitUserForm").unbind('submit').bind('submit', function() {
Do it like this:
$('#submitUserForm').submit(function (event) {
event.preventDefault();
//the rest of the submittion logic goes here
}
2 Button without the submit type
You actually don't have to create a button with the submit type, to send your form data (as you use $.ajax anyway). You can create a simple button with onClick event just like this:
<button onclick="submitForm()"><i class="fa fa-check"></i> Save</button>
And then the whole function that is under the
$("#submitUserForm").unbind('submit').bind('submit', function() {
can be extracted to the new submitForm method
I have some problem with uploading image with bootsrap modal. The problem is that even if I have selected an image, I always get the validation error "Your upload form is empty".
Here's my form sript on view
<div class="modal fade" id="modal_form" role="dialog">
<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>
<h3 class="modal-title">User Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal" enctype="multipart/form-data">
<input type="hidden" value="" name="id_berita"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Judul Berita</label>
<div class="col-md-9">
<input name="judul_berita" placeholder="Judul Berita" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Isi Berita</label>
<div class="col-md-9">
<textarea name="isi_berita" placeholder="Isi Berita Ini" class="form-control"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Foto Berita</label>
<div class="col-md-9">
<input type="file" name="foto_berita" class="form-control">
<span class="help-block"></span>
</div>
</div>
<input type="hidden" value="<?php echo $id_ses; ?>" name="id_user"/>
<input type="hidden" value="<?php $tgl=date("Y-m-d");echo $tgl;?>" name="postdate"/>
<input type="hidden" value="<?php date_default_timezone_set('Asia/Taipei');$jam=date("H:i:s");echo $jam;?>" name="waktu"/>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
the javascript :
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function() {
//datatables
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('databerita/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
});
function add_berita(){
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Berita'); // Set Title to Bootstrap modal title
}
function edit_berita(id){
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('databerita/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id_berita"]').val(data.id_berita);
$('[name="judul_berita"]').val(data.judul_berita);
$('[name="isi_berita"]').val(data.isi_berita);
$('[name="id_user"]').val(data.id_user);
$('[name="postdate"]').val(data.postdate);
$('[name="waktu"]').val(data.waktu);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Berita'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table(){
table.ajax.reload(null,false); //reload datatable ajax
}
function save(){
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('databerita/ajax_add')?>";
} else {
url = "<?php echo site_url('databerita/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
function delete_berita(id){
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('databerita/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
the controller
public function ajax_add()
{
$this->_validate();
$nmfile = "file_".time(); //nama file saya beri nama langsung dan diikuti fungsi time
$config['upload_path'] = './assets/images/'; //path folder
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //type yang dapat diakses bisa anda sesuaikan
$config['max_size'] = '2048'; //maksimum besar file 2M
$config['max_width'] = '1288'; //lebar maksimum 1288 px
$config['max_height'] = '768'; //tinggi maksimu 768 px
$config['file_name'] = $nmfile; //nama yang terupload nantinya
$this->load->library('upload',$config);
if($_FILES['foto_berita']['name']){
if ($this->upload->do_upload('foto_berita')){
$berita = $this->upload->data();
$data = array(
'judul_berita' =>$this->input->post('judul_berita'),
'isi_berita' =>$this->input->post('isi_berita'),
'foto_berita' =>$berita['file_name'],
'id_user' =>$this->input->post('id_user'),
'postdate' =>$this->input->post('postdate'),
'waktu' =>$this->input->post('waktu'),
);
$insert = $this->m_databerita->save($data);
echo json_encode(array("status" => TRUE));
}
}
}
Thank you for your help.
Here is an example on how I used a iFrame in my modal window to upload a picture, by doing it this way I avoided having to reload the page. I do not know if you can do it with ajax, but here is a different approach.
First inside the modal body add the iFrame, notice the src is the view that contains the iframe information:
<iframe id="photo_uploader" src="/image_form" class="picture-upload-iframe"></iframe>
This is the src view for the iframe, the header.php and footer.php are in case you use multiple iframes for different purposes and they share the header and footer:
<? include('header.php');?>
<?= form_open_multipart('items/item_image_upload');?>
<input id="upload-btn" name="userfile" type="file" class="upload" />
<button class="btn btn-primary" name="submit" type="submit" class="btn">
</form>
<? include('footer.php');
Now in your controller, this is just a sample function, you can add all the other fields in the iFrame if you need to submit them when you upload the picture then do what you need to do. I just return true or false just to see if the upload was successful or not.
public function item_image_upload()
{
$data['file_name'] = false;
$data['error'] = false;
$config['allowed_types'] = 'gif|jpg|png';
$config['upload_path'] = $this->img_full;
$config['encrypt_name'] = true;
$config['remove_spaces'] = true;
$this->load->library('upload', $config);
if ( $this->upload->do_upload())
{
$upload_data = $this->upload->data();
return true;
}
return false;
}
In my JavaScript file I created 2 events;
Key-down and click;
When you click on the button or press Enter, the text written in input field is show up in a div text area; This code works for the button click event but doesn't work correctly in key-down event.
HTML code:
<div id="chatarea">
<div id="jqarea">
<div class="chatboxcontent"></div>
</div>
</div>
<div class="chatbox">
<input type="hidden" name="cfrom" id="cfrom" value="<?php echo $cuser; ?>" ></input>
<p><input type="text" name="digit" id="digit" size="50"/></p>
<p><button class="btn" title="send" type="button">
<span>Send</span>
</button>
</p>
</div>
Javascript code
$("#digit").keydown(function(event){
if (event.which == 13) {
filltxtarea($("#digit").val());
}
});
$(".btn").click(function(){
filltxtarea($("#digit").val());
});
function filltxtarea(desctext) {
var uchat = $("#cfrom").val();
//$(".chatboxcontent").append('<div class=chatboxmessage><span class="chatboxmessagefrom">' + uchat + ': </span><span class="chatboxmessagecontent">' + desctext + '</span></div>');
$('#digit').val('');
$('#digit').focus();
$.post('chat.php','action=newrow&message='+desctext,function(data){
if (data==='failed'){alert("error in mysqli")};
});
}
});
function chatHeartbeat(){
$.ajax({
url: 'chat.php?action=chatheartbeat',
dataType: 'json',
cache: false,
success: function(data) {
alert("0");
$.each(data.items, function(i,item){
if(item){
alert("1");
$(".chatboxcontent").append('<div class=chatboxmessage><span class="chatboxmessagefrom">'+item.f+': </span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
}
});
}
});
setTimeout('chatHeartbeat();',1000);
}
When I use click anything work and I can see alert(1) and alert(2) but with key-down it create a new row in the db but I have only alert(0).... How can this be possible??? Any idea????
Did you try prevent default, sometimes with enter key you can have unwanted behavior:
$("#digit").keydown(function(event) {
if (event.which == 13) {
event.preventDefault();
filltxtarea($("#digit").val());
}
});