I have the following code. It is suppossed to send the formData of title ,tag and description to the controller for uploading.But I keep recieving this error.
Error :
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Multiple Images Upload Using Dropzone</title>
<meta name="_token" content="{{csrf_token()}}" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/dropzone.js"></script>
<style>
.data{
display:none;
}
.dropzone {
width: 98%;
margin: 1%;
border: 2px dashed #3498db !important;
border-radius: 5px;
transition: 0.2s;
}
.dropzone.dz-drag-hover {
border: 2px solid #3498db !important;
}
.dz-message.needsclick img {
width: 50px;
display: block;
margin: auto;
opacity: 0.6;
margin-bottom: 15px;
}
span.plus {
display: none;
}
.dropzone.dz-started .dz-message {
display: inline-block !important;
width: 120px;
float: right;
border: 1px solid rgba(238, 238, 238, 0.36);
border-radius: 30px;
height: 120px;
margin: 16px;
transition: 0.2s;
}
.dropzone.dz-started .dz-message span.text {
display: none;
}
.dropzone.dz-started .dz-message span.plus {
display: block;
font-size: 70px;
color: #AAA;
line-height: 110px;
}
</style>
</head>
<body>
<div class="container">
<form method="GET" enctype="multipart/form-data" class="dropzone" id="dropzone">
<button id='upload'>Upload</button>
#csrf
</form>
<div class='data' ></div>
</div>
<script type="text/javascript">
var title = $('#title').val();
var description = $('#description').val();
max=2
var thumbnail;
Dropzone.options.dropzone = {
maxFiles: max,
autoProcessQueue: false,
uploadMultiple: true,
method:"get",
maxFilesize: 12,
url: '/upload',
init: function() {
var myDropzone = this;
$("#upload").click(function(e) {
// First change the button to actually tell Dropzone to process the queue.
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
this.on("maxfilesexceeded", function(file) {
alert('Max of '+ max + ' files');
this.removeFile(file);
});
this.on("addedfile", function() {
this.on('thumbnail', function(file, thumbnail) {
thumbnail = file.thumbnail;
});
this.on('sending', function (file, xhr, formData) {
// Append all form inputs to the formData Dropzone will POST
var data = $('.dropzone').serializeArray();
$.each(data, function (key, el) {
formData.append(el.title, el.description, el.tags);
});
console.log(formData);
});
var myvar = '<div class="form-group">'+
'<img class="media-object thumbnail" src="'+ thumbnail +'" />'+
'<label for="title">Title</label>'+
'<input type="text" class="form-control" id="title" aria-describedby="title" placeholder="Give your image a title"><br>'+
'<label for="Description">Description</label>'+
'<input type="text" class="form-control" id="description" aria-describedby="Description" placeholder="Describe your image"><br>'+
'<label for="Tags">Tags</label>'+
'<input type="text" class="form-control" id="Tags" aria-describedby="Tags" placeholder="Give your image tags"><br>'+
'<small>Tags are important to let people easily find your image</small><br><br>'+
''
;
$('.data').show();
$('.data').append(myvar);
});
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
timeout: 50000,
processQueue: function(file) {
var name = file.upload.filename;
$.ajax({
headers:
{
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
type: 'POSTg',
url: '{{ url("image/delete") }}',
data: {
title: title,
description:description,
type:"image",
body:"upploaded/img"+filename
},
success: function(data) {
console.log("File has been successfully removed!!");
},
error: function(e) {
console.log(e);
}
});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
},
success: function(file, response) {
console.log(response);
},
error: function(file, response) {
return false;
}
};
</script>
</body>
</html>
And here is MyController:
public function upload(StorePostRequest $request)
{
$title= Post::where('title', $request->input('title'))->first();
if (!$title == null) {
return redirect()->back()->withErrors(['Title Already Exists', 'Title already exists']);
return response()->json(["message" => "Failed","reason" => "Title Already Exists"]);
}
$post = Post::create([
'title' => $request->input('title'),
'body' => $request->input('body'),
'description' => $request->input('description'),
'type' => $request->input('type'),
'user_id' => auth()->id(),
'published_at' => $request->has('draft') ? null : \Carbon\Carbon::now()
]);
}
StorePostRequest.php:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
class StorePostRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return Auth::check();
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required|max:255',
'body' => 'required',
'tags' => 'nullable',
'image' => 'nullable|image|max:2048'
];
}
}
Thanks in advance
Related
The InActive button in the top of the picture, gets displayed properly when it is outside the datatable but doesn't work inside the datatable.
I have added the same code for status column inside the datatable but it displays only a checkbox. How do I get the InActive button inside datatable?
<script type="text/javascript">
$(document).ready(function() {
$.noConflict();
fill_datatable();
function fill_datatable(collegeID = '') {
var table = $('.user_datatable1').DataTable({
order: [
[0, 'desc']
],
processing: true,
serverSide: true,
ajax: {
url: "{{ route('alumni.datatable1') }}",
data: {
collegeID: collegeID
}
},
columns: [{
data: 'id',
name: 'id'
},
{
data: 'name',
name: 'name'
},
{
data: 'status',
name: 'status',
mRender: function(data) {
return ' <input data-id="{{$colleges->id}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $colleges->status ? "checked" : "" }}>'
}
}
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
}
});
$(function() {
$('.toggle-class').change(function() {
var status = $(this).prop('checked') == true ? 1 : 0;
var user_id = $(this).data('id');
$.ajax({
type: "GET",
dataType: "json",
url: '/changeStatus',
data: {'status': status, 'id': id},
success: function(data){
console.log(data.success)
}
});
})
})
</script>
Please Add css.....
CSS
<style>
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
</style>
You can simple put after status....
Toggle switch
{
"data": "id",
render: function(data, type, row, meta) {
$html = '<label class="switch"> <input type="checkbox">
<span class="slider round"></span></label>';
return $html;
}
},
I have gotten stuck on a rather simple aspect of the autosave feature and that is the current status of the action like found on the overview page: https://ckeditor.com/docs/ckeditor5/latest/builds/guides/integration/saving-data.html#demo. But it doesn't look like they actually reference it anywhere (example below).
My html is just:
<textarea class="form-control" name="notes" id="notes">{!! $shipmentShortage->notes !!}</textarea>
My create script is below, the autosave feature works just fine, but the status just isn't there:
<script>
ClassicEditor
.create( document.querySelector( '#notes' ), {
toolbar: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote', 'undo', 'redo' ],
image: {
toolbar: [ 'imageStyle:full', 'imageStyle:side', '|', 'imageTextAlternative' ],
},
autosave: {
save( editor ) {
console.log(editor.getData());
// The saveData() function must return a promise
// which should be resolved when the data is successfully saved.
return saveData( editor.getData() );
}
}
} );
// Save the data to a fake HTTP server (emulated here with a setTimeout()).
function saveData( data ) {
return new Promise( resolve => {
setTimeout( () => {
console.log( 'Saved', data );
$.ajax({
url: '/osd/shortages/update',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
'shortage_id':'{{$shipmentShortage->id}}',
'notes': data,
},
dataType: 'json',
success: function (response) {
console.log('saved');
}
});
resolve();
}, 5000 );
} );
}
// Update the "Status: Saving..." info.
function displayStatus( editor ) {
const pendingActions = editor.plugins.get( 'PendingActions' );
const statusIndicator = document.querySelector( '#editor-status' );
pendingActions.on( 'change:hasAny', ( evt, propertyName, newValue ) => {
if ( newValue ) {
statusIndicator.classList.add( 'busy' );
} else {
statusIndicator.classList.remove( 'busy' );
}
} );
}
</script>
You are absolutely correct. They show us a sexy status updater but don't give us the code for it. Here is what I extracted from the demo page by looking at the page source. This should give you the Status updates as you asked. Let me know if you have any questions.
HTML:
<div id="snippet-autosave">
<textarea name="content" id="CKeditor_Notes">
Sample text
</textarea>
</div>
<!-- This will show the save status -->
<div id="snippet-autosave-header">
<div id="snippet-autosave-status" class="">
<div id="snippet-autosave-status_label">Status:</div>
<div id="snippet-autosave-status_spinner">
<span id="snippet-autosave-status_spinner-label"></span>
<span id="snippet-autosave-status_spinner-loader"></span>
</div>
</div>
</div>
CSS:
<style>
#snippet-autosave-header{
display: flex;
justify-content: space-between;
align-items: center;
background: var(--ck-color-toolbar-background);
border: 1px solid var(--ck-color-toolbar-border);
padding: 10px;
border-radius: var(--ck-border-radius);
/*margin-top: -1.5em;*/
margin-bottom: 1.5em;
border-top: 0;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
#snippet-autosave-status_spinner {
display: flex;
align-items: center;
position: relative;
}
#snippet-autosave-status_spinner-label {
position: relative;
}
#snippet-autosave-status_spinner-label::after {
content: 'Saved!';
color: green;
display: inline-block;
margin-right: var(--ck-spacing-medium);
}
/* During "Saving" display spinner and change content of label. */
#snippet-autosave-status.busy #snippet-autosave-status_spinner-label::after {
content: 'Saving...';
color: red;
}
#snippet-autosave-status.busy #snippet-autosave-status_spinner-loader {
display: block;
width: 16px;
height: 16px;
border-radius: 50%;
border-top: 3px solid hsl(0, 0%, 70%);
border-right: 2px solid transparent;
animation: autosave-status-spinner 1s linear infinite;
}
#snippet-autosave-status,
#snippet-autosave-server {
display: flex;
align-items: center;
}
#snippet-autosave-server_label,
#snippet-autosave-status_label {
font-weight: bold;
margin-right: var(--ck-spacing-medium);
}
#snippet-autosave + .ck.ck-editor .ck-editor__editable {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
#snippet-autosave-lag {
padding: 4px;
}
#snippet-autosave-console {
max-height: 300px;
overflow: auto;
white-space: normal;
background: #2b2c26;
transition: background-color 500ms;
}
#snippet-autosave-console.updated {
background: green;
}
#keyframes autosave-status-spinner {
to {
transform: rotate( 360deg );
}
}
</style>
The rest is just initializing the Editor just like on the demo page here.
ClassicEditor
.create(document.querySelector('#CKeditor_Notes'), {
autosave: {
save(editor) {
return saveData(editor.getData());
}
}
})
.then(editor => {
window.editor = editor;
displayStatus(editor);
})
.catch(err => {
console.error(err.stack);
});
// Save the data to Server Side DB.
function saveData(data) {
return new Promise(resolve => {
setTimeout(() => {
console.log('Saved', data);
SaveDataToDB(data)
resolve();
});
});
}
// Update the "Status: Saving..." info.
function displayStatus(editor) {
const pendingActions = editor.plugins.get('PendingActions');
const statusIndicator = document.querySelector('#snippet-autosave-status');
pendingActions.on('change:hasAny', (evt, propertyName, newValue) => {
if (newValue) {
statusIndicator.classList.add('busy');
} else {
statusIndicator.classList.remove('busy');
}
});
}
i want to sorting data and display the result in the view. I'm using codeigniter framework. What i want is to sorting data using ajax when dropdown values change.
Can someone give me the example code ?
my ajax
<script>
$(document).ready(function() {
$("#selectBerdasar").change(function() {
var key = $(this).val();
console.log(key);
var postdata = {key: key};
var url = '<?php echo site_url('produk/filter/GetFilterJson');?>';
$.post(url, postdata, function(result) {
console.log(result);
if (result) {
var obj = JSON.parse(result);
$('.col-item').empty();
$.each(obj, function(key, line) {
});
} else {
}
});
});
});
my controller
public function doFilter($key) {
$this->load->helper('url');
$this->load->model('filter_model', 'filter');
if ($key == 'termahal') {
$data = $this->filter->getDataMahal($key);
} elseif ($key == 'termurah') {
$data = $this->filter->getDataMurah($key);
} else {
$data = $this->filter->getDataAlfabet($key);
}
return $data;
}
public function GetFilterJson() {
$key = $this->input->post('key');
$data = $this->doFilter($key);
echo json_encode($data);
}
my model
public function getDataMahal($key) {
$this->db->select("*");
$this->db->from("produk");
$this->db->order_by("harga_produk", "desc");
$data = $this->db->get();
return $data->result_array();
}
public function getDataMurah($key) {
$this->db->select("*");
$this->db->from("produk");
$this->db->order_by("harga_produk", "asc");
$data = $this->db->get();
return $data->result_array();
}
public function getDataAlfabet($key) {
$this->db->select("*");
$this->db->from("produk");
$this->db->order_by("nama_produk", "asc");
$data = $this->db->get();
return $data->result_array();
}
here is a simple example. hope this helps..
Ajax
var phone_number = $(this).find('div.number').text();
$("#recipentno").val(phone_number);
$.ajax({
type:"POST",
dataType: 'json',
url:"<?php echo base_url('administrator/get_all_sms/'); ?>",
data: {number: phone_number},
success: function(data) {
//console.log(data);
$(".smsmessage").html("");
console.log(data.total);
for (var i = 0; i < data.total.length; i++) {
if(data.total[i].message_type==1){
$('<div class="col-lg-8 col-lg">'+
'<div class="media">'+
'<div class="" style="border-radius: 25px; background: #4CC1ED; padding: 1px; width: 100%; margin-top: 10px;">'+
'<p style="color: #000000; padding-top: 10px; padding-left: 10px;padding-right: 10px; font-size: 18px;">'+ data.total[i].body+'<i style="font-size: 9px;">'+data.total[i].date_time+'</i></p>'+
'</div>'+
'</div>'+
'</div>').appendTo (".smsmessage");
} else{
$('<div class="col-lg-offset-4 col-lg-8">'+
'<div class="media">'+
'<div class="" style="border-radius: 25px; background: #65CFBF; padding: 1px; width: 100%; height: 50px; margin-top: 10px;">'+
'<p class="sender-img pull-right" style="color: #000000; padding-top: 10px; padding-left: 10px;padding-right: 10px; font-size: 18px;">'+data.total[i].body+'<i style="font-size: 9px;">'+data.total[i].date_time+'</i></p>'+
'</div>'+
'</div>'+
'</div>').appendTo (".smsmessage");
}
}
}
});
Controller
function get_all_sms(){
$pon_number = $this->input->post('number');
$single_sms= $this->admin->get_all_sms_for_number($pon_number);
echo json_encode(array( 'total'=> $single_sms));
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src ="valid.js"></script>
<script type="text/javascript">
$(document).ready(function($){
$("#contact-form").validate({
rules: {
fullName: { //input name: fullName
required: true, //required boolean: true/false
minlength: 5,
},
email: { //input name: email
required: true, //required boolean: true/false
email: true //required boolean: true/false
},
subject: { //input name: subject
required: true, //required boolean: true/false
minlength: 5
},
message: { //input name: message
required: true,
minlength: 1
}
},
messages: { //messages to appear on error
fullName: {
required:"Please put your full name.",
minlength:"C'mon full name please."
},
email: "Enter a valid email.",
subject: {
required: "Whats the topic?",
minlength: ""
},
message: {
required: "What did you want to say?",
minlength: "Please complete your thoughts, then submit."
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
url:"echo/html",
type:"POST",
success: function($){
$("#contact-form").delay(500).fadeOut("slow", function(){
$("#sent").fadeIn("slow");
});
return false;
}
});
}
});
})
</script>
<style type="text/css">
#contact{
padding: 20px;
width: 250px;
background: #FFF;
border: 1px solid #29216d;
position: static;
margin-top:50px;
position: fixed;
z-index: 200;
}
.txt-input,
.input{
color:#aaa;
margin: 3px 0;
font-family: Helvetica;
font-size: 11px;
}
.txt-input{
width: 250px;
}
.input{
width: 200px;
}
.txt-input:focus,
.input:focus{
color:#000;
}
label.error{
float: left;
font-size: 10px;
font-weight: bold;
color:#F0F;
}
.submit{
margin-top:20px;
display: block;
}
#sent{
display:none;
}
</style>
<div id="contact" class="corner-5">
<a class="handle" href="mailto%3Aelan%40trybuch.com">Content</a>
<form id="contact-form" method="post">
<input class="input required error" type="text" name="fullName" title="What shall I call you?"/>
<input class="input required error" type="text" name="email" title="foo#bar.com"/>
<input class="input required error" type="text" name="subject" title="Topic of conversation"/>
<textarea class="txt-input required error" name="message" rows="6"></textarea>
<input class="submit" type="submit" name="submit" value="submit"/>
</form>
<div id="sent">Sucess</div>
</div>
Look at the code above.
All the validators are working fine, but when I fill all the data fields, it doesn't display the success message.
I don't know what I'm doing wrong.
Thanks in advance.
Your submit handler has a problem, it is taking a parameter $ which is overriding the jQuery object in the success callback
submitHandler: function(form) {
$(form).ajaxSubmit({
url:"/echo/html",
type:"GET",
success: function(){
$("#contact-form").delay(500).fadeOut("slow", function(){
$("#sent").fadeIn("slow");
});
return false;
}
});
}
Demo: Fiddle
Newbie with Kendo UI here, thanks for the help. Having a problem with a selected listview inside a grid popup editor window.
It displays and is selectable, but I can't get it to send the selected listview data to the JSON string
the json string sent to the server:
{"blog"=>{"id"=>"", "title"=>"New title", "content"=>"New content", "published"=>"", "img_name"=>""}}
My code, kendo-grid and kendo-listview:
<script type="text/x-kendo-tmpl" id="image_template">
<div class="product">
<img src="/assets/blog/${img_name}" width="100" />
</div>
</script>
<!-- popup editor template -->
<script id="popup_editor" type="text/x-kendo-template">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="title">Title</label>
<div class="controls">
<input type="text" id="title" name="Title" data-bind="value:title">
</div>
</div>
<div class="control-group">
<label class="control-label" for="published">Published</label>
<div class="controls">
<input type="checkbox" id="published" data-bind="checked: published" />
</div>
</div>
<textarea id="editor" name="content" data-bind="value:content"></textarea>
<div id="listView"></div>
<div class="control-group">
<label class="control-label" for="img_name">Image Name</label>
<div class="controls">
<input type="text" id="img_name" name="img_name" data-bind="value: img_name"/>
</div>
</div>
</form>
</script>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "/posts";
var blogimages = [
{ "img_name": "image_one.jpg"},
{ "img_name": "image_two.jpg"},
{ "img_name": "image_three.jpg"},
{ "img_name": "image_four.jpg"},
{ "img_name": "image_five.jpg"}
];
imageSource = new kendo.data.DataSource({
data: blogimages
});
imageSource.read();
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl,
dataType: "json"
},
update: {
url: function(posts) {
return crudServiceBaseUrl + "/" + posts.id;
},
dataType: "json",
contentType: "application/json",
type: "PUT"
},
destroy: {
url: function(posts) {
return crudServiceBaseUrl + "/" + posts.id
},
dataType: "json",
type: "DELETE"
},
create: {
url: crudServiceBaseUrl,
dataType: "json",
contentType: "application/json",
type: "POST"
},
batch:false,
parameterMap: function(posts, type) {
if (type === "create") {
return JSON.stringify({ post: posts });
}
else if(type === "update") {
return JSON.stringify({ post: posts }, replacer);
}
}
},
pageSize: 10,
schema: {
model: {
id: "id",
fields: {
title: { editable: true, defaultValue: "New title" },
content: { editable: true, defaultValue: "New content" },
published: {editable: true},
img_name: {editable: true}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
editable: true,
navigatable: true,
sortable: {
mode: "single",
allowUnsort: false
},
pageable: true,
selectable: "row",
height: 490,
toolbar: ["create"],
editable: {
mode: "popup",
template: $("#popup_editor").html()
},
edit: function(e) {
$("#editor").kendoEditor({
tools: [
"bold",
"italic",
"underline",
"justifyLeft",
"justifyCenter",
"justifyRight",
"justifyFull"
]
});
$("#listView").kendoListView({
dataSource: imageSource,
selectable: "multiple",
change: onChange,
template: kendo.template($("#image_template").html())
}).data("kendoGrid");
},
save: function(e) {
},
columns: [
{ field: "title",title:"Title", width: "25%" },
{ field: "created_at", title:"Created", width: "20%" },
{ field: "updated_at", title:"Updated", width: "20%" },
{ field: "published", title:"Published", width: "10%" },
{ command: ["edit", "destroy"], title: " ", width: "20%" }]
});
function onChange() {
var index = this.select().index();
var dataItem = this.dataSource.at(index);
$('#img_name').val(dataItem.img_name);
}
replacer = function(key, value){
if (key=="id"||key=="created_at"||key=="updated_at"){
return undefined;
}else{
return value;
}
}
});
</script>
<style scoped>
.product
{
float: left;
width: 100px;
height: 60px;
margin: 5px;
padding: 5px;
border: 1px solid #cccccc;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
background-image: none;
cursor: pointer;
overflow: hidden;
}
.product img
{
float: left;
width: 100px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
.k-listview:after
{
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.k-listview
{
border: 0;
padding: 0 0 20px 0;
min-width: 0;
}
</style>
I can successfully send img_name data through the input text
<input type="text" id="img_name" name="img_name" data-bind="value: img_name"/>
But I can't get it to change with onChange function in the listview
Any thoughts on this?