My problem is not being able to encode the image properly after retrieving it from the database otherwise all my work is fine. After I fetch the image I managed to display it at the same php file using "header('content-type: image/jpeg')".
<?php
header('content-type: image/jpeg');
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "select image from images order by id desc limit 1";
require_once('connection.php');
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
echo base64_decode($result['image']);
mysqli_close($con);
}else{
echo "Error";
}
?>
The previous piece of code is for displaying directly but it was for testing only, I need to use it as a JSON source so I modified it in this way:
header('Content-type: application/json');
.
.
.
$r['a'] = base64_encode( $result['image']);
echo json_encode($r);
For the Jquery and Ajax part also worked fine and I tested it by making another json file and put an image encoded professionally by this website https://www.base64-image.de/.
And here is Jquery code:
$(document).ready(function(){
(function()
{
d='';
var poll=function()
{
$.ajax({
url: "getjson.php",
type :"get",
dataType: "JSON",
success: function(json)
{
d +='data:image/jpeg;base64,';
d +=json.a;
$("#myimg2").attr("src",d);
}
})
};
poll();
setInterval(function(){
poll();
}, 2000);
})();
});
What I need now is to encode the image just like what this website does https://www.base64-image.de/ because this line base64_encode( $result['image']) seems to be not enough, I have tried many solutions available online but no one worked for me!
Related
I'm working with a CMS project.
Currently I want to build a rating system there but unfortunately that rating system require's JQUERY I'm # learning position on jQuery.
buy my knowledge in working with this rating system.
db ::tables ::columns = id,path,likes,dislikes..
Index.php
<?php
include 'db.php';
include 'conf.php';
$path = $home_path;
$q = "select * from likes where path='".$path."'";
$res = mysqli_fetch_assoc(mysqli_query($mysqli ,$q));
echo 'Likes('.$res["yes"].') ';
echo 'Unlikes('.$res["no"].')';
**Here I wanted to send my parameters with like() function and pass them via jQuery and contact the php page ..and I want the results back from that php page. Like I want to get the json reply **
Kindly please help me.
I meant I need that full jquery code.
And can you please explain me how is that working.
Like what I tried to say is:
index.php & #post_rating.php
<head>
<title>The jQuery Example</title>
<script type ="text/javascript"
src ="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type ="text/javascript" language="javascript">
$(document).ready(function() {
$("#like").click(function(path,type){ //i want to get the values
with this function here
$.ajax({
type: "POST",
url: "post_rating.php",
data: "path=" +path + "&type=" +type,
success: function(){alert('success');}
/////i want to show the the
reply which is producded by php-json page post_rating.php
});
});
});
</script>
</head>
<body>
<?php
include 'db.php';
include 'conf.php';
$path = $home_path;
$q = "select * from likes where path='".$path."'";
$res = mysqli_fetch_assoc(mysqli_query($mysqli ,$q));
echo 'Likes('.$res["yes"].') ';
echo 'Unlikes('.$res["no"].') ';
?>
#post_rating.php
<?php
if(isset($_REQUEST["path"]) && isset($_REQUEST["type"])){
$path = $_REQUEST["path"];
$type = $_REQUEST["type"];
if($type =="dislike"){
$reply = 'you disliked this page '.$path.'';
}
elseif($type =="like"){
$reply = echo 'you lick this page : '.$path.'';
}
json_encode($reply);
}
?>
I'm pulling data from a mysql db using php and echoing a json_encoded array.
Using ajax I pull in the results and set the values of various dom elements. I have a string which has some html tags eg <p></p>.
When I set the element $("#element").html(data['text']) it adds double quotes to the text and all of the html elements appear as text.
I can't seem to remove the quotes using replace. Oddly when I alert the value there are no quotes. They only appear in the html when I view the code.
What is the best way to include html with text? And how do I get jquery to render this has html and not text?
Many thanks!
PHP / MySQL
//Article by id
if(isset($_GET['do']) && $_GET['do']=='get_art') {
$content = array();
$id = clean_input($_GET['id']);
$q = "SELECT * FROM articles WHERE id = '$id'";
$r = $conn->query($q);
$row = $r->fetch_assoc();
$content['title'] = str_replace("€", '€', $row['title']);
$content['img'] = $row['img'];
$content['text'] = str_replace('€', '€', $row['text']);
$content['text'] = htmlentities($row['text']);
echo json_encode($content);
}
//end article by id
jQuery
//load article onclick
$('body').on('click', '.get_art', function (e) {
e.preventDefault();
var href = $(this).attr('href').replace('#', ' ');
$.ajax({
url: 'actions.inc.php?do=get_art&id=' + href,
dataType: 'json',
type: 'post',
success: function(data) {
var art_text = data['text'];
art_text = art_text.replace('€', '€');
$("#art_img").attr("src", "images/" + data['img']);
$("#art_title").html(data['title']);
$("#art_text").html($.parseHTML(art_text));
} //end success
});//end ajax
});
//end load
The htmlentities (php) was making a mess of things, got it working now after I console logged the output from the php file
I'm doing a project for an exam. I'm stuck with that and I hope someone of you could help me (I'm italian, so sorry for my bad english!).
I have to query an existing database stored in phpmyadmin with a PHP script. Then, the query result need to be parsed with a jquery script and printed to an HTML page.
Here is the PHP script:
<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Errore di connessione: ' . mysql_error());
}
mysql_select_db("progetto_lpw", $con);
$sql="SELECT denominazione FROM farmacia";
$result = mysql_query($sql) or die(mysql_error());
$num=mysql_numrows($result);
while($row = mysql_fetch_array($result)){
print json_encode($row['denominazione']);
print "<br />";
}
?>
I've already tested the PHP script calling it via browser and it works.
Then, I parse the result with this jquery script (the use of this combination is a requirement of the project):
$("#button").click(function(){
$.getJSON('json.php', function(data) {
$.each(data, function(index,value){
$("#xx").append("<p>"+value+"</p>")
})
})
})
Here is the problem: when I open the HTML page and I click the button on firefox, consolle says "no element found" referring to PHP script.
"xx" is the id of the div in which elements are printed.
Where is the error?
Thanks to everyone.
Replace below code
while ($row = mysql_fetch_array($result)) {
print json_encode($row['denominazione']);
print "<br />";
}
With below code and try
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row['denominazione'];
}
header('Content-type: application/json');
echo json_encode($rows);
HTML
<button id="button">Fetch JSON</button>
<div id="xx"></div>
JS
$("#button").click(function() {
$.getJSON('json.php', function(data) {
$.each(data, function(index, value) {
$("#xx").append("<p>" + value + "</p>")
});
});
});
Response from json.php should be in below format
["AGGERI","ALCHEMICA 1961"]
The reason your code isn't working is that it's producing output like this:
"foo"<br />
"bar"<br />
That's not valid JSON. To be valid, you have to not have the HTML <br /> in there (this is JSON, not HTML), and you have to have commas between the elements you want to return.
json_encode will handle formatting the array correctly for you.
jsFiddle Demo with post request to send and get json output
'print' works differently then 'echo'. At least i am sending JSON packages with echo from php.
Can you replace it ?
// in php
echo json_encode($row['denominazione']);
// in jquery script, best to place "<br />" tag here
$("#xx").append("<p>"+value+"</p><br />")
I'm building an audio player that makes 3 different API calls, and I need them all to be in JSONP format, so I made a PHP proxy file that determines the output of the JSON data like so:
$datatype = $_GET["type"];
$artist = urlencode($_GET["artist"]);
$album = urlencode($_GET["album"]);
$content = "";
if($datatype == 'albumart'){
$content = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=037358e302c80571663e6a7a66b1dc05&artist=' . $artist . '&album=' . $album . '&format=json');
} elseif($datatype == 'artistart'){
$content = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=037358e302c80571663e6a7a66b1dc05&artist=' . $artist . '&autocorrect=1&format=json');
} else {
$content = file_get_contents('http://cjzn.streamon.fm/metadata/recentevents/CJZN-48k.json');
}
header('Content-type: application/json; charset=utf-8');
echo $_GET['callback'] . '(' . json_encode($content) . ')';
Upon testing the output it seems to work fine, it gets the respective API data, wraps it in the JSONP () and accepts a JSONP callback.
Bur when I try and use it in my Javascript file it doesn't seem to work, but I can't figure out why! Here's an example of one of the functions being used to call the JSON data:
function getAlbumArt(artist,album){
var dataArtist = artist,
dataAlbum = album,
albumArtURL;
$.ajax({
url: 'jsonproxy.php',
dataType: 'jsonp',
data: {
type: 'albumart',
artist: dataArtist,
album: dataAlbum
},
success: function(data) {
if(data.album.image[4]["#text"]){
var albumArtURL = data.album.image[4]["#text"];
$('section.player div.album-artwork').css({'background-image':'url("' + albumArtURL + '")'});
} else {
getArtistArt(dataArtist);
}
},
error: function() {
getArtistArt(dataArtist);
alert('Sorry, unable to retrieve album artwork!');
}
});
}
Can anyone help with why this doesn't work for me?
Edit
I did alert(data); on success, and that returned all of the data from the feed, after that if I did something more specific like alert(data.album.image[4]["#text"]); it returned undefined. Very confused here. Anyone have any thoughts?
I have a function in javascript called "dumpData" which I call from a button on an html page as **onlick="dumpData(dbControl);"* What it does is return an xml file of the settings (to an alert box right now). I want to return it to the user as a file download. Is there a way to create a button when click will open a file download box and ask the user to save or open it? (sorta of like right-clicking and save target as)...
Or can it be sent to a php file and use export();? Not sure how I would send a long string like that to php and have it simple send it back as a file download.
Dennis
I don't think you can do that with javascipt, at least not with a nice solution.
Here's how to force a download of a file in PHP:
$file = "myfile.xml";
header('Content-Type: application/xml');
header("Content-Disposition: attachment; filename='$file'");
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
Instead of using readfile to output your file, you could also directly display content using echo.
/EDIT: hell, someone was faster :).
EDITED:
just a proof of concept.. but you get the idea!
instead of
<a onlick="dumpData(dbControl); href="#">xml file</a>
you can have like this:
xml file
then like this:
// Assuming your js dumpData(dbControl); is doing the same thing,
// retrieve data from db!
$xml = mysql_query('SELECT * FROM xml WHERE id= $_GET['id'] ');
header("Content-type: text/xml");
echo $xml;
I eneded up going this route:
The HTML code
<script type="text/javascript">
$(document).ready(function() {
$("#save").click(function(e) { openDialog() } );
});
</script>
<button id="save" >Send for processing.</button>
The javascript code:
function openDialog() {
$("#addEditDialog").dialog("destroy");
$("#Name").val('');
$("#addEditDialog").dialog({
modal: true,
width: 600,
zIndex: 3999,
resizable: false,
buttons: {
"Done": function () {
var XMLname = $("#Name").val();
var XML = dumpXMLDocument(XMLname,geomInfo);
var filename = new Date().getTime();
$.get('sendTo.php?' + filename,{'XML':XML}, function() {
addListItem(XMLname, filename + ".XML");
});
$(this).dialog('close');
},
"Cancel": function () {
$("#Name").val('');
$(this).dialog('close');
//var XMLname = null;
}
}
});
}
PHP Code, I just decided to write the file out to a directory. Since I created the filename in the javascript and passed to PHP, I knew where it was and the filename, so I populated a side panel with a link to the file.
<?php
if(count($_GET)>0)
{
$keys = array_keys($_GET);
// first parameter is a timestamp so good enough for filename
$XMLFile = "./data/" . $keys[0] . ".kml";
echo $XMLFile;
$fh = fopen($XMLFile, 'w');
$XML = html_entity_decode($_GET["XML"]);
$XML = str_replace( '\"', '"', $XML );
fwrite($fh, $XML);
fclose($fh);
}
//echo "{'success':true}";
echo "XMLFile: ".$XMLFile;
?>
I don't know why, but when I send the XML to my php file it wrote out the contents withs escape charters on all qoutes and double quotes. So I had to do a str_replace to properly format the xml file. Anyone know why this happens?
POST the XML via a form to a php script that writes it back to the client with a Content-Disposition: attachment; filename=xxx.xml header.
<form name="xml_sender" action="i_return_what_i_was_posted.php" method="POST">
<input type="hidden" name="the_xml" value="" />
</form>
Then with js
function dumpData(arg) {
var parsedXML = ??? //whatever you do to get the xml
//assign it to the the_xml field of the form
document.forms["xml_sender"].the_xml.value = parsedXML;
//send it to the script
document.forms["xml_sender"].submit();
}
Can't remember if this loses the original window, if so, post to an iframe.