No response when ValidationException is thrown using Plupload and Symfony3 - javascript

INTRODUCTION:
In order to upload multiple files to the server I am using:
Symfony v3.2.6
OneUpUploaderBundle
OneUpFlysystemBundle
Plupload file uploading library jQuery UI Widget version
NOTE 1:
Please note that: this configuration works for single and multiple file uploads, but it does not return any response when ValidationException is thrown!
NOTE 2:
In order to know that upload of a file finished successfully I added response to part of my UploadListener:
public function onUpload(PreUploadEvent $event)
{
$file = $event->getFile();
$response = $event->getResponse();
$message = [
'error' => 'none'
];
$response->addToOffset($message, array('files'));
}
It gives following response (if there was no error with file upload)
response: {"files":[{"error": "none"}]}
TARGET:
I would like to receive response with corresponding error when ValidationException is thrown.
example:
response: {"files":[{"error": "error code"}]}
PROBLEM:
I am using validator to restrict some uploadable files.
At the moment - files that validator restricts are not uploaded (ValidationException is being thrown). Yet no response is sent to the client/browser on this occasion!
I do not know how to make Plupload and Symfony3 return errors after ValidationException to client/browser.
CODE:
Validation Listener:
<?php
namespace AppBundle\EventListener;
use Oneup\UploaderBundle\Event\ValidationEvent;
use Oneup\UploaderBundle\Uploader\Exception\ValidationException;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
class AllowedMimeTypeValidationListener
{
/**
* #var Container
*/
private $container;
private $file_extension_array = [];
private $file_type_array = [];
private $banned_files = [];
public function __construct(Container $container)
{
$this->container = $container;
}
public function onValidate(ValidationEvent $event)
{
$ultra_helpers = $this->container->get('app.ultra_helpers');
$ultra_text = $this->container->get('app.ultra_text');
array_push($this->file_extension_array, '.gif');
array_push($this->file_extension_array, '.jpg');
array_push($this->file_extension_array, '.jpeg');
array_push($this->file_extension_array, '.png');
array_push($this->file_extension_array, '.zip');
array_push($this->file_extension_array, '.7z');
array_push($this->file_extension_array, '.pdf');
array_push($this->file_extension_array, '.bin');
array_push($this->file_extension_array, '.txt');
array_push($this->file_type_array, 'image/gif');
array_push($this->file_type_array, 'image/jpg');
array_push($this->file_type_array, 'image/jpeg');
array_push($this->file_type_array, 'image/png');
array_push($this->file_type_array, 'application/zip');
array_push($this->file_type_array, 'application/x-7z-compressed');
array_push($this->file_type_array, 'application/pdf');
array_push($this->file_type_array, 'application/octet-stream');
array_push($this->file_type_array, 'text/plain');
array_push($this->banned_files, 'do_not_allow_me_1.txt');
array_push($this->banned_files, 'do_not_allow_me_2.txt');
array_push($this->banned_files, 'do_not_allow_me_3.txt');
$file = $event->getFile();
$file_extension = '.'. $file->getExtension();
$file_mime_type = $file->getMimeType();
$full_file_name = $file->getClientOriginalName()
if (in_array($full_file_name, $this->banned_files))
{
throw new ValidationException('error.file_exists');
}
// Is file mime type the same as extension mime type
$mime_type_position = array_search($file_extension, $this->file_extension_array);
if ($mime_type_position !== false)
{
$mime_type_by_extension = $this->file_type_array[$mime_type_position];
if ($mime_type_by_extension !== $file_mime_type)
{
throw new ValidationException('error.mime_type_mismatch');
}
}
// Is file type not in activated file type array
if (!in_array($file_mime_type, $this->file_type_array))
{
throw new ValidationException('error.forbidden_mime_type');
}
}
}
Twig template with JavaScript:
{% extends 'base.html.twig' %}
{% block stylesheets %}
{{ parent() }}
<link type="text/css" rel="stylesheet" href="{{ asset('js/plupload/jquery-ui-1.12.1/jquery-ui.css') }}" />
<link type="text/css" rel="stylesheet" href="{{ asset('js/plupload/jquery.ui.plupload/css/jquery.ui.plupload.css') }}" media="screen" />
{% endblock %}
{% block content %}
<div id="box-upload">
<div id="uploader">
<p>Your browser doesn't have HTML5 support.</p>
</div>
</div>
{% endblock %}
{% block javascripts %}
<script type="text/javascript" src="{{ asset('js/browserplus/browserplus.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/plupload/plupload.full.min.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/jquery-2.2.4.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/plupload/jquery-ui-1.12.1/jquery-ui.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/plupload/jquery.ui.plupload/jquery.ui.plupload.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/plupload/i18n/lv.js') }}"></script>
<script type="text/javascript">
'use strict';
$(function()
{
var uploader;
uploader = $("#uploader");
uploader.plupload(
{
// General settings
runtimes: 'html5',
url: "{{ oneup_uploader_endpoint('gallery') }}",
multi_selection: true,
// Maximum file size
max_file_size: '5mb',
chunk_size: '5mb',
// Specify what files to browse for
filters: [
{title: "Binary files", extensions: "bin"},
{title: "Image files", extensions: "gif,jpg,jpeg,png"},
{title: "Media files", extensions: "avi"},
{title: "Pdf files", extensions: "pdf"},
{title: "Text files", extensions: "txt"},
{title: "Zip files", extensions: "zip,7z"}
],
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
// Views to activate
views: {
list: true,
thumbs: false, // Show thumbs
active: 'list'
}
});
var $uploader = uploader.plupload('getUploader');
// Add Clear Button
var $button = $("<button>"+ plupload.translate("Clear list") + "</button>").button({icons: {primary: "ui-icon-trash"}}).button("disable").appendTo('.plupload_buttons');
// Clear Button Action
$button.click(function()
{
removeErrorMessages();
$uploader.splice();
$(".plupload_filelist_content").html('');
$button.button("disable");
return true;
});
// Clear Button Toggle Enabled
$uploader.bind('QueueChanged', function ()
{
if ($uploader.files.length > 0)
{
$button.button("enable");
}
else
{
$button.button("disable");
}
});
// Clear Button Toggle Hidden
$uploader.bind('StateChanged', function ()
{
if ($uploader.state === plupload.STARTED)
{
$button.hide();
}
else
{
$button.show();
}
});
// Clear Button Toggle Hidden
$uploader.bind('Browse', function ()
{
removeErrorMessages();
$uploader.splice();
});
$uploader.bind('FileUploaded', function(up, file, info)
{
var response;
response = jQuery.parseJSON(info.response);
console.log("-- next is response --");
console.log(response);
up.trigger("error", {message: "Fails: "+ file.name +" jau atrodas šajā mapē!<br> Augšupielādējamais fails <i>netika</i> saglabāts!", code: 12345, details: "Testing errors"});
$("#"+ file.id).addClass("duplicateFile");
});
function removeErrorMessages()
{
$(".ui-state-error").remove();
}
});
</script>
{% endblock %}
UPDATE
Added current code to the question
PluploadErrorHandler.php
<?php
namespace Oneup\UploaderBundle\Uploader\ErrorHandler;
use Exception;
use Oneup\UploaderBundle\Uploader\Response\AbstractResponse;
class PluploadErrorHandler implements ErrorHandlerInterface
{
public function addException(AbstractResponse $response, Exception $exception)
{
$message = $exception->getMessage();
$response->addToOffset(array('error' => $message), array('files'));
}
}
errorhandler.xml
<?xml version="1.0" encoding="utf-8" ?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<parameters>
<parameter key="oneup_uploader.error_handler.noop.class">Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler</parameter>
<parameter key="oneup_uploader.error_handler.blueimp.class">Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler</parameter>
<parameter key="oneup_uploader.error_handler.dropzone.class">Oneup\UploaderBundle\Uploader\ErrorHandler\DropzoneErrorHandler</parameter>
<parameter key="oneup_uploader.error_handler.plupload.class">Oneup\UploaderBundle\Uploader\ErrorHandler\PluploadErrorHandler</parameter>
</parameters>
<services>
<service id="oneup_uploader.error_handler.noop" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.blueimp" class="%oneup_uploader.error_handler.blueimp.class%" public="false">
<argument type="service" id="translator"/>
</service>
<service id="oneup_uploader.error_handler.dropzone" class="%oneup_uploader.error_handler.dropzone.class%" public="false" />
<service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.plupload.class%" public="false" />
<service id="oneup_uploader.error_handler.fineuploader" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.uploadify" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.yui3" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.fancyupload" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.mooupload" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.custom" class="%oneup_uploader.error_handler.noop.class%" public="false" />
</services>
</container>
QUESTION:
What am I missing?

Sorry previous version was incorrect.
OneupUploaderBundle catches exceptions in a controller and pass them to error_handler service.
class PluploadController extends AbstractChunkedController
{
public function upload()
{
...
foreach ($files as $file) {
try {
$chunked ?
$this->handleChunkedUpload($file, $response, $request) :
$this->handleUpload($file, $response, $request)
;
} catch (UploadException $e) {
$this->errorHandler->addException($response, $e);
}
}
return $this->createSupportedJsonResponse($response->assemble());
}
You should check which error handler is used for your application. Looks like by default for Plupload the bundle set up NoopErrorHandler which does nothing with your exception.
Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler
public function addException(AbstractResponse $response, Exception $exception)
{
// noop
}
errorhandler.xml
<service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.noop.class%" public="false" />
To get Response of desired shape you should set up BlueimpErrorHandler or to define a custom handler.
Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler
public function addException(AbstractResponse $response, Exception $exception)
{
$message = $this->translator->trans($exception->getMessage(), array(), 'OneupUploaderBundle');
$response->addToOffset(array('error' => $message), array('files'));
}
OT: Using exceptions in the validator that way will bring bad experience to a user. The user should see all errors with an uploaded file not just first one. You should collect all errors and then throw an exception. For example:
...
if (in_array($full_file_name, $this->banned_files))
{
throw new ValidationException('error.file_exists');
}
$errors = [];
// Is file mime type the same as extension mime type
$mime_type_position = array_search($file_extension, $this->file_extension_array);
if ($mime_type_position !== false)
{
$mime_type_by_extension = $this->file_type_array[$mime_type_position];
if ($mime_type_by_extension !== $file_mime_type)
{
$errors[] = 'error.mime_type_mismatch';
}
}
// Is file type not in activated file type array
if (!in_array($file_mime_type, $this->file_type_array))
{
$errors[] = 'error.forbidden_mime_type';
}
if (empty($errors)) {
throw new ValidationException(implode(', ', $errors));
}
...

Related

Add a download functionality in django change view

I already added a button alongside the save buttons for my django change view:
{% extends 'admin/change_form.html' %}
{% load static %}
{% load i18n %}
{% block submit_buttons_bottom %}
<div class="submit-row">
<input type="submit" value="Download" id="download_profile" name="_continue">
<input type="submit" value="{% trans 'Save' %}" class="default" name="_save">
<input type="submit" value="{% trans 'Save and add another' %}" name="_addanother">
<input type="submit" value="{% trans 'Save and continue editing' %}" name="_continue">
<!-- inmport script -->
<script src="{% static '/js/downloadData.js' %}"></script>
<script src="{% static '/js/collapsibleSection.js' %}"></script>
<script src="{% static '/js/investmentAdminScript.js' %}"></script>
{% endblock %}
and I already started adding the script to retrieve individual data per row to download them.
'use strict';
window.addEventListener('load', () => {
const downloadButton = document.querySelector('#download_profile');
downloadButton.addEventListener('click', e => {
if (!confirm('Data will be saved before downloading. Are you sure you want to continue?')) {
e.preventDefault();
return;
}
// get module
const fieldsets = document.querySelectorAll('fieldset');
fieldsets.forEach(thisFieldset => {
const dataRows = thisFieldset.querySelectorAll('.form-row');
dataRows.forEach(dataRow => {
// retrieve each input field and add a download to .xlsx function
});
});
});
});
However, it gets complicated very fast. Is there a better way to do this?
Found a single JS file that allows you to format .xlsx files and start a download with one function
https://github.com/egeriis/zipcelx
Since you're using django, download the "standalone.js" file and add it to your static files. Reference it in your template in a script tag. Now you'll have access to the "zipcelx()" function
Here's a "getting started" example I made
const config = {
filename: "practice-file",
sheet: {
data: [
// Row 1
[
{value: "row1 value1",type:"string"},
{value: "1000",type: 'number'}
],
// Row 2
[
{value: "row2 value1", type: 'string'},
{value: "row2 value2", type: "string"}
]
]
}
}
// call zipcelx to immediately start the download in client's browser
zipcelx(config)
Example of the File Generated
Don't know how large your data sets are, might get tedious with having to format your data in such a way. Some helper functions should do the trick if that became a problem.
Hope this helped!

how can i fetch a file that i have already upload and i want to delete it and replace it using bootstrap file input

i want to fetch the file based on my applications_id and i want to see it in the bootstrap file input and i want to delete it and replace with a new file. how can i do it. below is what i have tried .can anyone help me .i am stuck.
this is my contoller function SoleProprietorController.php
public function uploadImages(Request $request, $applications_id)
{
$applications = new Applications;
// $KRAPIN = Input::get('KRA_unique_field');
$applications_id = Input::get('applications_id_unique_field');
if ($request->hasFile('breg_cert')) {
if ($request->file('breg_cert')->isValid()) {
// request()->breg_cert->move(public_path('breg_cert'), $imgName);
// $imgName = basename($request->breg_cert->store(public_path('breg_cert')));
$imgName = basename($request->breg_cert->move(public_path('breg_cert')));
$applications->breg_cert = $imgName;
}
return response()->json(['uploaded' => '/breg_cert/'.$imgName]);
}
}
this my web.php
Route::post('/uploadImages/{applications_id}', 'SoleProprietorController#uploadImages')->name('home');
this is my bootstrap file in my blade
<div class="col-md-4 mb-3">
<label for="validationServer023">Upload Business Registration Document</label>
<div class="form-group">
<div content="{{ csrf_token() }}" class="input-group input-file" name="Fichier1">
<input id="file-0a" name="breg_cert" value="" class="file" accept="text" type="file"> <br />
</div>
</div>
</div>
<script>
$("#file-0a").fileinput({
initialPreview: [
"<img src='/images/php' class='file-preview-image'>",
],
showUpload: true,
showRemove: true,
showCaption: true,
showPreview: true,
showClose: false,
autoOrientImage: true,
showUploadedThumbs: false,
uploadAsync: false,
uploadUrlThumb: false,
deleteUrl: "/public/KFS_Business_Registration_Certificates",
uploadUrl: "/uploadImages/{applications_id}",
// dataUrl: "/breg_cert/",
// uploadUrl: '/public/KFS_Business_Registration_Certificates', // you must set a valid URL here else you will get an error
theme: 'fa',
uploadExtraData: function() {
return {
_token: "{{ csrf_token() }}",
};
},
allowedFileExtensions: ['jpg', 'png', 'gif', 'pdf', 'jpeg'],
overwriteInitial: false,
maxFileSize: 500,
maxFilesNum: 10,
//allowedFileTypes: ['image', 'video', 'flash'],
slugCallback: function (filename) {
return filename.replace('(', '_').replace(']', '_');
}
});
</script>
1.Use code like this to store uploaded file and associate it with your Applications
if ($request->hasFile('breg_cert')) {
if ($request->file('breg_cert')->isValid()) {
$imgName = basename($request->breg_cert->store(public_path('breg_cert')));
$applications->breg_cert = $imgName;
}
}
https://laravel.com/docs/5.8/requests#storing-uploaded-files
To store an uploaded file, you will typically use one of your configured filesystems. The UploadedFile class has a store method which will move an uploaded file to one of your disks, which may be a location on your local filesystem or even a cloud storage location like Amazon S3.
The store method accepts the path where the file should be stored relative to the filesystem's configured root directory. This path should not contain a file name, since a unique ID will automatically be generated to serve as the file name.
To handle delete/replace create a corresponding controller method and POST route and then provide the route to deleteUrl option.
In the above method check the filename associated and unlink it. (actual code depends on what dd($request); output)
To show stored image as preview add option to $("#file-0a").fileinput({
initialPreview: [
"<img src='/images/path-to.jpg' class='file-preview-image'>",
],

CSS/JS Image on-click change synchronized on multiple devices

I wanted to ask if it would be possible to do some script or css style for the fact that once I click on the image it will change to another. I found a lot like this, but I need it a little differently, I need to see the picture changed on one device when I click the picture on another device.
In the code I have an image type input and after clicking on the input I need to change the picture and remember the already changed value. So when I open the page on the new device, the image has already been changed.
<form method="get">
<input type="image" class="switch_img" src="switch_off.png" value="Zapnout" name="on1">
</form>
(The program works like switching off and on of LEDs. And I want the clicker to make the "animation" of the switch.)
I have the variables stored in the txt file in Raspberry, here is the part of the code that could theoretically be connected:
$fileName = __DIR__.'/txt/led2.txt';
if (!file_exists($fileName) || (file_get_contents($fileName) !== '1' && file_get_contents($fileName) !== '0')) {
file_put_contents($fileName, '1');
}
if (isset($_GET['on2']) && file_get_contents($fileName) === '1') {
shell_exec("/usr/local/bin/gpio -g write 15 1");
file_put_contents($fileName, '0');
}
else if (isset($_GET['on2']) && file_get_contents($fileName) === '0') {
shell_exec("/usr/local/bin/gpio -g write 15 0");
file_put_contents($fileName, '1');
}
Thanks for your help!
Projects like Vue, Vuetify and Axios make it easy to build out what you want with straightforward syntax, in just a few lines of "javascript".
<!DOCTYPE html>
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet">
<link href="https://unpkg.com/vuetify/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
<div id="app">
<v-app>
<v-content>
<v-container>
<h4>My Switch/s</h4>
<v-alert type="error" :value="error">
{{ error }}
</v-alert>
<v-card v-for="(item, index) in switches" :key="index">
<v-card-title primary-title>
<div>
<div class="headline"></div>
<span class="grey--text">{{ item.name }}</span>
</div>
</v-card-title>
<v-card-text>
<v-switch v-model="item.state" :label="item.state ? 'On' : 'Off'" color="success" hide-details #click="setState(item)"></v-switch>
</v-card-text>
</v-card>
</v-container>
</v-content>
</v-app>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuetify/dist/vuetify.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
//
var vm = new Vue({
el: '#app',
data: () => ({
error: false,
pollId: 0,
switches: [{
name: 'LED 1',
state: false
}
]
}),
beforeDestroy: function() {
clearInterval(this.pollId);
},
mounted: function() {
this.getState()
this.poll()
},
methods: {
poll() {
clearInterval(this.pollId)
this.pollId = setInterval(() => {
this.getState()
}, 2000)
},
async getState() {
try {
const response = await axios.get('/switch.php')
this.switches = response.data
} catch (error) {
this.error = error
}
},
async setState(item) {
item.state = !item.state
try {
await axios.post('/switch.php', item)
} catch (error) {
this.error = error
}
}
}
});
</script>
</body>
</html>
Then the PHP part (switch.php):
<?php
$switches = file_get_contents('switches.json');
// handle toggle
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// get json body
$body = (array) json_decode(file_get_contents('php://input'), true);
// toggle the switch
shell_exec('/usr/local/bin/gpio -g write 15 '.intval(!empty($body['state'])));
// set its current state
if (isset($switches[$body['name']])) {
$switches[$body['name']]['state'] = $body['state'];
} else {
$switches[$body['name']] = $body;
}
// save
file_put_contents('switches.json', json_encode($switches, JSON_PRETTY_PRINT));
header('HTTP/1.1 204 No content');
} else {
header('Content-Type: application/json');
echo json_encode($switches);
}
Untested but should point you in the right direction.

Django Ajax POST empty Error 500

I am trying to let the user select x and y coordinates from an image using cropper.js and pass the data with using ajax to the next view. I am using Django 1.9.4. I am also not really practiced with Javascript, the Javascript part is not written by me.
Using the Firefox Dev Tools Network Tab I seem to get a 500 Internal Server Error. In the Dev Tools view the request has the needed JSON data. However Django does not seem to work the request properly. Why?
Relevant part from views.py:
def render_stl(request):
print("Got to STL render")
if request.method == 'POST':
print("BELOW DATA")
print(request.POST) # <QueryDict: {}>
print(request.is_ajax()) # False
print(request.POST.__dict__) # {'_encoding': 'utf-8', '_mutable': False}
# This is old from a former version, but should be updated if ajax works
x_start = request.POST.get("x_start")
z_start = request.POST.get("z_start")
x_end = request.POST.get("x_end")
z_end = request.POST.get("z_end")
print(x_start, z_start, x_end, z_end)
run_stl_render(x_start, z_start, x_end, z_end)
# os.chdir(settings.MEDIA_ROOT)
stl_file = open(settings.MEDIA_ROOT + "/mySTL.stl", "r")
django_file = File(stl_file)
return render(request, 'img_crop/render_stl.html', {'django_file': django_file})
urls.py:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^render_img$', views.upload_file, name='render_img'),
url(r'^render_stl$', views.render_stl, name='render_stl'),
url(r'^download_stl$', views.download_stl, name='download_stl'),
# url(r'^media/mySTL.stl', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
]
Javascript (the csrftoken is defined in another function):
sendDataOfCroppedImage = function(dataOfCroppedImage) {
// var data = 'data : [' + JSON.stringify(dataOfCroppedImage) + ']';
var data_s = JSON.stringify(dataOfCroppedImage);
console.log('data',data_s);
$.ajax({
async: true,
crossDomain: true,
method: 'POST',
data: data_s,
dataType: 'json',
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest',
'content-type': 'application/json',
'cache-control': 'no-cache',
'X-CSRFToken': csrftoken
},
url: 'render_stl',
success: function () {
console.log('sendDataOfCroppedImage okay');
}
});
},
The template:
<html>
{% load staticfiles %}
<head>
<title>
Your rendered image
</title>
<script src="{% static 'img_crop/js/jquery-3.2.1.js' %}"></script>
<script src="{% static 'img_crop/js/cookie.js' %}"></script>
<script src="{% static 'img_crop/js/cropper.js' %}"></script>
<link href="{% static 'img_crop/css/cropper.css' %}" rel="stylesheet">
<style>
#image {
max-width: 100%;
}
</style>
</head>
<body>
<h1>Hier ist das generierte Bild aus Ihrer Welt!</h1>
<h2>Wählen Sie nun Ihren Bereich aus: </h2>
<div style="overflow: hidden; width: 400px; height: calc(400px / 16 * 9);">
<div>
<img id="image" src="{% static "img_crop/MC2px.png" %}" alt="Rendered image"/>
</div>
</div>
<button id="getDataBtn" class="button get-data">Submit Choice</button>
request.POST is only for form-encoded data. If you are sending json encoded data then you should access request.body instead.
data = json.loads(request.body.decode('utf-8'))
If you get a 500 error with DEBUG=True, then you should be able to see the traceback using your browser dev tools. If DEBUG=False, then look in your logs or the error email sent to the site admins.

laravel auto complete Text View

I am using Laravel 5.2.
here is my code
//for header
<head>
<script type="text/javascript" src="{{ URL::asset('src/js/jquery-1.10.2.js') }}"></script>
<script type="text/javascript" src="{{ URL::asset('src/js/jquery-ui.js') }}"></script>
<link rel="stylesheet" href="{{ URL::to('src/css/jquery-ui.css') }}">
</head>
//body
<div class="col-sm-6 feature" >
<div class="ui-widget">
<label for="skills">Skills: </label>
<input type="text" class="search_keyword" id="skills" placeholder="Search.." name="skills" />
</div>
<script>
$(function() {
$( "#skills" ).autocomplete({
source: "{{URL::route('auto')}}"
//source: ["a","b"]
});
});
</script>
</div><!-- end feature -->
//route
Route::get('/', function () {
return view('welcome');
});
Route::get('/auto', [
'uses' => 'SearchController#AutoSug',
'as' => 'auto'
]);
//controller
class SearchController extends Controller
{
public function AutoSug()
{
$auto_s = DB::table('skills')
->pluck('skill');
return response()->json($auto_s);
}
}
Now problem is when I browse manually the link {{URL::route('auto')}} which says as here json view
So the problem is it does not give as it should be see here
main view
But if I change the code "{{URL::route('auto')}}" to source: ["a","b"]. It outputs properly. So where might be the problem ?
So here is the solution.
For javascript please write as follows
$(function()
{
$( "#q" ).autocomplete({
source: "{{URL('auto')}}",
minLength: 1,
select: function(event, ui) {
$( "#q" ).val(ui.item.value);
}
});
});
For controller please add as follows
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use App\Product;
use DB;
class SearchController extends Controller
{
public function autoComplete()
{
$term = Input::get('term');
$results = array();
$queries = DB::table('skills')
->where('skill', 'LIKE', '%'.$term.'%')
->take(9)->get();
foreach ($queries as $query)
{
$results[] = [ 'id' => $query->ID, 'value' => $query->skill];
}
return response()->json($results);
}
}
The problem was in controller it was getting null value for get variable and query builder was returning all the result from the database.I have added a library and associate variable as follows and solved the issue.
use Illuminate\Support\Facades\Input;
$term = Input::get('term');
Hope it will help others for same issue.
I hope the following links will be helpful.
https://gist.github.com/imranismail/10200241?signup=true
https://gist.github.com/manoj-nandakumar/11beb90916dfbdc6af7a

Categories