In jQuery I have:
url = "http://example.com/";
$('div').append('<img src="'+url+'/get_image/10">');
In Laravel I have a function named get_image contains:
public function get_image($id)
{
$media = Media::where('id', $id)->first()->file_path;
return 'data:image/png;base64,'.base64_encode(file_get_contents($media));
}
but when I open the page the src attribute contains:
http://example.com/show_image/36
however I want this to be shown:
data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==
that the result would be the image in base64_encoded.
How can I fix this to show the base64 content of image instead of the url?
Thanks
try to use Get fist ;
$.get( "http://example.com/show_image/36", function( data ) {
$('div').append('<img src="'+data+'"');
});
Hope This Help,
Related
now im doing AXIOS code combine with laravel to get image from instagram URL. the URL is this https://www.instagram.com/p/B_zZCRpB895/media/?size=t
AXIOS is new from me. to get the image, i tried this simple code. i set this code into my frontend site
<img id="imgsrc" src="" >
<script>
axios
.get('https://www.instagram.com/p/B_zZCRpB895/media/?size=t', {
responseType: 'arraybuffer'
})
.then(response => {
const buffer = Buffer.from(response.data, 'base64');
document.getElementById("imgsrc").src = Buffer;
console.log(Buffer);
})
.catch(ex => {
console.error(ex);
});
</script>
but the image not display into <img id="imgsrc" src="" >
i really want that, when we open the page. the instagram image can display.
how to solve this matter. please help.
you can use file reader to get base64 and set it as the image source :
<script>
axios.get('https://www.instagram.com/p/B_zZCRpB895/media/?size=t', {responseType: "blob"})
.then(function (response) {
var reader = new window.FileReader();
reader.readAsDataURL(response.data);
reader.onload = function () {
document.getElementById("imgsrc").src = reader.result;
}
});
</script>
Is there a particular reason you are retrieving this via an AJAX call using axios?
The endpoint you provided returns an image source already. To make it appear in the image element all you need to do is set the src to the endpoint URL as shown below. Unless you need to run a process to do something to the image you don't need to get the data as an array buffer.
document.getElementById("imgsrc").src = "https://www.instagram.com/p/B_zZCRpB895/media/?size=t";
I have this PHP File called print.php:
<?php
require_once("modules/pdf/dompdf_config.inc.php");
$html = $_POST["toRender"];
$number = $_POST["number"];
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream($number.".pdf");
As you can see, the HTML and a Number are received via POST.
The JavaScript file looks like this:
$("#btnViewPDF").click(function() {
var theHtml = $("#printable").html();
var theNumber = $("#invoiceNumber").val();
$.ajax({
type : "post",
url : "views/print.php",
data : {toRender : theHtml, number : theNumber},
beforeSend: function() {
$(".ajax-loader-bg").fadeIn();
}
}).always(function() {
$(".ajax-loader-bg").fadeOut();
});
return false;
});
Basically it takes all the content inside a DIV called 'printable' but what I want next is the PDF that has been generated in print.php to be displayed, I haven't been able to figure out how can I make this.
I've made it work when I generate test HTML inside print.php and then I type in the url mysite.com/print.php ... it renders the PDF and allows me to download it or see it in another browser tab.
How can I achieve this via AJAX?
You can't download something via AJAX, you could simulate the behavior using an hidden iframe.
Not that you can't download it, but, it will never end up in the filesystem for saving purpose because javascript can't do that for security reasons.
Anyway people always find solutions, you can try this: https://stackoverflow.com/a/23797348/1131176
i did achieve this, by doing just a trick, this example is made in codeigniter, so you can adapt it, first, the ajax method:
$.ajax({
url: base_url+"controladorapr/exportComprobanteIngresos", //method i called
data: $(this).serialize() //i serialized data from a form,
type:"POST",
dataType: 'JSON',
success: function (data) {
//create a link to download the pdf file
var link=document.createElement('a');
//i used the base url to target a file on mi proyect folder
link.href=window.URL = base_url+"exportacion.pdf";
//download the name with a different name given in the php method
link.download=data.nombre_archivo;
link.click();
//this js function hides the loading gif i use
hideLoad();
}
});
Now, let's head to the method on my controller:
function exportComprobanteIngresos(){
//receive your ajax data
$fecha = $this->input->post("fecha_comprobante_ingresos");
$fecha = date_format(DateTime::createFromFormat('d/m/Y', $fecha), "Y-m-d");
//send data to pdf
$data["fecha"] = $fecha;
//do some query here to send data and save it into $data[] array
//pdf size
$tamaño = 'A4';
//create a file name
$nombre_archivo = "Comprobante_ingresos".date_format(DateTime::createFromFormat('Y-m-d', $fecha), "Y_m_d").".pdf";
//load dompdf method, i will show this later, and send the data from db and file name
$pdf = $this->pdf->load_view("pdf/comprobanteIngresos", $data, $tamaño, $nombre_archivo);
//save the pdf content into the file we are downloading
file_put_contents('exportacion.pdf', $pdf);
//send data back to javascript
$data2["nombre_archivo"] = $nombre_archivo;
echo json_encode($data2);
}
now, we will include dompdf, to use dompdf on codeigniter see this answer: Codeigniter with dompdf
Now, this is the code from dompdf i use in the function '$this->pdf->load_view':
$dompdf = new Dompdf();
$html = $this->ci()->load->view($view, $data, TRUE);
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation
$dompdf->setPaper($size, 'portrait');
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to variable and return it to save it into the file
$output = $dompdf->output();
return $output;
now with this, i managed to use ajax with dompdf and put a loading gif to it, and it works great, by last, the php file you load on '$this->pdf->load_view' doesn't have a header or else, is pure html and php, hope this helps!
I really need some help here!
I have a page with images in groups of 1, 2, or 3. I click on an image and the class gets sent to some jquery ajax stuff to get the id(mysql) then this gets sent to a php file to build the html for the images to display on a div in my page. This bit works OK, but I'm trying to use the galleria plugin to show the image that haave been sent, but it just act like galleria is not there! If I hardcode some images in the dive. galleria works as it should!
here is my project.js file
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.post('../inc/showprojects.php', {project: projectvalue}, function(data) {
$('#shownews').html(data);
});
});
This is my showproducts.php file
<?php
include 'connect.php';
// if no project was sent, display some error message
if(!isset($_POST['project'])) {
die('No project has been chosen');
}
// cast the project to integer (just a little bit of basic security)
$project = (int) $_POST['project'];
// this will be the string that you will return into the shownews div
$returnHtml = '';
$q = "SELECT * FROM projects WHERE id='$project'";
if($r = mysql_query($q)) {
// construct the html to return
while($row = mysql_fetch_array($r)) {
$returnHtml .= "<img src='{$row['filename']}' />";
$returnHtml .= "<img src='{$row['filename1']}' />";
$returnHtml .= "<img src='{$row['filename2']}' />";
}
}
// display the html (you actually return it this way)
echo $returnHtml;
?>
This is how I'm calling galleria on the div
// Load the classic theme
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
// Initialize Galleria
$('#shownews').galleria();
Can anyone help me out?
Thanks
try this one
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.ajax({url:'../inc/showprojects.php',
type:'POST' ,
method,async:false ,
data:{project: projectvalue},
success:function(data) {
$('#shownews').html(data);
}});
Galleria.run('#shownews');
});
I think, you need to call Galleria.run after recieve data from php
EDIT: ugly way - destroy gallery, if already running before inserting new images into div
if($('#shownews').data('galleria')){$('#shownews').data('galleria').destroy()} //destroy, if allready running
$.post('../inc/showprojects.php', {project: projectvalue}, function(data) {
$('#shownews').html(data);
Galleria.run('#shownews');
});
and remove $('#shownews').galleria();
EDIT 2: use Galleria's .load api to load new data
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.post('../inc/showprojects.php', {project: projectvalue},
function(data) {
$('#shownews').data('galleria').load(data);
},"json"
);
});
PHP
<?php
include 'connect.php';
// if no project was sent, display some error message
if(!isset($_POST['project'])) {
die('No project has been chosen');
}
// cast the project to integer (just a little bit of basic security)
$project = (int) $_POST['project'];
// this will be data array that you will return into galleria
$returnData = array();
$q = "SELECT * FROM projects WHERE id='$project'";
if($r = mysql_query($q)) {
// construct datat object to return
while($row = mysql_fetch_array($r)) {
$returnData[] = array('image'=>$row['filename']);
$returnData[] = array('image'=>$row['filename1']);
$returnData[] = array('image'=>$row['filename2']);
}
}
// return JSON
echo json_encode($returnData);
?>
Galleria init:
(Gallery will be empty until you will load data into it)
// Load the classic theme
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
// Initialize Galleria
Galleria.run('#shownews');
Try loading galleria after the ajax request has successfully completed. By doing this jquery waits until ShowNews has been rendered and then runs galleria.
$.ajax(
{
type: "POST",
url:'../inc/showprojects.php',
data:{project: projectvalue},
success: function(data)
{
$('#shownews').html(data);
},
complete: function()
{
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
$('#shownews').galleria();
}
});
I use this method whenever i gather the image data from a remote source. Hope this helps!
I tried this answer and other answers on the web and nothing worked. Then I moved galleria-1.3.5.min.js to the parent page and it worked. What an amazingly simple solution!
I'm in a page called 'add.cpt' that has a list of images. The user has the option to remove the images but I can't make it work. In the event of click I try to call an ajax trying to pass the name of the image and id of the item (.../item/imageName) but it does delete the image and alerts what seems to be the content of delete_photo_file.ctp. It looks like the ajax is using the URL but it is not sending the data to delete the file wanted.
ItemsController:
App::uses('File', 'Utility');
class ItemsController extends AppController{
[...]
public function deletePhotoFile(){
//$this->autoRender = false; //did not tested but maybe I need to use this
$imgName = //don't know how to get it from ajax call
$itemId = //don't know how to get it from ajax call
$file = new File($dir.'/'.$itemId.'/'.$imgName);
$file->delete();
}
}
Ajax Call (from my ctp file):
$('#delete').click(function (){
[...]
var itemId=$('#itemId').val(); //comes from hidden input
var imgName = $('#imgName').val(); //comes from hidden input
$.ajax({
type: 'POST',
url:'http://localhost/html/Project/v5/CakeStrap/items/deletePhotoFile/',
data:{"itemId":itemId, imgName: imgName},
success: function(data){
alert(data); //alerts some HTML... seems to be delete_photo_file.ctp content
}
});
});
Can anyone help me? Thanks!
In your ItemsController, make sure you actually load the File utility class, by adding:
App::uses('File', 'Utility');
Just below the opening <?php tag before your class definition. In your action you can just use $this->request->data to get the data keys. Also, return the action of the delete() function, so you can trigger your AJAX success/error call accordingly.
public function deletePhotoFile() {
$imgName = $this->request->data['imgName'];
$itemId = $this->request->data['itemId'];
/**
* Where is the $dir below actually set? Make sure to pass it properly!
* Furthermore, it's always cleaner to use DS constant
* (short for DIRECTORY_SEPARATOR), so the code will work on any OS
*/
$file = new File($dir . DS . $itemId . DS . $imgName);
return $file->delete();
}
Finally, mind your quotes in the AJAX call:
data:{"itemId":itemId, imgName: imgName},
Should become:
data:{"itemId":itemId, "imgName": imgName},
As otherwise, you just call the imgName JS var twice.
In the php $imgName = $this->request->data('imgName'); $itemId = $this->request->data('imgId'); In the js you might want to put quotes around the variable name since it's the same as the name of the value being passed data: {'itemId': itemId, 'imgName': imgName},
To get the data out simply debug($this->request->data) in your deletePhotoFile() method and check the response in your browsers console, it should be a nicely formatted array with the data you POST`d over in your ajax request, you should be able to work out the rest from there.
You'll also want to look into using the RequestHandler component so you can assure the request is an ajax request.
i'm a little stuck with a jQuery. At the moment my function looks like this.
$(function(){
$(".url2").keyup(validNum).blur(validNum);
function validNum() {
var initVal = $(this).val();
outputVal = initVal.replace(/(https?:\/\/)?(www.)?[0-9A-Za-z-]{2,50}\.[a-zA-Z]{2,4}([\/\w\-\.,#?^=%&:/~\+#]*[\w\-\#?^=%&/~\+#]){0,250}(\s){1}$/
,"http://my.site/ref.php?id=<?php $code = unqiue-ref-id(); echo $unqiue-ref-id;?>");
if (initVal != outputVal) {
$(this).val(outputVal);
return false;
}}
});
So right now it rewrites a user typed url (in a textarea) to a redirection link with my own url (e.g. my.site?ref.php?id=unique12. What I need exactly is a POST Request to a php file (code below) where the valid user-url is given to the php file as a var and then the php file should give back a var with the generated unique unique-ref-id. I do of course know that the code above isn't working like that, it only shows how the final result should look like. The php file wich generates the unique-ref-id looks like this.
function unqiue-ref-id() {
$unqiue-ref-id = "";
$lenght=4;
$string="abcdefghijklmnopqrstuvwxyz123456789";
mt_srand((double)microtime()*1000000);
for ($i=1; $i <= $lenght; $i++) {
$shorturl .= substr($string, mt_rand(0,strlen($string)-1), 1);
}
return $unqiue-ref-id;
}
$user-url = // var send from jquery
do{
$unqiue-ref-id = unqiue-ref-id();
} while(in_array($unqiue-ref-id, $result));
// var send back to jquery function => final results of do function above
// Here i add the $user-url and $unique-ref-id to datebase (Dont need code for that)
?>
Would be so great if someone can help me out with that. Thanks a lot :)
Use the POST jQuery's method. Here's an example
$.post('URL-TO-POST-DATA', {'parameter1': 'value', 'parameter2': 'value'}, function(data_received){
/** Here goes your callback function **/ alert(data_received);
});
More information about POST method
Don't forget one thing. jQuery will not receive nothing if you don't use echo on PHP (instead of return). You MUST use echo in PHP, don't forget it.