Here's my PHP code:
$cipher = 'aes-256-cbc';
// 128-bit key
$key = md5('super secret', true);
// 128-bit IV
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($message, $cipher, $key, OPENSSL_RAW_DATA, $iv);
error_log(__FILE__ . __LINE__ . ' key: ' . bin2hex($key));
error_log(__FILE__ . __LINE__ . ' iv: ' . bin2hex($iv));
error_log(__FILE__ . __LINE__ . ' ciphertext: ' . bin2hex($ciphertext));
file_put_contents($courseOutlineFile, bin2hex($iv) . bin2hex($ciphertext));
And my Javascript code, where res is the text from the ajax response to read the file generated by PHP:
var k = CryptoJS.MD5('super secret');
var iv = CryptoJS.enc.Hex.parse(res.substring(0, 32));
var data = CryptoJS.enc.Hex.parse(res.substring(32));
console.log("key: ", CryptoJS.enc.Hex.stringify(k))
console.log("iv: ", CryptoJS.enc.Hex.stringify(iv))
console.log("ciphertext: ", CryptoJS.enc.Hex.stringify(data))
var cipher = CryptoJS.lib.CipherParams.create({
ciphertext: data
});
var dec = CryptoJS.AES.decrypt(cipher, k, {
iv: iv,
mode: CryptoJS.mode.CBC
});
console.log("decrypted:", dec.toString(CryptoJS.enc.Hex));
var json = dec.toString(CryptoJS.enc.Utf8);
console.log("json:", json)
I've verified with a compare tool that the hex values of the key, IV, and data are the same in PHP and what gets printed to the browser's console. It does successfully decrypt (something), but that last console.log statement generates an error: Error: "Malformed UTF-8 data". If I try Latin1 it results in a bunch of non-printable characters.
The $message variable that I'm encrypting is the output from json_encode on an array.
Does anyone know what I'm missing?
These are the first 80 hex digits of the decrypted result, the entire thing is a little under 28k hex digits.
20a290156abf2855f2c3344a2d9cf7dc84c5c02b1a48a03f18aa8a5054f650dd5517b25b6582c72d
Here's a complete example:
<?php
ini_set('display_errors', 1);
$jsonObj = [
'el1' => 'val1',
'ar1' => [
'el2' => 'val2',
'el3' => 'val3',
],
];
$message = json_encode($jsonObj);
echo $message . '<br>';
$cipher = 'aes-256-cbc';
// 128-bit key
$key = md5('super secret', true);
// 128-bit IV
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($message, $cipher, $key, OPENSSL_RAW_DATA, $iv);
echo ' key: ' . bin2hex($key) . '<br>';
echo ' iv: ' . bin2hex($iv) . '<br>';
echo ' ciphertext: ' . bin2hex($ciphertext) . '<br>';
echo bin2hex($iv) . bin2hex($ciphertext);
The output:
{"el1":"val1","ar1":{"el2":"val2","el3":"val3"}}
key: 5f1903f5f2cb32acb4c1dcae9e30d374
iv: bfdb765d1ca4734c5748ffb9883dd15c
ciphertext:
02717027440040375f7e0dbea69e77783949d3c160529eef0b9d59a751a2a312fa137a5034f6f4c9f89a348ef3f96fce40c8afe0c8a20a2f7a2535417cca2dd2
bfdb765d1ca4734c5748ffb9883dd15c02717027440040375f7e0dbea69e77783949d3c160529eef0b9d59a751a2a312fa137a5034f6f4c9f89a348ef3f96fce40c8afe0c8a20a2f7a2535417cca2dd2
And the Javascript:
res = 'bfdb765d1ca4734c5748ffb9883dd15c02717027440040375f7e0dbea69e77783949d3c160529eef0b9d59a751a2a312fa137a5034f6f4c9f89a348ef3f96fce40c8afe0c8a20a2f7a2535417cca2dd2';
var k = CryptoJS.MD5('super secret');
var iv = CryptoJS.enc.Hex.parse(res.substring(0, 32));
var data = CryptoJS.enc.Hex.parse(res.substring(32));
console.log("key: ", CryptoJS.enc.Hex.stringify(k))
console.log("iv: ", CryptoJS.enc.Hex.stringify(iv))
console.log("ciphertext: ", CryptoJS.enc.Hex.stringify(data))
var cipher = CryptoJS.lib.CipherParams.create({
ciphertext: data
});
var dec = CryptoJS.AES.decrypt(cipher, k, {
iv: iv,
mode: CryptoJS.mode.CBC
});
console.log("dec:", dec.toString());
console.log("decrypted:", dec.toString(CryptoJS.enc.Hex));
var json = dec.toString(CryptoJS.enc.Utf8);
console.log("json:", json)
// parse the JSON string to get the object
var obj = JSON.parse(json);
And the console output:
key: 5f1903f5f2cb32acb4c1dcae9e30d374
iv: bfdb765d1ca4734c5748ffb9883dd15c
ciphertext: 02717027440040375f7e0dbea69e77783949d3c160529eef0b9d59a751a2a312fa137a5034f6f4c9f89a348ef3f96fce40c8afe0c8a20a2f7a2535417cca2dd2
dec: 50d411522f2d08b34d68f847fb78e0cfabf1144f933d83839431732a473079d9b3ed843e120d9ad6a239
decrypted: 50d411522f2d08b34d68f847fb78e0cfabf1144f933d83839431732a473079d9b3ed843e120d9ad6a239
Error during decryption: Error: "Malformed UTF-8 data"
Related
var CryptoJS = require("crypto-js");
const a = {
name: "Burak",
surName: "Bayraktaroglu"
};
const aString = JSON.stringify(a);
// Encrypt
var ciphertext = CryptoJS.AES.encrypt(
aString,
"XRWT2lTKcr13PbTRaWndA6H8AT6JuBwBVkrCpSGJ6cE6JnEhDHHV6Xz26gULg5rM"
).toString();
console.log(ciphertext);
// Decrypt
var bytes = CryptoJS.AES.decrypt(
ciphertext,
"XRWT2lTKcr13PbTRaWndA6H8AT6JuBwBVkrCpSGJ6cE6JnEhDHHV6Xz26gULg5rM"
);
var originalText = bytes.toString(CryptoJS.enc.Utf8);
const jsonObject = JSON.parse(originalText);
console.log(jsonObject);
i want to decrypt ciphertext in php
<?php
$plaintext = '{"phoneNumber":"+628888888888","phoneNumberValid":"+628888888888","phoneNumberMiniSurvey":"","calculateLoan":"","specialRateResult":"","dob":"","checkBox1":"Y","checkBox2":"N","submittedForm":"N","isLogin":"N","email":"","nameTmp":"Dzarr al ghifari","gender":"","isRegistered":"N","name":"Dzarr al ghifari"}';
$password = 'XRWT2lTKcr13PbTRaWndA6H8AT6JuBwBVkrCpSGJ6cE6JnEhDHHV6Xz26gULg5rM';
$method = 'aes-256-cbc';
// Must be exact 32 chars (256 bit)
$password = substr(hash('sha256', $password, true), 0, 32);
echo "Password:" . $password . "\n";
// IV must be exact 16 chars (128 bit)
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
// av3DYGLkwBsErphcyYp+imUW4QKs19hUnFyyYcXwURU=
$encrypted = base64_encode(openssl_encrypt($plaintext, $method, $password, OPENSSL_RAW_DATA, $iv));
$$encrypted = base64_encode("U2FsdGVkX1/ABCbXVG5iVcjZ+qVwLcXJ0Mbxfr8EEU+2JNVji7yiYQQGEjeWB4MgFWE89BTPXDdyBvjGCpfQ+BH5evxyS/Fj1OeijQr0RmhWliiazgX90gOLEBOBAw9FzyJn8m3CzjrJksx27q/a7izq4mAVRAitj4/1m0+uI8sBSqmC2HGxmol7MxQxODE/cYbmYYOrg+wFgg8J3+mYv2dDcHIIXknTyZsGx26CicZ//tWwGkdIhjDuWo5Rq5IqlFcqST9F3m5NicDSiy/hotQEFP9PrRveAtNnMnTuOWcSsNp63zfR2oPSy22Z7cz6+4fnu4eEjguyxeN38RRU5jbUFBQLxrth8tERI44O/fRMQiMheDUBUdCVIsh0vGHh7F17t/oBBTq5YrD8l+noMUE/M6kBa5Yr24NLw/PYDgPyO9jD5XMUhNXmFeLUe8SQ");
$iv = "a591cdd0d7bea71eae2eefe4c73f612f";
// My secret message 1234
$decrypted = openssl_decrypt(base64_decode($encrypted), $method, $password, OPENSSL_RAW_DATA, $iv);
echo 'plaintext=' . $plaintext . "\n";
echo 'cipher=' . $method . "\n";
echo 'encrypted to: ' . $encrypted . "\n";
echo 'decrypted to: ' . $decrypted . "\n\n";
result isn't match with plain text :
plaintext=
{"phoneNumber":"+628888888888","phoneNumberValid":"+628888888888","phoneNumberMiniSurvey":"","calculateLoan":"","specialRateResult":"","dob":"","checkBox1":"Y","checkBox2":"N","submittedForm":"N","isLogin":"N","email":"","nameTmp":"Dzarr al ghifari","gender":"","isRegistered":"N","name":"Dzarr al ghifari"}
decrypted to:
IY ~ZG+628888888888","phoneNumberValid":"+628888888888","phoneNumberMiniSurvey":"","calculateLoan":"","specialRateResult":"","dob":"","checkBox1":"Y","checkBox2":"N","submittedForm":"N","isLogin":"N","email":"","nameTmp":"Dzarr al ghifari","gender":"","isRegistered":"N","name":"Dzarr al ghifari"}
I have
$dataSavedBlocks = get_user_meta( $user_id, 'jsonBlock');
var_dump($dataSavedBlocks);
Which gives:
array(1) { [0]=> string(534) "{"date":"3/25/20","ricoverati_con_sintomi":999,"terapia_intensiva":251,"totale_ospedalizzati":1250,"isolamento_domiciliare":1526,"totale_attualmente_positivi":2776,"nuovi_attualmente_positivi":257,"dimessi_guariti":54,"deceduti":142,"totale_casi":2972,"tamponi":17868} | ,{"date":"3/25/20","ricoverati_con_sintomi":82,"terapia_intensiva":19,"totale_ospedalizzati":101,"isolamento_domiciliare":311,"totale_attualmente_positivi":412,"nuovi_attualmente_positivi":17,"dimessi_guariti":12,"deceduti":18,"totale_casi":442,"tamponi":3019} | " }
I tried:
$dataSavedBlocks = get_user_meta( $user_id, 'jsonBlock');
$dataCustom = implode("| ,", $dataSavedBlocks[0]);
$dataCustom = str_replace("| ,",",",$dataCustom);
$dataCustom = explode(",", $dataCustom);
var_dump($dataCustom);
I get:
Warning: implode(): Invalid arguments passed in ...
array(1) { [0]=> string(0) "" }
I need a correct json to parse it in js:
var customJsonData = JSON.parse('<?php echo $dataCustom; ?>');
But I have | , as a separator and I cannot exclude it for other reasons when I save it. What am I doing wrong?
All you need to do is to replace | with an empty string and to wrap the result in square brackets:
$jsonBlock = '{"date":"3/25/20","ricoverati_con_sintomi":999,"terapia_intensiva":251,"totale_ospedalizzati":1250,"isolamento_domiciliare":1526,"totale_attualmente_positivi":2776,"nuovi_attualmente_positivi":257,"dimessi_guariti":54,"deceduti":142,"totale_casi":2972,"tamponi":17868} | ,{"date":"3/25/20","ricoverati_con_sintomi":82,"terapia_intensiva":19,"totale_ospedalizzati":101,"isolamento_domiciliare":311,"totale_attualmente_positivi":412,"nuovi_attualmente_positivi":17,"dimessi_guariti":12,"deceduti":18,"totale_casi":442,"tamponi":3019} | ';
$json = '[' . str_replace(' | ', '', $jsonBlock) . ']';
var_dump($json);
The result would be:
string(530) "[{"date":"3/25/20","ricoverati_con_sintomi":999,"terapia_intensiva":251,"totale_ospedalizzati":1250,"isolamento_domiciliare":1526,"totale_attualmente_positivi":2776,"nuovi_attualmente_positivi":257,"dimessi_guariti":54,"deceduti":142,"totale_casi":2972,"tamponi":17868},{"date":"3/25/20","ricoverati_con_sintomi":82,"terapia_intensiva":19,"totale_ospedalizzati":101,"isolamento_domiciliare":311,"totale_attualmente_positivi":412,"nuovi_attualmente_positivi":17,"dimessi_guariti":12,"deceduti":18,"totale_casi":442,"tamponi":3019}]"
const json = JSON.parse('[{"date":"3/25/20","ricoverati_con_sintomi":999,"terapia_intensiva":251,"totale_ospedalizzati":1250,"isolamento_domiciliare":1526,"totale_attualmente_positivi":2776,"nuovi_attualmente_positivi":257,"dimessi_guariti":54,"deceduti":142,"totale_casi":2972,"tamponi":17868},{"date":"3/25/20","ricoverati_con_sintomi":82,"terapia_intensiva":19,"totale_ospedalizzati":101,"isolamento_domiciliare":311,"totale_attualmente_positivi":412,"nuovi_attualmente_positivi":17,"dimessi_guariti":12,"deceduti":18,"totale_casi":442,"tamponi":3019}]');
console.log(json);
JS can handle the string
const str = `{"date":"3/25/20","ricoverati_con_sintomi":999,"terapia_intensiva":251,"totale_ospedalizzati":1250,"isolamento_domiciliare":1526,"totale_attualmente_positivi":2776,"nuovi_attualmente_positivi":257,"dimessi_guariti":54,"deceduti":142,"totale_casi":2972,"tamponi":17868} | ,{"date":"3/25/20","ricoverati_con_sintomi":82,"terapia_intensiva":19,"totale_ospedalizzati":101,"isolamento_domiciliare":311,"totale_attualmente_positivi":412,"nuovi_attualmente_positivi":17,"dimessi_guariti":12,"deceduti":18,"totale_casi":442,"tamponi":3019} | " }`
.replace(/\|/g,"").replace(/ " }/,"")
console.log(JSON.parse("["+str+"]"))
This is what I had to do and worked
<?php
$user_id = get_current_user_id();
$dataSavedBlocks = get_user_meta( $user_id, 'jsonBlock');
$dataCustom = json_encode($dataSavedBlocks[0]);
$dataCustom = str_replace('|', '', $dataCustom);
$dataCustom = stripslashes($dataCustom);
?>
js
var myJson = '<?php echo $dataCustom; ?>';
var result = myJson.substring(1, myJson.length-1);
var customJsonData = JSON.parse("["+result+"]");
Whenever I am trying to update my chart through AJAX by clicking a button, I am getting following error:
TypeError: this.canvas is null
this.context = this.canvas.getContext('2d');
RGraph.bar.js (line 49, col 9)
I tried various solutions but nothing worked for me. Here's are my two files which are being used in this process:
index.php:
<?php
include("includes/db-config.php");
$query = "SELECT * FROM `tb_daily_statistics`";
$rs = mysqli_query($con, $query);
$labels = array();
$data = array();
while($row = mysqli_fetch_array($rs))
{
$labels[] = $row['day'];
$data[] = $row['statistics'];
}
// Now you can aggregate all the data into one string
$data_string = "[" . implode(", ", $data) . "]";
$labels_string = "['" . implode("', '", $labels) . "']";
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>RGraph Charts</title>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="js/RGraph/RGraph.common.core.js"></script>
<script type="text/javascript" src="js/RGraph/RGraph.bar.js"></script>
<!--[if lt IE 9]><script src="js/RGraph/excanvas.js"></script><![endif]-->
<script type="text/javascript">
$(document).ready(function (){
var bar = new RGraph.Bar({
id: 'mycanvas',
data: <?php echo $data_string; ?>,
options: {
labels: <?php echo $labels_string; ?>,
gutter: {
left: 50
}
}
}).draw()
$("#btnstats").click(function(){
var order_by = $(this).data("order");
//alert(order_by);
// Reset the canvas
RGraph.Reset(document.getElementById("mycanvas"));
// Prepare data to send over server
data = 'order_by='+order_by;
RGraph.AJAX.getJSON('ajax/update-chart.php?'+data, draw_graph);
})
});
// This is the AJAX callback function. It splits up the response, converts it to numbers and then creates the chart.
function draw_graph(json)
{
// Set the JSON on the window object so that the button below can show it to the user.
//window.__json__ = json;
//$p(window.__json__);
// Reset the canvas
RGraph.Reset(document.getElementById("mycanvas"));
// Now draw the chart
var bar = new RGraph.Bar({
id: 'mycanvas',
data: json.data,
options: {
labels: json.labels,
gutter: {
left: 50
}
}
}).draw()
}
</script>
</head>
<body>
<canvas id="mycanvas" width="600" height="250">[No canvas support]</canvas>
<br />
<input type="button" id="btnstats" value="Order By Stats" data-order="statistics" />
</body>
</html>
update-chart.php:
<?php
require_once '../includes/db-config.php';
/*
echo "<pre>";
print_r($_GET);
echo "<pre>";
*/
// Order by day
if(isset($_GET['order_by']) && $_GET['order_by'] == "statistics")
{
$order_by = $_GET['order_by'];
$query = "SELECT * FROM `tb_daily_statistics` ";
$query .= "ORDER BY " . $order_by;
$rs = mysqli_query($con, $query);
$labels = array();
$data = array();
while($row = mysqli_fetch_array($rs))
{
$labels[] = $row['day'];
$data[] = $row['statistics'];
}
// Now you can aggregate all the data into one string
$data_string = "[" . implode(", ", $data) . "]";
$labels_string = "['" . implode("', '", $labels) . "']";
echo json_encode(array('data' => $data_string, 'labels' => $labels_string));
}
?>
The response from server is fine. Here's what I am receiving:
{"data":"[64, 75, 84, 94, 95, 98, 124]","labels":"['Wed', 'Fri', 'Sun', 'Thu', 'Tue', 'Sat', 'Mon']"
}
What could be the issue?
The response from the server is not formatted in correct way that RGraph understands. It's
{"data":"[64, 75, 84, 94, 95, 98, 124]","labels":"['Wed', 'Fri', 'Sun', 'Thu', 'Tue', 'Sat', 'Mon']"
}
If you do
window.__json__ = json;
$p(window.__json__);
in your draw_graph(json) function, then response from server will be
Object {
data => [64, 75, 84, 94, 95, 98, 124] (string, 29)
labels => ['Wed', 'Fri', 'Sun', 'Thu', 'Tue', 'Sat', 'Mon'] (string, 49)
}
which is wrong. Rather it should be
Object {
data => Object {
0 => 64 (number)
1 => 75 (number)
2 => 84 (number)
3 => 94 (number)
4 => 95 (number)
5 => 98 (number)
6 => 124 (number)
}
labels => Object {
0 => Wed (string, 3)
1 => Fri (string, 3)
2 => Sun (string, 3)
3 => Thu (string, 3)
4 => Tue (string, 3)
5 => Sat (string, 3)
6 => Mon (string, 3)
}
}
To fix your issue, change few lines of code in update-chart.php as
From
$data[] = $row['statistics'];
to
$data[] = (int) $row['statistics'];
Remove following lines:
// Now you can aggregate all the data into one string
$data_string = "[" . implode(", ", $data) . "]";
$labels_string = "['" . implode("', '", $labels) . "']";
From
echo json_encode(array('data ' => $data_string , 'labels' => $labels_string));
to
echo json_encode(array('data' => $data, 'labels' => $labels));
I have an issue where I'm trying to export html table to a csv file. The issue is that no download box appears but I know my JS function is run via an alert check.
I wonder if it can be my table that is generated from an exiting csv file like this:
echo "<table>\n\n";
$f = fopen("../translations/EXAMPLE.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
foreach ($line as $cell) {
echo "<td contenteditable>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
echo "\n</table>";
I have a button to call the javascript:
<button class='saveCSV' style='float:right;'>Save</button>
And here is the javascript file:
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
alert("KØRT");
}
// This must be a hyperlink
$(".saveCSV").on('click', function (event) {
// CSV
exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
Anyone having an idea to what os wrong here and the csv file is not exported?
Simply convert the csvData to a blob file or base64 file and then send to the server using ajax. Take note of the two functions added after the document.ready.
$(document).ready(function () {
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
function uploadCSV( blob ) {
var reader = new FileReader();
reader.onload = function(event){
var fd = {};
fd["fname"] = "example.csv";
fd["data"] = event.target.result;
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
dataType: 'text'
}).done(function(data) {
console.log(data);
});
};
reader.readAsDataURL(blob);
}
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
var asblob = dataURItoBlob(csvData);
uploadCSV( asblob ); //prepare and send via ajax post. The ajax post is not tested though
}
// This must be a hyperlink
$(".saveCSV").on('click', function (event) {
// CSV
exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
PHP CODE should be
<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
$filename = $_POST['fname'];
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
OR
Blob blob = *// get Blob file *
byte [] bytes = blob.getBytes(1, (int) blob.length());
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Testing/";
File dir = new File(filePath);
File file = new File(dir, "filename.csv");
FileOutputStream fOut = new FileOutputStream(file);
//bmp.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
Have you tried removing the encodeURIComponent method? With some initial testing, I found this to break functionality. So your code may look something like this instead:
var csvData = 'data:application/csv;charset=utf-8,' + csv;
Here's an example of this in action.
Remember also, that what you're attempting to do won't work in every browser as the download attribute is not universally supported. See here for more about support.
Connection.php file which stored database connection code with json:
<?php
$username = "root";
$password = "";
$database = "roadmap";
$url = "localhost";
$con = mysql_connect($url, $username , $password);
if (!$con) {
die('Could not connect:' . mysql_error());
}
mysql_select_db($database, $con) ;
$data = array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM students");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['Id'] = $row['Id'];
$json['Lon'] = $row['Lon'];
$json['Lat'] = $row['Lat'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
mysql_close($con);
?>
In separate file index.php:
$.getJSON("connection.php", function(data) {
addMarker( data[0].Lon,data[0].Lat ,data[0].desc);
addMarker(-0.13264,51.50918 , );
addMarker( -0.12498,51.50807 , );
center = bounds.getCenterLonLat();
map.setCenter(center, map.getZoomForExtent(bounds) - 1);
zoom = map.getZoom();
});
this currently pulls the json data through and I have to use it for each individual assigning of a part from the database such as data[0].lon will get the longitude entry for the first record with in the database.
As I am going to be working with quite a few entry's. I want to loop through the json array and then out put all records as so:
addMarker( RECORD 1 );
addMarker( RECORD 2 );
addMarker( RECORD 3 );
Can anyone help me with this.
use something like this
$.each(data, function(i,row){
addMarker( row['Lon'],row['Lat'] ,row['desc'])
})
You can use a for loop:
$.getJSON("connection.php", function(data) {
for(var i = 0; i < data.length; ++i) {
addMarker(data[i].Lon, data[i].Lat, data[i].desc);
}
addMarker(-0.13264,51.50918 , );
addMarker( -0.12498,51.50807 , );
center = bounds.getCenterLonLat();
map.setCenter(center, map.getZoomForExtent(bounds) - 1);
zoom = map.getZoom();
});
Or like the other answers use the jQuery each function.
You can use $.each loop to iterate over your json .. Try this
Try this
function(data){
$.each(data, function(i){
console.log('Record ' + i + ' : Longitude - ' + data[i].Lon + ' . Latitude - ' + data[i].Lat + '. Description - ' + data[i].desc )
});
}
Check FIDDLE