Ajax Base64 Image Response Text - php

I am sending ajax request to the server as :
Client Side Code :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script language="">
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var imgVal='img_id'+1;
xmlhttp.open("GET","imageprovider.php",false);
xmlhttp.send();
if(xmlhttp.readyState==4)
{
alert(xmlhttp.responseText);
document.getElementById('img').appendChild(xmlhttp.responseText);
}
</script>
</head>
<body>
<div id='img'>
</div>
</body>
And here is the server side code that shows a simple image with base64 encode.How can i get the response from client the above code and show it.
Server Side PHP Code :
<?php
$img_src = "images/1.png";
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
?>

Try replacing
document.getElementById('img').appendChild(xmlhttp.responseText);
with
document.getElementById('img').innerHTML = xmlhttp.responseText;
Or, if you need to continue using .appendChild(), try replacing
document.getElementById('img').appendChild(xmlhttp.responseText);
with
var o = document.createElement('img');
o.src = xmlhttp.responseText;
document.getElementById('img').appendChild(o);
And replacing
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
with
echo 'data:image/jpg;base64,'.$img_str;

you capture the response
you inject the response into the DOM
Whith jQuery the code would be something like this:
$.ajax({
url: "imageprovider.php",
context: document.body,
success: function(data){
$('#objectToAddImage').html(data);
}
});
Nevertheless I would advise against passing the image as a base64 as the browser will have no way to cache it. If passing the image as a base64 encode is not an absolute requirement of your project I would recommend the server simple pass a link to the actual image.

Related

ajax will not send canvas data to php

This is the code in my js
(function(){
var video = document.getElementById('video'),
canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
photo = document.getElementById('photo'),
vendorUrl = window.URL || window.webkitURL;
datas = canvas.toDataURL('images/png');
navigator.getMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;
navigator.getMedia({
video: true,
audio: false
}, function(stream){
video.src = vendorUrl.createObjectURL(stream);
video.play();
}, function(error){
});
document.getElementById('capture').addEventListener('click',function(){
context.drawImage(video, 0, 0, 400, 300);
photo.setAttribute('src', canvas.toDataURL('images/png'));
datas = canvas.toDataURL('images/png');
});
var canvasData = canvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'webcam.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData);
})();
This is the php code to receive the data
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
echo "true";
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>
<head>
<meta charset="UTF-8">
<Title>Document</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="booth">
<video id = "video" width="400" height="300"></video>
Snap Shot
<canvas id="canvas" width="400" height="300"></canvas>
<img id ="photo" name = "photo" src="images/events/default.png" alt="Photo of you">
</div>
<script src="js/photo.js"></script>
</body>
<?php
?>
The application intends to take a snapshot of the user and saves the photo via javascript. I am trying to find a way to send the data back to php and utilize it to save into the database. I understand it is saved in base64 encode. I tried different methods of Ajax including the one I have saved, but the data tends to not send any data to the php folder.
Thank you in advanced.
I just suggest you to check some of you code points:
Form content type. To upload files you must use "multipart/form-data"
ajax.setRequestHeader('Content-Type', 'multipart/form-data');
You can use FormData class in JS to make form data before sending:
https://developer.mozilla.org/en/docs/Web/API/FormData/append
Canvas function "toDataURL" have no mime types "images/png". Just "image/png"

I'm trying to src a js file containing XMHTTPRequest script into my HTML

If I embed my XHR file into my HTML document directly, everything works fine. As soon as I src it via
<script type="text/javascript" src="js/ajax_gallery.js">ajax_json_gallery('gallery');</script>
Nothing works, and I get no errors. I'm assuming it's something to do with the XHR being created in a separate file to the HTML. I just don't like XHR script cluttering up my HTML, I just want to load as an external JS file.
I've moved my main 3 scripts, galleryHandle.php, XHR.js, ajax_gallery.html all to the same dir level to keep things simple. And the gallery images are in a folder called "gallery", also on the same level.
Here's my code:
HTML
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/gallery.css" />
</head>
<body>
<div id="pagetop"></div>
<div id="thumbnailbox"></div>
<div id="pictureframe"></div>
<script type="text/javascript" src="XHR.js">ajax_json_gallery('gallery');</script>
</body>
</html>
JavaScript
function ajax_json_gallery(folder) {
"use strict";
var httpRequest = new XMLHttpRequest();
document.getElementById("pagetop").innerHTML = "dynamic ajax json gallery";
var thumbnailbox = document.getElementById("thumbnailbox");
httpRequest.open("POST", "galleryHandle.php", true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
var pictureframe;
pictureframe.innerHTML = "<img src='"+data.img1.src+"'>";
thumbnailbox.innerHTML = "";
for (var obj in data) {
if (data[obj].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+data[obj].src+'\')"><img src="'+data[obj].src+'"></div>';
}
}
}
};
httpRequest.send("folder="+folder);
thumbnailbox.innerHTML = "Loading...";
}
function putinframe(src) {
"use strict";
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src = " '+src+' " >';
}
PHP
<?php
header("Content-Type: application/json");
//bring in folder name
$folder = $_POST["folder"];
//start componding json
$jsonData = '{';
//compound directory path
$dir = $folder."/";
//open directory
$dirHandle = opendir($dir);
//init while looop
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && strpos($file, '.jpg')){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
I understand there are some redundancies in my code but it's just a tutorial I'm going through to learn the basics of JSON building with POST, XHR.
Anyway, help appreciated as always.
Thanks
Explanation
FROM W3C:
<script type="text/javascript" src="myscript.js">
alert('I am pointless as I won\'t be executed');
</script>
Upon meeting this element in a page, browsers will then load the file myscript.js and execute it. Any content inside the script element itself will be skipped when you provide a src attribute. The [last] example will load the file myscript.js and execute the code in it but will not execute the alert inside the script element at all.
Solution
Try the following in your head tags:
HTML
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">
ajax_json_gallery('gallery');
</script>
<script type="text/javascript" src="XHR.js">
You can't have src attribute and javascript both in a single tag. Separate them out. Like this...
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">ajax_json_gallery('gallery');</script>

get content back to javascript from PHP file in JSON format

When sending the request from the jQuery Mobile script to the specified PHP file, nothing is returned, nothing is appended to the html file. Here's the URL of the page:
localhost/basket/newstext.html?url=http://www.basket-planet.com/ru/news/9235
newstext.html:
<head>
<script src="js/newstext.js"></script>
</head>
<body>
<div data-role="page" id="newstext">
<div data-role="content">
<div id="textcontent"></div>
</div>
</div>
</body>
newstext.js:
var serviceURL = "http://localhost/basket/services/";
$('#newstext').bind('pageshow', function(event) {
var url = getUrlVars()["url"];
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText);
});
function displayNewsText(data){
var newstext = data.item;
console.log(newstext);
$('#textcontent').text(newstext);
$('#textcontent').trigger('create');
}
function getUrlVars(){
//it displays in the alert perfectly, shortening the message here
}
getnewstext.php:
<?php
include_once ('simple_html_dom.php');
$url = $_GET['url'];
$html = file_get_html(''.$url.'');
$article = $html->find('div[class=newsItem]');
$a = str_get_html(implode("\n", (array)$article));
//parse the article
header("Content-type: application/json");
echo '{"item":'. json_encode($a) .'}';
?>
I think my problem is how I'm encoding the $a variable in the PHP script. The $a variable contains html tags of all kind...how can I append it in the html file?
Where you have this line:
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText);
Change it to be:
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText, function(response){
$('#elem').append(response);
});
Where #elem is the name of the element that you want to append the data, returned from the PHP file, to.

syntax highlighter doesn't work after call back

So I'm new to Js & php and I'm trying to print out a piece of code from a call back function
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","callback_json.php",true);
xmlhttp.send();
}
</script>
<title>Simple Cross Domain Ajax</title>
</head>
<body>
<h1>.....</h1>
<h2>.....</h2>
<button onclick="loadXMLDoc();">Get Data</button>
<div id="myDiv"><h2>...</h2></div>
</body>
</html>
and my php file goes like
<?php
$ch = curl_init();
$url='someurl';
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
echo "<script type='text/javascript' src='syntaxhighlighter/scripts/shCore.js'></script><script type='text/javascript' src='syntaxhighlighter/scripts/shBrushJava.js'></script><link href='syntaxhighlighter/styles/shCore.css' rel='stylesheet' type='text/css' /><link href='syntaxhighlighter/styles/shThemeDefault.css' rel='stylesheet' type='text/css' />";
echo "<pre class='brush:java;'>";
echo $data;
echo "</pre>";
echo '<script type="text/javascript">SyntaxHighlighter.highlight();</script>';
?>
And it seems syntax highlighter works on my php file but not after call back...I did some research and I know I'm supposed to use SyntaxHighlighter.highlight() instead of all() in the code but I've already done that. Is there any problem with my code structure?
<script> tags added by innerHTML are not executed by the browser. You need to execute them manually:
var scripts = document.getElementById("myDiv").getElementsByTagName("script");
if (scripts && scripts.length) {
for (var i =0; i<scripts.length; i++) {
eval(scripts[i].innerHTML);
}
}
Alternatively you can re-append the script nodes to the page instead of evaling it:
// ...
for (var i =0; i<scripts.length; i++) {
var s = document.createElement('script');
s.innerHTML = eval(scripts[i].innerHTML);
document.body.appendChild(s);
}
but this is exactly the same as evaling the code anyway (no really, think hard about it both methods execute the code unchecked).
A better way is to avoid script injection altogether by adding the Syntaxhighlighter files at the top of the page and calling SyntaxHighlighter.highlight() after you've innerHTMLed the code.

populating two dropdown list using ajax

I have two dropdowns and I want the second dropdown to get populated on the basis of the data selected from the 1st dropdown
Here is my main.php:
<?php
include('connection.php');
$query_religion="SELECT DISTINCT religion FROM religion_caste_table";
$result_religion = mysql_query($query_religion, $con);
?>
<html>
<body>
<select name="religion" id="religion" style="width: 100px" onChange="showcaste(this.value)">
<?php
while($q_rel_data = mysql_fetch_array($result_religion))
{?>
<option value="<?php echo $q_rel_data[0]; ?>">
<?php echo $q_rel_data[0]; ?>
</option>
<?php }?>
</select>
<div id="view"></div>
<select name="caste" id="caste" style="width: 100px"></select>
</body>
</html>
And this is getcaste.php:
<?php
include('connection.php');
$string=$_GET["religion"];
$sql="SELECT caste FROM religion_caste_table WHERE religion = '".$string."'";
$result = mysql_query($sql,$con);
$myarray=array();
$str="";
while($result_caste=mysql_fetch_array($result))
{
$str=$str . "\"$result_caste[caste]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo $str;/*Stop hiding from IE Mac */
//echo $string;
mysql_close($con);
?>
<html>
</html>
now for the javascript ajax file,(religion_caste.js)
function showcaste(string)
{
if (string=="")
{
document.getElementById("caste").innerHTML="";
return;
}
alert(string);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("view").innerHTML=xmlhttp.responseText;
//now how to catch the string from (getcaste.php), split it and save it into array
// and to populate the second dropdwn by the array;
}
}
xmlhttp.open("GET","getcaste.php?religion="+string,true);
xmlhttp.send();
}
For more better assistance, the database table contains two fields, religion and caste, where the first attribute is religion, and caste being the second.
If somehow I can catch the string str, then it could have solved the matter.
document.getElementById("view").InnerHTML=xmlhttp.responseText provides the string "str1","str2",... to be viewed in <div id="view">
But if I write the following code:
var string=(document.getElementById("view").InnerHTML);
alert(string);
Then a msgbox pops up with such view:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
"Catholic","Protestant"
If I could just get the string, I would be happy.
So in your place a would do a little remake in getcaste.php first - place all results from your query into an array and then use implode to get a string using delimiter - ;. (Optionaly you could use a json and decode it in js). In religion_caste.js use split to get an array back from it (; as delimiter);
Now use for cycle to cycle through all values, and every cycle add one option into select
example:
var select = document.getElementById("caste");
for (var key in values)
{
var OptNew = document.createElement('option');
OptNew.text = values[key];
OptNew.value = key;
try
{
select.add(OptNew, null); // doesn't work in IE
}
catch(ex)
{
select.add(OptNew); // IE only
}
}
Edit:
so json in php is easy - json_encode
json in js is a little bit more difficult. New browsers should support JSON.parse, for old ones you have to use this code(Not 100% sure here since I always use jQuery). Alternatively you could use jQuery and jQuery.parseJSON

Categories