how to add csrf token into dropzonejs - javascript style - laravel 5.1 - javascript

I have successfully sent a csrf token using dropzone but using jquery style, now I don't want to use any jquery in my code I want to use javascript style to get the csrf token. I tried using below code but it keeps on giving me the tokenmismatch error,
myDropzone.on("sending", function(file,xhr,formData) {
// Show the total progress bar when upload starts
var folname = document.getElementById('folname').value;
var token = document.getElementsByName("_token")[0].value;
formData.append('folname',folname);
formData.append('_token', token );
});
this is the code that is working using jquery.
myDropzone.on("sending", function(file,xhr,formData) {
// Show the total progress bar when upload starts
var folname = document.getElementById('folname').value;
formData.append('folname',folname);
formData.append('_token', $('input[name="_token"]').val() );
});
any advice is appreciated. thanks guys.

Plain old inline javascript variable perhaps? Placed before all scripts possibly at the head
var csrf_token = "{{ csrf_token() }}";
...
// js file where dz related code is residing
...
myDropzone.on("sending", function(file,xhr,formData) {
// Show the total progress bar when upload
var folname = document.getElementById('folname').value;
formData.append('folname',folname);
formData.append('_token', csrf_token);
});

Guys thank you for leading me to the right path. I found the problem, I have two elements with "_token" name. so when debugging it returns 'undefined' error.
this code now works.
var token = document.getElementsByName("_token")[0].value;
my csrf token declaration is like this
<form name="post_form" id="post_form" class="form-horizontal" role="form" method="POST" action="/post">
{!! csrf_field() !!}
<!-- other code input boxes -->
</form>
<!--my dropzone code is below the form-->
<script>
// dropzone code here
</script>
the solution is either I use the token in my meta tag to my dropzone submission or change the name of the meta tag name from "_token" to something else.
so for this, I choose to use the meta tag to my dropzone code and it's now working. please see below for the solution.
I added a meta tag in my header with "_token" name.
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="_token" content="{!! csrf_token() !!}"/>
</head>
and in my footer
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
</body>
</html>
I have use the meta tag token value instead. here's what I did.
myDropzone.on("sending", function(file,xhr,formData) {
// Show the total progress bar when upload starts
var folname = document.getElementById('folname').value;
var token1 = document.getElementsByTagName('meta')['_token_'].getAttribute('content');
formData.append('folname',folname);
formData.append('_token', token1 );
});
let me know if I should add anything else to make the post more useful.

There are two ways to solve it.
--- FIRST (easiest) ---
<form method="POST" action="/your/url/here" class="dropzone" id="upload-files" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('POST') }}
</form>
<script>
$(function() {
Dropzone.options.uploadFiles = {
paramName: 'document_files',
maxFilesize: 3,
init : function() {
this.on("success", function(file, response) {
// file uploaded successfully
});
}
};
});
</script>
--- SECOND ---
Using dropzone in this way, you can place your dropzone inside another form.
<div class="dropzone dropzone-previews" id="dropzone-upload-documents"></div>
<script>
$(function() {
// in this case is important that autoDiscover = false
Dropzone.autoDiscover = false;
$("#dropzone-upload-documents").dropzone({
paramName: 'document_files',
maxFilesize: 3,
url: "/your/url/here",
init: function() {
this.on("success", function(file, response) {
// file uploaded successfully
});
},
sending: function(file, xhr, formData) {
formData.append("_token", "{{ csrf_token() }}");
formData.append("_method", "POST");
}
});
});
</script>

Related

Failed to load resource : Internal Server Error (500) : jQuery

We are using jQuery 3.3.1 in our project. When we are using and testing on localhost the jQuery works fine and its loading without any issue.
However, now we have deployed our web application on AWS and after deploying it is giving the below error
Failed to load resource : the server responded with a status of 500 (Internal Server Error)
We are loading third party payment providers iFrame in our html page. Is that causing an issue ? If it is an issue then why does it works fine in localhost ?
Also, we have kept the file in our solution itself and tried with jQuery CDN as well. But it gives the same error.
#using Microsoft.AspNetCore.Mvc.Rendering;
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>PaymentProviders</title>
<script src="~/jquery.min.js"></script>
</head>
<body>
<div class="form-control">
<label>Payment Provider Name:- </label>
#Html.DropDownList("ID", new SelectList(ViewBag.PaymentProvidersList, "ID", "PaymentProviderName"), "Please select", new { #id = "ddlPaymentProviders", #onChange = "SelectedValue(this)" })
</div>
<div id="divContainer"></div>
</body>
</html>
<script>
function SelectedValue(ddlObject) {
var selectedText = ddlObject.options[ddlObject.selectedIndex].innerHTML;
$.ajax({
type: "GET",
url: "/Home/Index",
data: { 'paymentProviderName': selectedText },
success: function (data) {
$('#divContainer').html(data);
$('#divContainer iframe').height("500");
}
});
}
</script>
Below is the screenshot for the same.
Any help on this appreciated !

Summernote image upload from URL

I'm using summernote html text editor on my site. I want to download images to my server when user put an image url to Image URL area then press to Insert Image button.
Currently summernote only get image's source for src attribute. I want to store images on my own Amazon S3 Bucket or VPS.
There are many docs about summernote image upload but all of them for upload from pc not from URL.
How can I overwrite this feature?
Image dialog
So since you are not able to read dataUrl of cross-origin images in your client-side script the decision is to get url from Image URL area and send it to your backend. There you may use a simple php script to download the image.
The example includes both client and backend codes. Both tested. All you need is to put these two scripts to one of your web server's directories and give it a try.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Summernote</title>
<!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.2/summernote.js"></script>
</head>
<body>
<div id="summernote">Hello Summernote</div>
<script type="text/javascript">
$(document).ready(function() {
$('#summernote').summernote();
$('button[data-original-title="Picture"]').click(function(){
// Set handler on Inset Image button when dialog window is opened
$('.modal-dialog .note-image-btn').one('click', function(e) {
// Get Image URL area
var imageUrl = $('.modal-dialog .note-image-url').val();
// Send it to your backend
$.ajax({
url: "image_loader.php",
data: "url="+imageUrl,
type: "POST",
dataType: 'json'
}).success(function(data) {
if (typeof data[0] === 'string') {
$('img[src="'+imageUrl+'"]').attr('src', data);
} else {
// What to do if image downloading failed
window.alert('oops');
}
}).error(function() {
// What to do if ajax request failed
window.alert('oops');
});
});
});
});
</script>
</body>
</html>
image_loader.php
<?php
if ($_POST['url']) {
// Here you'd better put some logic to check that $_POST['url'] is a correct url before use it
$image = file_get_contents($_POST['url']);
if ($image) {
// Put downloaded image on your server
$file = fopen('imagename.jpeg', 'w');
fwrite($file, $image);
fclose($file);
}
/**
* Now your code needs to echo one of the following:
* string Url of an uploaded image on your server
* bool False if it failed
*
* To avoid bool to string conversion during output response needs to be sent as JSON
*/
$response = ($image) ? array('/PATH_TO_IMAGE_DIRECTORY_IF_NEEDED/imagename.jpeg') : array(false);
echo json_encode($response);
}
For example with this image https://imgsnap.com/images/2015/02/23/abstract_0005.jpg
UPDATE (to your comment about img styling)
Put the following line in summernote.js to trigger a special event when image url has been handled by the editor.
$(document).trigger('imageUrlInserted', src);
Put it on line 4095 (according to my version of file) inside of insertImage() method before
$image.css('width', Math.min($editable.width(), $image.width()));
Now in index.php inside of
$('.modal-dialog .note-image-btn').one('click', function(e) {
...
...
});
replace all the code with this
// Get Image URL area
var imageUrl = $('.modal-dialog .note-image-url').val();
// Send it to your backend after the image been handled by the editor
$(document).on('imageUrlInserted', function(e, sourceUrl) {
if (sourceUrl === imageUrl) {
$.ajax({
url: "image_loader.php",
data: "url="+imageUrl,
type: "POST",
dataType: 'json'
}).success(function(data) {
if (typeof data[0] === 'string') {
$('img[src="'+imageUrl+'"]').attr('src', data).removeAttr('style');
} else {
// What to do if image downloading failed
window.alert('oops');
}
}).error(function() {
// What to do if ajax request failed
window.alert('oops');
});
}
});

Paypal lightbox: does not permit cross-origin framing

I have attempted to go about the use of Paypal Lightbox a bit differently.
I have used a button to trigger an ajax call which then generates the PayKey and if all goes well then triggers the form (from the documentation) to be created and submitted.
When i click the button the lightbox html is created but the content is not loaded into it. Instead i get the error:
Load denied by X-Frame-Options: https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_dispatch-failed does not permit cross-origin framing.
My Code:
<head>
<script src="https://www.paypalobjects.com/js/external/dg.js" type="text/javascript"></script>
</head>
External Script:
$("#checkout").click(function() {
var id = $(this).data("id");
if(id) { pay(id); }
});
function pay(id) {
$.ajax({
url : 'paypal/Pay-Chained.php',
type : 'POST',
data : "id="+id,
success : function (data) {
var info = (JSON.parse(data));
if (info['Type'] == 'Success') {
var output = info['URL'].substr(0, 64) + "expType=light&" + info['URL'].substr(64);
$("body").append('<form action="'+output+'" target="PPDGFrame" class="standard"><input type="submit" id="submitBtn"></form>');
$("#submitBtn").click();
} else {
alert("Error: Please try again or contact support.");
}
},
error : function () {
alert("Error: Please try again.");
}
});
}
At the bottom of the buttons page:
<script type="text/javascript" charset="utf-8">
var embeddedPPFlow = new PAYPAL.apps.DGFlow({trigger: 'checkout'});
</script>
I am thinking maybe it has to do with the order things are executed but can't seem to figure it out. Any help would be great!
EDIT: I just created a blank page and copied the script from the documentation exactly. I still get the same error. Might it have something to do with server settings? I am running a WampServer with an address like 192.168.1.1/mysite/index.html.

Valums file uploader issue

Valumes doesn't show UPLOAD button under Firefox (MVC3 Project).
It works fine under: IE, Chrome
I am going to kill myself but I don't understand why is it?
ANYYY CLUUU pleaseeee!
<script src="#Url.Content("~/Scripts/valums/FileUploader.js")" type="text/javascript"></script>
<div id="fileUploader">
<noscript>
<p>
Please enable JavaScript to use file uploader.</p>
<!-- or put a simple form for upload here -->
</noscript>
</div>
.................
var button = $('#fileUploader')[0];
var uploader = new qq.FileUploader({
element: button,
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
sizeLimit: 2147483647,
action: '#Url.Action("UploadFile")',
multiple: false,
onComplete: function (id, fileName, responseJSON) {
var uploadedFile = "/Images/Orders/thumb-" + responseJSON.uploadedFile;
$("#uploadedImage").attr("src", uploadedFile);
$("#ImageErrorMessage").text("");
}
});
Just put the VALUMS code within $(document).ready(function () { // here });
and keep it under the <HEAD> tag. That's it!

How to send web browser a loading page, then some time later a results page

I've wasted at least a half day of my company's time searching the Internet for an answer and I'm getting wrapped around the axle here. I can't figure out the difference between all the different technology choices (long polling, ajax streaming, comet, XMPP, etc.) and I can't get a simple hello world example working on my PC.
I am running Apache 2.2 and ActivePerl 5.10.0. JavaScript is completely acceptable for this solution. All I want to do is write a simple Perl CGI script that when accessed, it immediately returns some HTML that tells the user to wait or maybe sends an animated GIF. Then without any user intervention (no mouse clicks or anything) I want the CGI script to at some time later replace the wait message or the animated GIF with the actual results from their query.
I know this is simple stuff and websites do it all the time using JavaScript, but I can't find a single working example that I can cut and paste onto my machine that will work in Perl.
Here is my simple Hello World example that I've compiled from various Internet sources, but it doesn't seem to work. When I refresh this Perl CGI script in my web browser it prints nothing for 5 seconds, then it prints the PLEASE BE PATIENT web page, but not the results web page. So the Ajax XMLHttpRequest stuff obviously isn't working right. What am I doing wrong?
#!C:\Perl\bin\perl.exe
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
sub Create_HTML {
my $html = <<EOHTML;
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="expires" content="-1" />
<script type="text/javascript" >
var xmlhttp=false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#end #*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}
</script>
<title>Ajax Streaming Connection Demo</title>
</head>
<body>
Some header text.
<p>
<div id="response">PLEASE BE PATIENT</div>
<p>
Some footer text.
</body>
</html>
EOHTML
return $html;
}
my $cgi = new CGI;
print $cgi->header;
print Create_HTML();
sleep(5);
print "<script type=\"text/javascript\">\n";
print "\$('response').innerHTML = 'Here are your results!';\n";
print "</script>\n";
If your process relies on query-string parameters, a simple meta-refresh would suffice. E.g. if they load http://yoursite.com/message?foo=1, then that can output a meta tag like:
<meta http-equiv="refresh" content="0; http://yoursite.com/realquery?foo=1" />
And some HTML that has your "please wait" message. The realquery script would actually execute the query and the HTML output by message will remain on the screen until realquery provides some output.
If the query relies on POST data, then it gets a little more complicated, because you can't redirect a POST. You can, however, output a form with some hidden fields and use Javascript to submit it. For example:
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'form_with_hidden_fields' ).submit();
}
</script>
<form method="POST" action="realquery" id="form_with_hidden_fields">
<input type="hidden" name="foo" value="1" />
...
</form>
Please wait while your query is processed...
If you're interested in an AJAX solution, here's an example using jQuery:
$( '#submit-button' ).click( function() {
// show a "please wait" image
$( '#status-div' ).html( '<img src="please_wait.gif" />' ); // animated gif
// get form values
var formdata = { foo: $( 'input#foo' ).val(),
...
};
// submit form via ajax:
$.ajax( { type: "POST", url: "/realquery", data: formdata, success: function() {
$( '#status-div' ).html( '<img src="success.gif" />' );
} );
} );
And you could attach that to a form like:
<form>
<input type="text" name="foo" id="foo" />
<input type="submit" id="submit-button" />
<div id="status-div"> </div>
</form>
The empty status-div div will receive an image tag that points to a "please wait" image (this can be an animated gif). When the Ajax query finishes, it's replaced by a "success" image.
See Watching long processes through CGI by Randal Schwartz.
Here is a complete working example using friedo's HTTP meta refresh solution. This is not my personal first choice solution because it modifies the URL in the browser and it also refreshes the whole web page.
#!C:\Perl\bin\perl.exe
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
sub html_page {
my ( $meta_string, $results_string ) = #_;
my $html = <<EOHTML;
<html>
<head>
$meta_string
<title>Two Stage Web Page Demo</title>
</head>
<body>
Some header text.
<p>
$results_string
<p>
Some footer text.
</body>
</html>
EOHTML
return $html;
}
my $cgi = new CGI;
print $cgi->header;
if ($cgi->param()) {
if ($cgi->param('doResults') eq "true") {
sleep(5);
print html_page('', 'Here are your results!');
}
}
else {
my $meta_refresh = '<meta http-equiv="refresh" content="0; /cgi-bin/twoStageScript.pl?doResults=true" />';
print html_page($meta_refresh, 'PLEASE BE PATIENT');
}
exit;
Finally got an Ajax version working. The slow.pl file is the file that takes a while to return.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Two Stage web page demo using Ajax</title>
</head>
<body>
<h1>Two Stage web page demo using Ajax</h1>
<div id="result">
Users input form goes here.
<p>
<input type="submit" value="Here is your submit button" id="load_basic" />
</div>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var ajax_load = "Please be patient, this could take a while. <p> <img src='img/load.gif'/>";
// load() function
$("#load_basic").click(function(){
$("#result").html(ajax_load).load("/cgi-bin/slow.pl");
});
</script>
</body>
</html>

Categories