I am using dropzone file upload, when I return success / error from controller, how do I show it on my view file..
View file ,
<div class="box-body">
#if ( $errors->count() > 0 )
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{{ $message = 'Please select csv file only.' }}
</div>
#endif
{!! Form::open([ 'url' => 'admin/reports','class' => 'dropzone', 'id' => 'reportfile' ]) !!}
{!! csrf_field() !!}
<div class="col-md-12">
<h3 style="text-align : center">Select File</h3>
</div>
<button type="submit" class="btn btn-primary">Upload Report</button>
{!! Form::close() !!}
</div>
Controller Code
if ($request->hasFile('file')) {
$file = Input::file('file');
$validator = Validator::make(
[
'file' => $file,
'extension' => strtolower($file->getClientOriginalExtension()),
], [
'file' => 'required',
'extension' => 'required|in:csv',
]
);
if ($validator->fails()) {
return Response::json('error', 400);
}
JS Code
<script>
window.onload = function () {
Dropzone.options.reportfile = {
paramName: "file",
maxFilesize: 2,
error: function (file, response) {
alert('hiii')
},
init: function () {
this.on("addedfile", function (file) {
alert("Added file.");
});
},
accept: function (file, done) {
alert('hi')
if (file.name == "justinbieber.jpg") {
done("Naha, you don't.");
}
}
};
};
</script>
Not even alert is working...any help is much appreciated..Thanks
You should listen the events, and trigger whether it is success or not
Dropzone.options.uploadWidget = {
init: function() {
this.on('success', function( file, resp ){
alert("Success");
});
},
...
};
Note : You can have the other breakpoints as suggested here
Related
I have 2 modal that each have a grecaptcha. I load the script once the first modal is opened and render the captcha for that specific modal afterwards. This is working as expected. But once i submit the form with the captcha, i get the following error:
Uncaught Error: Invalid reCAPTCHA client id: 1
This is the JS code of the captcha render
var grecaptcha_contact = 0;
var grecaptcha_newsletter = 0;
function renderCaptcha(grecaptchatype) {
// Render Google Captcha
function renderCall(grecaptchatype) {
var captcha = grecaptcha.render(grecaptchatype, {
'sitekey': 'SITEKEY_censored',
'theme': 'light'
});
}
// Check if Google Captcha already rendered
if(grecaptchatype === 'g-recaptcha-newsletter'){
if(grecaptcha_newsletter !== 0){
return false;
}
else{
// Render Google Captcha
renderCall(grecaptchatype);
grecaptcha_newsletter++;
}
}
else if(grecaptchatype === 'g-recaptcha-contact'){
if(grecaptcha_contact !== 0){
return false;
}
else{
// Render Google Captcha
renderCall(grecaptchatype);
grecaptcha_contact++;
}
}
}
// load google captcha script on show modal newsletter & contact us
$('#newsletterModal').on('shown.bs.modal', function () {
if(window.grecaptcha) {
renderCaptcha('g-recaptcha-newsletter');
}
else{
var attempts = 0;
$.getScript('https://www.google.com/recaptcha/api.js')
.done(function() {
var setIntervalID = setInterval(function() {
if (window.grecaptcha) {
clearInterval(setIntervalID);
renderCaptcha('g-recaptcha-newsletter');
return false;
}
else if (attempts >= 100) {
clearInterval(setIntervalID);
return false;
}
attempts++;
}, 100);
});
}
});
$('#contactModal').on('shown.bs.modal', function () {
if(window.grecaptcha) {
renderCaptcha('g-recaptcha-contact');
}
else{
var attempts = 0;
$.getScript('https://www.google.com/recaptcha/api.js')
.done(function() {
var setIntervalID = setInterval(function() {
if (window.grecaptcha) {
clearInterval(setIntervalID);
renderCaptcha('g-recaptcha-contact');
return false;
}
else if (attempts >= 100) {
clearInterval(setIntervalID);
return false;
}
attempts++;
}, 100);
});
}
});
This is the Newsletter Form:
<button aria-label="Newsletter" type="button" class="newsletterbutton" data-toggle="modal"
data-target="#newsletterModal">#lang('footer.blade.newsletter')</button>
<div class="modal fade" id="newsletterModal" tabindex="-1" role="dialog" aria-labelledby="newsletterModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<div class="modal-title" id="newsletterModalLabel">#lang('footer.blade.receive_newsletter')</div>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{{ Form::open(['id' => 'newsletterform']) }}
{{ csrf_field() }}
<div class="modal-body">
<div class="alert"></div>
<div class="form-group">
{{ Form::label('newsletter_email', __('footer.blade.contact.email'), ['class' => 'col-form-label']) }}
{{ Form::email('newsletter_email', '', ['required', 'class' => 'form-control']) }}
</div>
<div class="row form-group">
<div class="col-sm-12 acceptrules">
{{ Form::checkbox('acceptrules', 'value', null, ['id' => 'acceptrules', 'required']) }}
<label for="acceptrules" class="control-label">
#lang('add_app.blade.acceptrules')<a class="privacypolicy_link" target="_blank" href="{{ route('privacy-policy') }}">#lang('add_app.blade.acceptrules_link')</a>#lang('add_app.blade.acceptrules_link2')
</label>
</div>
</div>
<div class="form-group g-recaptcha-div">
<div class="g-recaptcha-newsletter g-recaptcha-count" id="g-recaptcha-newsletter"></div>
#if($errors->has('g-recaptcha-response'))
<span>{{$errors->first('g-recaptcha-response')}}</span>
#endif
</div>
</div>
<div class="modal-footer modal-footer-recaptcha">
{{ Form::submit(__('footer.blade.apply_newsletter'), ['class' => 'btn btn-primary']) }}
{{ Form::button(__('footer.blade.close_newsletter'), ['class' => 'btn btn-secondary', 'data-dismiss' => 'modal']) }}
</div>
{{ Form::close() }}
</div>
</div>
</div>
I'm not sure but i think the captcha was working before. I'm not sure if i changed something in the code which broke it or something else that broke it (server/laravel configs). Someone has an idea where to go from here?
I checked on my php code and the error appears here in the captcha.php:
public function passes($attribute, $value)
{
$client = new Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify',
[
'form_params' => [
'secret' => env('CAPTCHA_SECRET', false),
'remoteip' => request()->getClientIp(),
'response' => $value
]
]
);
$body = json_decode((string)$response->getBody());
return $body->success;
}
The getbody() response if success=false
The $attribute is g-recaptcha-response and the $value is a long key probably the public key encrypted.
The secret form_params seems false all the time. I'm not sure why is that, my env file has the captcha_secret set. I tried it with my secret key inside this function instead which did it. So there seems to be something wrong with my env secret key call. Maybe a caching problem or so, will try to figure it out myself from here.
I am developing an application and i want to upload a picture using Ajax with symfony 3.4. Sorry if i am missing anything because i am new to AJAX. I am following the step from https://codepen.io/dsalvagni/pen/BLapab
I am getting the 200 response from symfony but the files doesnt upload.
Entity:
/**
* #ORM\Column(type="string", length=255)
* #var string
*/
private $image;
/**
* #Vich\UploadableField(mapping="profile_image", fileNameProperty="image")
* #var File
*/
private $imageFile;
Here is my controller:
public function testAction(Request $request)
{
$testEntry = new Test();
$form = $this->createForm(TestType::class, $testEntry);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $testEntry->getImageFile();
$fileName = md5(uniqid()) . '.' . $file->guessExtension();
$photoDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/images';
$file->move($photoDir, $fileName);
$testEntry->setImage($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($testEntry);
$em->flush();
if ($request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'Success!', 'success' => true), 200);
}
if ($request->isMethod('POST')) {
return new JsonResponse(array('message' => 'Invalid form', 'success' => false), 400);
}
return $this->redirect($this->generateUrl('homepage'));
}
return $this->render('#Alumni/Default/test.html.twig',
['form' => $form->createView()]);
}
and here is my html.twig
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_row(form.name) }}
<div class="profile">
<div class="photo">
{{ form_widget(form.imageFile, {'attr': {'class': 'file-upload'}}) }}
<div class="photo__helper">
<div class="photo__frame photo__frame--circle">
<canvas class="photo__canvas"></canvas>
<div class="message is-empty">
<p class="message--desktop">Drop your photo here or browse your computer.</p>
<p class="message--mobile">Tap here to select your picture.</p>
</div>
<div class="message is-loading">
<i class="fa fa-2x fa-spin fa-spinner"></i>
</div>
<div class="message is-dragover">
<i class="fa fa-2x fa-cloud-upload"></i>
<p>Drop your photo</p>
</div>
<div class="message is-wrong-file-type">
<p>Only images allowed.</p>
<p class="message--desktop">Drop your photo here or browse your computer.</p>
<p class="message--mobile">Tap here to select your picture.</p>
</div>
<div class="message is-wrong-image-size">
<p>Your photo must be larger than 350px.</p>
</div>
</div>
</div>
<div class="photo__options hide">
<div class="photo__zoom">
<input type="range" class="zoom-handler">
</div><i class="fa fa-trash"></i>
</div>
<button type="button" id="uploadBtn">Upload</button>
</div>
</div>
{{ form_row(form.submit, { 'label': 'Submit me' }) }}
{{ form_end(form) }}
here is my route
test:
path: /test
defaults: {_controller: AlumniBundle:Default:test}
here is my js
$(function() {
/**
* DEMO
*/
var p = new profilePicture('.profile', null,
{
imageHelper: true,
onRemove: function (type) {
$('.preview').hide().attr('src','');
},
onError: function (type) {
console.log('Error type: ' + type);
}
});
$('#uploadBtn').on('click', function() {
var image = p.getAsDataURL();
$.post("/test", { image: image });
});
and i am getting 200 response but i cannot locate the file:
Many thanks in advance for your help
It won't upload because your function isn't sending any file.
It's just sending the file name at most.
The Function
function ajaxSubmit(node) {
$.ajax({
type: node.attr("method"), // Method on form tag
url: node.attr("action"), // Action on form tag
enctype: "multipart/form-data", //needed to upload files
data: new FormData(node[0]), // The form content
processData: false,
contentType: false,
cache: false
}).done(function(response, status, xhr) {
console.info(response);
}).fail(function(request, status, error) {
console.error(request);
console.error(status);
console.error(error);
});
}
The Action
$(body).on("submit", ".ajs", function(e) {
e.preventDefault(); // Prevent default HTML behavior
ajaxSubmit($(this)); //Handle submit with AJAX
});
The View
// Add 'ajs' class to forms that should be submited with AJAX
{{ form_start(form, {'class': 'ajs'}) }}
I am trying to submit a form using ajax so my page will not do a full page reload rather only the form should change to show any errors. I have tried many options from the web with no luck. This here is the best help I have seen, but it doesn't give the solution. Note I am using laravel version 5.3.10.
Here is my code:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$('#footer-form').click(function () {
//event.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost/ensignhospital/mail',
data: $('form#footer-form').serialize(),
dataType: 'html'
})
.done(function (data) {
console.log(data);
});
});
});
</script>
Laravel Route:
Route::group(['before' => 'guest'], function () {
/*
* CSRF Protection
*
* */
Route::group(['before' => 'csrf'], function () {
Route::post('/ensignhospital/mail', [
'as' => 'mail',
'uses' => 'HomeController#postSendMail'
]);
});
});
Laravel controller:
public function postSendMail(Request $request)
{
if($request->ajax()){
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'message' => 'required',
'g-recaptcha-response' => 'required|captcha'
]);
if($validator->fails()){
return redirect()->back()
->withErrors($validator)
->withInput(Input::all());
}else{
return View('passed');
}
}else{
return View('fail');
}
}
Form:
{!! Form::open(['route' => 'mail', 'method' => 'post', 'role' => 'form', 'id' => 'footer-form']) !!}
<div class="form-group has-feedback">
{!! Form::label('first_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('first_name', null, ['class' => 'form-control', 'placeholder' => 'First Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('first_name'))
{{ $errors->first('first_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('last_name', null, ['class' => 'sr-only']) !!}
{!! Form::text('last_name', null, ['class' => 'form-control', 'placeholder' => 'Last Name']) !!}
<i class="fa fa-user form-control-feedback"></i>
#if($errors->has('last_name'))
{{ $errors->first('last_name') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('email', null, ['class' => 'sr-only']) !!}
{!! Form::email('email', null, ['class' => 'form-control', 'placeholder' => 'Email address']) !!}
<i class="fa fa-envelope form-control-feedback"></i>
#if($errors->has('email'))
{{ $errors->first('email') }}
#endif
</div>
<div class="form-group has-feedback">
{!! Form::label('message', null, ['class' => 'sr-only']) !!}
{!! Form::textarea('message', null, ['class' => 'form-control', 'rows' => 8, 'placeholder' => 'Message']) !!}
<i class="fa fa-pencil form-control-feedback"></i>
#if($errors->has('message'))
{{ $errors->first('message') }}
#endif
</div>
{!! Form::submit('Send', ['class' => 'btn btn-default', 'id' => 'mail_btn']) !!}
{!! Form::close() !!}
What you need to do is to render the view that you want to pass throught the ajax like this:
return view('passed')->render();
...
return view('fail')->render();
EDIT
You have to pass event as a clouser parameter and uncomment this: //event.preventDefault();:
$('#footer-form').click(function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost/ensignhospital/mail',
data: $('form#footer-form').serialize(),
dataType: 'html'
})
.done(function (data) {
console.log(data);
});
});
so that:
click(function () {
why it doesn't work. Should be:
click(function (event) {
I'm trying to handle dropzone.js to work correct with my entity symfony formbuilder.
Everything works properly if I'm using simple <input type="file" id="form_file" name="form[file]">
BUT if I'm using dropzone.js I get this difference in my POST:
How I can handle it?
This is my js for it:
Dropzone.options.myAwesomeDropzone = {
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 25,
maxFiles: 25,
init: function() {
var myDropzone = this;
$("#submit-all").click(function (e) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
}
);
}
}
My form file looks like:
<form id="my-awesome-dropzone" class="wizard-big dropzone" action="{{ path('add') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form.name, {'attr': { 'class': 'form-control' } }) }}
<div class="row">
<div class="dropzone-previews"></div>
<div class="fallback">
{{ form_widget(form.file, {'attr': { 'class': 'cotam' } }) }}
</div>
</div>
<button type="submit" id="submit-all" class="btn">Upload the file</button>
{{ form_rest(form) }}
</form>
And my controller:
public function addAction(Request $Request) {
$photo = new Photo();
$form = $this->createFormBuilder($photo)
->add('name')
->add('file')
->getForm();
$form->handleRequest($Request);
if ($form->isValid() && $Request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$em->persist($photo);
$em->flush();
$this->redirect($this->generateUrl('add'));
}
return $this->render('MyBundle::add.html.twig', array(
'form' => $form->createView()
));
}
Could You help me?
Ok I found the answer... It was simple as possible..
You need to just add a option:
paramName: "form[file]"
To Your dropzone configuration.
I have a question about using a zend form in a twitter bootstrap modal. This is what I have:
In my Controller:
public function accountAction() {
$form = new Form_CancelAccount();
$this->view->form = $form;
// Some executions and view params for the view, ex:
/*if ($user->getRecurlyId() && NameSpace_Feature_Access_RoleHelper::hasAccess('show_billing')) {
try {
$account = Recurly_Account::get($user->getRecurlyId());
$this->view->token = $account->hosted_login_token;
$this->view->show_billing = true;
} catch (Recurly_NotFoundError $e) {
$this->view->show_billing = false;
}
} else {
$this->view->show_billing = false;
}*/
if ($this->getRequest()->isPost() && $form->isValid($_POST)) {
$data = $form->getValues();
var_dump($data);
} else {
var_dump("it didn't work!");
}
}
My CancelAccount Form:
<?php
class Form_CancelAccount extends NameSpace_Form_Base
{
public function __construct($options = null) {
parent::__construct($options);
$this->setName('cancelaccount');
$element = new Zend_Form_Element_Radio('reason');
$element->addMultiOptions(array(
'It is really bad!' => 'bad',
'No time for it!' => 'notime',
'Other option:' => 'otheroption'
))->setDecorators(array(array('ViewScript', array('viewScript' => 'user/radio.phtml'))));
$this->addElement($element);
$this->addElement('text', 'otheroption', array(
'attribs' => array(
'class' => 'input-block-level otheroption',
'size' => 30,
'placeholder' => 'Other option'
),
'decorators' => $this->elementDecoratorsNoTag
));
}
}
In my View:
// Some data sent from the controller
<h4>Delete account</h4>
<p>Deleting of your account implies your account and the related data will be deleted. Please note that this is not reversible.</p>
<button type="button" data-target="#cancelModal" data-toggle="modal" class="btn btn-primary">Delete account</button>
<div class="modal hide fade" id="cancelModal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<?php echo $this->form; ?>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" value="OK" form="cancelaccount">
<a id="cancel" class="btn btn-default close" data-dismiss="modal">Cancel</a>
</div>
But I always get the output 'it didn't work!' from the var_dump when the form isn't valid ... . What's the best way to do this? And how does it comes it's always not valid?
UPDATE:
When I leave out the "&& $form->isValid($_POST)" in my if statement I come in the statement, but my var_dump shows this:
array (size=2)
'reason' => null
'otheroption' => null
My response:
The problem is that my radiobuttons aren't valid ... How can I fix this?
The problem where my radiobuttons. Change the radiobuttons in my form to:
$this->addElement('radio', 'reason', array(
'label'=>'Reason:',
'multiOptions'=>array(
'bad' => 'It is really bad!',
'notime' => 'No time for it!',
'otheroption' => 'Other option:'
),
));
Now it works!
if ($this->getRequest()->isPost() && $form->isValid($_POST)) {
$data = $form->getValues();
var_dump($data);
} else {
var_dump("it didn't work!");
}
to
if ($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost()){
$data = $form->getValues();
var_dump($data);
} else {
var_dump("it didn't work!");
}
}
and remember put this to last line of action:
$this->view->form = $form;
i'm sorry, i speak English not well.