CKEditor file upload not working in Yii2 - javascript

I'm working on Yii2 Project where I've integrated http://ckeditor.com/demo
Now I want to implement functionality of file/image upload in it.
This is how I integrated CKEditor in Yii2 Project.
Step1: AppAsset.php
public $js = [
'ckeditor/ckeditor.js',
];
Calling ckeditor.js javascript file from config/AppAsset Class
Step2: View
<?= $form->field($model, 'standard_output_information')->textarea(['rows' => 2, 'class'=>'ckeditor']) ?>
Step3: config.js
CKEDITOR.editorConfig = function (config) {
var base_url = window.location.origin;
var pathArray = window.location.pathname.split('/');
var projectUrl = base_url + "/" + pathArray[1] + "/" + pathArray[2] + "/" + pathArray[3] + "/uploads";
config.filebrowserImageBrowseUrl = base_url + "/pcwf" + "/backend" + "/web" + "/businessprocessprofile" + "/upload";
config.filebrowserImageUploadUrl = base_url + "/pcwf" + "/backend" + "/web" + "/businessprocessprofile" + "/upload";
};
Here I've configured ImageBrowserUrl and ImageUploadUrl mentioned here http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader)
Step4: Controller
public function actionUpload() {
echo \yii\helpers\Html::csrfMetaTags();
echo "<pre>";
print_r($_FILES);
print_r($_REQUEST);
exit;
}
Here I'm expecting uploaded image data. But whenever I click on Send it to Server button after selection of an image its giving me following error.
Not sure whether its issue of wrong url configuration in config.js or is it Yii2 form submission issue.
Any help would be appreciated.

I believe you have a problem with the CRSF tokens. Read more about the security here: http://www.yiiframework.com/doc-2.0/guide-security-best-practices.html. The easiest way to get around this is to disable CRSF for that particular action. You can take a look on how to do that here: https://stackoverflow.com/a/28526946/1880627

Rather than disabling CSRF validation it is far better and more secure to submit the token with the form to pass server-side validation. This can be quite easily done by injecting a hidden input field into the upload form with javascript:
$(document).off('click', '.cke_dialog_tabs a[id^="cke_Upload_"]').on('click', '.cke_dialog_tabs a[id^="cke_Upload_"]', function () {
var $forms = $('.cke_dialog_ui_input_file iframe').contents().find('form');
var csrfName = yii.getCsrfParam();
$forms.each(function () {
if (!$(this).find('input[name=' + csrfName + ']').length) {
var csrfTokenInput = $('<input/>').attr({
'type': 'hidden',
'name': csrfName
}).val(yii.getCsrfToken());
$(this).append(csrfTokenInput);
}
});
});
For a more detailed discussion on the issue refer to 2amigos/yii2-ckeditor-widget, issue #2. This is also where the code snippet is taken from, with a few minor tweaks to cover the case of multiple widgets on the page.

Related

Send Data to php file with javascript

I am trying to send form data to another PHP file.
its working but once data is submitted the page is not redirecting to that specific page.
Like it work in php.
function codeverify() {
var code=document.getElementById('verificationCode').value;
coderesult.confirm(code).then(function (result) {
if (confirm("OTP Confirmed!")) {
var number=document.getElementById('number').value;
$.post("confirm-phone-reg.php", { status: number }); //send data to file
//document.location.href = "http://localhost/test/new/confirm-phone-reg.php";
} else {
window.location.href = "http://localhost/test/new/try-again.php";
};
var user=result.user;
console.log(user);
}).catch(function (error) {
alert(error.message);
});
}
How can I make sure when I send data to the confirm-phone-reg.php the post data and my page will be opened there.
I searched too much on internet but failed to search for answer.
I hope you guys will help me.
var number = document.getElementById('number').value;
var url = 'register.php';
var form = $('<form action="' + url + '" method="post">' + '<input type="text" name="phone" value="' + number + '" />' + '</form>');
$('body').append(form);
form.submit();
For those who are also stuck like this.
This is the easiest way to send data to another file and also redirect at the same time.

How to change the text of my form in blade.php? [duplicate]

This question already has answers here:
Blade view not reflecting changes
(12 answers)
Closed 3 years ago.
I'm trying to change the text of the popup form but even though I already change it in blade.php still doesn't change the text. This is a template I just bought.
Image reference
I tried to change the text 'Are you want to Donate' to 'Do you want to Donate' but it doesn't change.
<script type="text/javascript">
$(document).ready(function () {
$("#cause-share").jsSocials({
showLabel: false,
showCount: false,
$(document).on('click', '#pay-next', function () {
var amo = $('#amount').val();
if (!isNaN(amo) && amo > 0) {
$('#payment-details').css('display', 'none');
$('#deposit-method').show();
$('#back-btn').show();
$(document).on('click', '.deposit_button', function () {
var gId = $(this).data('id');
var cur = $(this).data('currency');
var paymentGate = $(this).data('val');
var amount = parseFloat($('#amount').val());
var name = $('#name').val();
var phone = $('#phone').val();
var email = $('#email').val();
var description = $('#description').val();
var causeId = {{$item->id}};
$('#deposit-method').css('display', 'none');
$('#donate-popup').css('display', 'none');
$('#back-btn').css('display', 'none');
$('#gt_preview').show();
$('#deposit-text').text('Are You Want to Donate ' + amount + ' ' + cur + ' ?');
$('#accinfo').text('Please Send Total ' + amount + ' ' + cur + ' to');
This is the result is shows "Are you want to Donate"?
Image reference
It should be "Do you want to Donate?"
Try clearing out both your Browser and Laravel App's cache, to clear Laravel's cache cd into your project and run:
php artisan cache:clear
php artisan config:clear
php artisan view:clear
As mentioned in another post; In order to avoid the parsing of Blade files on each reload, Laravel caches the views after Blade is processed. I've experienced some situations where the source (view file) is updated but the cache file is not "reloaded". In these cases, all you need to do is to delete the cached views and reload the page.
The cached view files are stored in the storage/framework/views directory.
I was able to fix it there's another file which is the footer blade php file and change the text there and after that I cleared the laravel's cache

How do I fetch PHP script output from Javascript?

This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/

Sending URL as a parameter using javascript

I have to send a name and a link from client side to the server. I thought of using AJAX called by Javascript to do this.
This is what I mean. I wished to make an ajax request to a file called abc.php with parameters :-
1. http://thumbs2.ebaystatic.com/m/m7dFgOtLUUUSpktHRspjhXw/140.jpg
2. Apple iPod touch, 3rd generation, 32GB
To begin with, I encoded the URL and tried to send it. But the server says status Forbidden
Any solution to this ?
UPDATE ::
It end up calling to
http://abc.com/addToWishlist.php?rand=506075547542422&image=http://thumbs1.ebaystatic.com/m/mO64jQrMqam2jde9aKiXC9A/140.jpg&prod=Flat%20USB%20Data%20Sync%20Charging%20Charger%20Cable%20Apple%20iPhone%204G%204S%20iPod%20Touch%20Nano
Javascript Code ::
function addToWishlist(num) {
var myurl = "addToWishlist.php";
var myurl1 = myurl;
myRand = parseInt(Math.random()*999999999999999);
var rand = "?rand="+myRand ;
var modurl = myurl1+ rand + "&image=" + encodeURI(storeArray[num][1]) + "&prod=" + encodeURI(storeArray[num][0]);
httpq2.open("GET", modurl, true);
httpq2.onreadystatechange = useHttpResponseq2;
httpq2.send(null);
}
function useHttpResponseq2() {
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
}
Server Code
<?php
include('/home/ankit/public_html/connect_db.php');
$image = $_GET['image'];
$prod = $_GET['prod'];
$id = $_GET['id'];
echo $prod;
echo $image;
?>
As I mentioned, its pretty basics
More Updates :
On trying to send a POST request via AJAX to the server, it says :-
Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"
2 things.
Use encodeURIComponent() instead of encodeURI().
Here is a detailed discussion on this: When are you supposed to use escape instead of encodeURI / encodeURIComponent?
If you are new to JavaScript, use some lib to help you do the AJAX work. Like mootools, jQuery, etc.
Using a POST request solved my issue :)
function addToWishlist(num) {
var url = "trial.php";
var parameters = "prod=" + encodeURIComponent(storeArray[num][0]) + "&image=" + encodeURIComponent(storeArray[num][1]);
httpq2.open("POST", url, true);
httpq2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpq2.onreadystatechange = function(){
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
};
httpq2.send(parameters);
}

Creating a post by sending HTTP request to Facebook API

I want to post on my facebook page by sending a HTTP POST. The way I am doing this is by creating a permanent access_token that is used to post to my facebook page. The problem is the access_token can be easily taken/inspected using firebug or any other tool (since it is hard-coded). How can I send it in a way that is kept from others.
$appID = 'MY_APP_ID';
$fb_page_id = 'MY_PAGE_ID';
$fb_page_access_token = 'PERMANENT_ACCESS_TOKEN';
$html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
. '<html><body>'
. '<div id="fb-root"></div>'
. "<script type=\"text/javascript\">
function post_to_fb(commentText, commentUsername, commentLink) {
var logoName = get_logoname_from_link(commentLink);
var strURL = 'https://graph.facebook.com/" . $fb_page_id . "/feed';
var params = 'link=' + commentLink + '&name=Brandchamp+-+' + logoName + '&message=[' + commentUsername +'+commented on ' + logoName + ':]+' + commentText + '&access_token=" . $fb_page_access_token . "';
var xmlHttpReq;
xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open('POST', strURL, true);
xmlHttpReq.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlHttpReq.send(params);
}
window.fbAsyncInit = function() {
FB.init({
appId: " . $appID . ",
status: true,
cookie: true,
xfbml: true,
});
FB.Event.subscribe('comment.create', function(response) {
var commentQuery = FB.Data.query('SELECT fromid, text FROM comment WHERE post_fbid=\'' + response.commentID + '\' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url=\'' + response.href + '\')');
var userQuery = FB.Data.query('SELECT name FROM user WHERE uid in (select fromid from {0})', commentQuery);
FB.Data.waitOn([commentQuery, userQuery], function () {
var commentRow = commentQuery.value[0];
var userRow = userQuery.value[0];
var commentText = commentRow.text;
var commentUsername = userRow.name;
post_to_fb(commentText, commentUsername, response.href);
});
});
};
(function() {
var e = document.createElement('script');
e.async = true;
e.src = document.location.protocol + '//connect.facebook.net/de_DE/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>"
. '</body></html>';
print $html;
Simply don't let users see your access token: you have to create some kind of proxy which will post to your's page wall server-side
Whats the problem if a user who is granting you permission can see his/her own access_token in firebug. Firebug is on client side only. Also, official javascript sdk gives access_token to client. I dont think its bad.
User can always see his/her own password :) . What is bad in it ?
You should care about sniffing access_token over network. As #Juicy suggested use https to overcome that situation.
Edit after reading comment:
In your situation, I would suggest not to use javascript/ajax.
Also, I would recommend to use an sdk over your own php code.
An sdk uses all security measures which should be taken.
Official php sdk:
https://github.com/facebook/facebook-php-sdk

Categories