I am trying to use javascript to change an image in my blade file
but am getting the following error. As a side note I have enabled HTML forms in laravel, and I am able to display images without javascript.
Fatal error: Class 'HTML' not found (View:/home/vagrant/Code/Laravel/resources/views/pages/progress.blade.php)
Below is my javascript code
<script>
window.onload = function() {
changeImageForSeniorLevel();
};
function changeImageForSeniorLevel() {
var level = '<?php echo $levelValue; ?>';
if (level == 3)
{
document.getElementById("image").src="{{ HTML::image('progress2/Icons/Calls_Icon.png', 'alt',array('width' => 150 )) }}";
}
}
</script>
Here is the code for the image I am trying to change, the code will display an image if I comment my javascript.
{{ HTML::image('progress2/Icons/Meetings_Icon.png', 'alt', array('id' => 'image', 'width' =>150)) }}
HTML::image is a Laravel class / method that is parsed in PHP (which is hosted on your server). You cannot parse it using a browser / HTML. The browser does not know what HTML::image means. In your case, you just want to change the attributes of an image already drawn on your document.
You can use the following to achieve what you are looking for:
if(level == 3){
var myImage = document.getElementById("image");
myImage.src = 'progress2/Icons/Calls_Icon.png';
myImage.alt = 'alt';
myImage.style.width = '150px';
}
Related
** How to get laravel Storage path in js file**
I want to display dinamic image in laravel from database using jquery ajax, but I can't get Stoage path in js file to put my image name
which is a variable:
images.forEach(function (image) {
var img = `<img src="http://localhost/storage/${product.image}"`;
});
"http://localhost/storage/" works,but I want to replace "http://localhost/storage/" to dinamic url using javascript
Use a relative path, which will fix the issue in any server.
As follows
images.forEach(function (image) {
var img = `<img src="/storage/${product.image}"`;
});
To get laravel storage path in js file you can do like:
In your headerfile.blade.php
<script>
var storagePath = {!! storage_path() !!}; // old with error
var storagePath = "{!! storage_path() !!}"; // updated and tested
</script>
The in js file you can use storagePath variable.
I hope this will help you.
For that either 1.
{!! storage_path('app/public') !!}
2.you can pass it with your data of product
or
3.you use model for set the full src of image
protected $appends = ['image_url'];
public function getImageUrlAttribute()
{
$imageUrl = "";
if (isset($this->attributes['image']) && $this->attributes['image'] != "") {
$imageUrl = storage_path('app/public').$this->attributes['image'];
}
return $imageUrl;
}
and you can use them in your blade like
images.forEach(function (image) {
var img = `<img src="${product.image_url}"`;
});
I'we html code for the editor:
<div id="editor">
<h1>Hello world!</h1>
<p>I'm an instance of CKEditor.</p>
</div>
And javascript for it.
if (CKEDITOR.env.ie && CKEDITOR.env.version < 9) {
CKEDITOR.tools.enableHtml5Elements(document);
}
CKEDITOR.config.height = 150;
CKEDITOR.config.width = 'auto';
CKEDITOR.config.defaultLanguage = 'en';
CKEDITOR.config.language = 'en';
CKEDITOR.config.extraPlugins = 'uploadimage,filebrowser';
CKEDITOR.config.toolbarCanCollapse = true;
function loadEditor(id) {
if (CKEDITOR.revision === ('%RE' + 'V%') || !!CKEDITOR.plugins.get('wysiwygarea')) {
CKEDITOR.replace(id);
} else {
CKEDITOR.document.getById(id).setAttribute('contenteditable', 'true');
CKEDITOR.inline(id);
}
}
loadEditor('editor');
Can somebody give me a simple explanation how to make that i can upload image straight throw ckeditor. I've been trying over a week to do it. I downloaded plugins uploadimage, and it's dependencies plugins. No "Upload" tag appear in "Image Properties" window.
Thank you
UploadImage add-on only works for dropped or pasted images. If you only want Upload tab in Image Properties, you have to set config.filebrowserImageUploadUrl to a script that will handle the upload:
config.filebrowserImageUploadUrl = '/uploader/upload.php?type=Images';
Your upload.php should be like this (taken from Integrating CKEditor with a Custom File Browser, example 3):
<?php
// Required: anonymous function reference number as explained above.
$funcNum = $_GET['CKEditorFuncNum'] ;
// Optional: instance name (might be used to load a specific configuration file or anything else).
$CKEditor = $_GET['CKEditor'] ;
// Optional: might be used to provide localized messages.
$langCode = $_GET['langCode'] ;
// Check the $_FILES array and save the file. Assign the correct path to a variable ($url).
$url = '/path/to/uploaded/file.ext';
// Usually you will only assign something here if the file could not be uploaded.
$message = '';
echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";
?>
I have this line in my Razor :
#Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Home/index.html")))
And in HTML file, I have this :
<li>Personal Records</li>
And in my js file I have this :
if ($(link).text() === 'Personal Records') {
$("#govde").load("PersonalRecords.html");
}
But when I click on that link, nothing happens. When I open Index.html directly from file browser, it works. How can I fix this?
EDIT :
In console, it has this :
http://localhost:12345/PersonalRecords.html 404 (Not Found)
I guess I have placed the html files to a wrong folder. Can you tell me where to place? Thanks.
EDIT2 :
I have this in my JS :
var upperMenu = document.getElementById('upperMenu');
var requests = document.getElementById('requests');
$(upperMenu ).click(function (event) {
ustMenu.childNodes.forEach((myList) => {
$(myList).attr('class', ' ');
});
var link = event.target;
var list = link.parentNode;
$(myList).attr('class', 'active');
if ($(link).text() === 'Personal Records') {
$("#govde").load('#Url.Content("~/PersonalRecords.html")');
}
});
.load function is created in this(seperate) JS file.
The problem started with file name mentioned in $("#govde").load method:
$("#govde").load("PersonalRecords.html");
This statement tries to load "PersonalRecords.html" which assumed exists in the project's root directory, but it returns 404 since the target file exist in different directory.
Hence, it should be mentions full absolute path URL to load HTML content first:
var url = '#Url.Content("~/Views/Home/PersonalRecords.html")';
Then, since load method placed inside separate JS file, putting them together should results like this:
Razor
<script src="#Url.Content("~/[path_to_your_JS_file]")" type="text/javascript"></script>
<script>
var url = '#Url.Content("~/Views/Home/PersonalRecords.html")';
loadRequest(url);
</script>
JavaScript file
function loadRequest(url) {
var upperMenu = $("#upperMenu").get(0);
var requests = $("#requests").get(0);
$(upperMenu).click(function (event) {
ustMenu.childNodes.forEach((myList) => {
$(myList).attr('class', ' ');
});
var link = event.target;
var list = link.parentNode;
$(myList).attr('class', 'active');
if ($(link).text() === 'Personal Records') {
$("#govde").load(url);
}
}
}
Next, as of first mentioned part:
#Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Home/index.html")))
I considered this is not a good practice to read all file contents in view side, hence I prefer return the file contents from controller side using FilePathResult like #Guruprasad Rao said:
// taken from /a/20871997 (Selman Genç)
[ChildActionOnly]
public ActionResult GetHtmlFile(String path)
{
// other stuff
// consider using Server.MapPath(path) if in doubt determining file path
return new FilePathResult(path, "text/html");
}
Usage as link in view:
<li>#Html.ActionLink("HTML File", "GetHtmlFile", "Controller", new { path = "~/Views/Home/PersonalRecords.html" }, null)</li>
Similar issues:
Rendering .html files as views in ASP.NET MVC
Render HTML file in ASP.NET MVC view?
I am trying to upload an image created from Java's toDataURL, submitted in a form automatically with javascript, captured by PHP and converted using imagecreatefrompng() and assigned to a variable.
Here is the code to start with:
Javascript code:
if(getImageData == true){
console.log("Saving avatar as image...");
window.setTimeout(function () {
imgData = renderer.domElement.toDataURL("image/png");
document.getElementById('avatarimg').src = imgData;
document.getElementById("timg").value = imgData;
console.log(imgData);
document.getElementById("form1").submit();
console.log("Avatar saved as PNG img.");
}, 300);
getImageData = false;
PHP code:
if($_POST['timg']){
$renderedav = imagecreatefrompng($_POST['timg']);
imageAlphaBlending($renderedav, true);
imageSaveAlpha($renderedav, true);
$target = "images/Avatars/";
$newname = md5($_POST['timg']);
echo ("<font color='#000000'>Image rendered. - " . $newname . " </font>");
$target = $target . $newname . ".png";
if(move_uploaded_file($renderedav, $target))
{ echo("File uploaded."); }else{echo("Error uploading file.");}
}
When I display the image as a raw img using the imgData, everything looks great, but I want to create an actual image from that data and upload it to a directory on my database using the name created in $newname. Is this possible to do? Am I going about it correctly? I know move_uploaded_file() is intended to move a suspended file from a file form element to a new location, but in my research I couldn't find another method that does this.
There are a couple things here that are not going to work:
You can not write text over top by echoing some html, you have to use a gdlib text function like imagettftext(). One note, you have to point to a font file to use it (Resource here). If you are not trying to write this echo ("<font color='#000000'>Image rendered. - " . $newname . " </font>"); over top of the image, disregard this part of the script HOWEVER, you still can not do it because if you echo anything (or have empty space before your script), it will corrupt the image.
You have to use imagepng() (Resource here) to save the file.
PHP Script:
if($_POST['timg']){
// Set file path info
$target = "images/Avatars/";
$newname = md5($_POST['timg']);
$target = $target.$newname.".png";
// Start gdlib functions
$renderedav = imagecreatefrompng($_POST['timg']);
imagealphablending($renderedav, true);
imagesavealpha($renderedav, true);
$fColor_white = imagecolorallocate($renderedav, 255, 255, 255);
// Path to truetype font
$font = 'font.TTF';
// Add text to image
imagettftext($renderedav, 25, 0, 75, 300, $fColor_white, $font, "Image rendered. - ".$newname);
// Here you output the png and use the second parameter to save to a destination
imagepng($renderedav,$target);
// Now you destroy the resouce
imagedestroy($renderedav);
}
I had this code inside the <div id="chtmsg"> on a page that shows a messenger...
PHP :
if($perguntas){
for($c=0;$c<count($perguntas);$c++){
$perguntas[$c]->tipo == 'F' ? $class = 'message_F' : $class = 'message_P';
$hora = substr($perguntas[$c]->hora, 0, 5);
echo "<li class=\"".$class."\"><p>".$perguntas[$c]->mensagem."</p><span>".$pergunta->databr($perguntas[$c]->data)." - ".$hora."</span></li>";
if($perguntas[$c]->tipo=='F' and $perguntas[$c]->status == 0){
$pergunta->marcaRespLida($perguntas[$c]->id);
}
}
}
It works very well. So, I wanted to load it with js to refresh all new messages only inside the div #chtmsg and then I created a file msg.php and with the <?php include("msg");?> it continues working good, but with js I needed to put the path...
HTML :
$(document).ready(function () {
setInterval(function() {
$.get(hostGlobal+'site/modulos/produto/msg.php', function (result) {
$('#chtmsg').html(result);
scTop();
});
}, 3000);
});
But its shows the error inside de div...
Notice: Undefined variable: perguntas in /Applications/XAMPP/xamppfiles/htdocs/sisconbr-sistema-novo/site/modulos/produto/msg.php on line 3
I tested other codes inside the msg.php file and works ok without variables...
Just a thought...
Your first line in PHP
if($perguntas){
Should perhaps check if defined like so
if(isset($perguntas)){
My suggestion explained in another answer here
For better code, You should preferably use:
if (isset($perguntas) && is_array($perguntas)){