I have a canvas which I need to save to a directory and store the URL in a database.
When I save the file without storing the URL in the database it works fine, and vice versa.
However, when I put the two together and specify the PHP file through AJAX, for some reason it doesn't recognise the session variable?
When I try to call the "success" on AJAX, nothing shows up. I get no response.
This could possibly be an easy fix! I think I've been staring at this code for too long.
JavaScript:
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'doodleupload.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
PHP:
<?php
session_start();
/* AUTOMATED VARIABLES */
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$upload_dir = "images/external/doodles/";
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';
require_once 'php/connect.php';
try
{
$stmt = $pdo->prepare("INSERT INTO posts (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUE (:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "File in database";
}
else
{
echo "Not in database";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
Move $upload_dir at the top, as you are calling it before you initialize it.
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
Related
Right now I am creating a system like after edit the map using custom editor I need to print a map in 4 different large sizes but after customization when I am going to print in large size pixel is not good or printable and I am done with Editor now I need to help to create the image of large size to print. it must be a 300 dpi/ppi.
<?php
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
include '../../../wp-load.php';
$wp_content_path = wp_upload_dir();
// echo json_encode($wp_content_path['baseurl']);
$upload_dir = $wp_content_path['basedir']."/map-image-upload/";
$web_path = $wp_content_path['baseurl']."/map-image-upload/";
// echo $web_path;
// echo json_encode($upload_dir);
$w = $_POST['w'];
// echo json_encode($w);
$h = $_POST['h'];
// echo json_encode($h);
$img_data = $_POST['img_data'];
// echo json_encode($img_data);
$img_data = str_replace('data:image/png;base64,', '', $img_data);
// echo json_encode($img_data);
$img_data = str_replace(' ', '+', $img_data);
// echo json_encode($img_data);
$data = base64_decode($img_data);
// echo json_encode($data);
$timestamp = date("Y-m-d_H:i:s");
// echo json_encode($timestamp);
$file = $upload_dir .$timestamp . ".png";
$large_img_path = $web_path.'large_'.$timestamp . ".png";
// here i set large img path in session
$_SESSION['large_img_path'] = $large_img_path;
$_SESSION['large_img_name'] = 'large_'.$timestamp . ".png";
// echo $large_img_path;
$myfile = fopen($file, "w") ;
$ch = fwrite($myfile, $data);
echo json_encode($ch);
fclose($myfile);
// i use imagick extension here
header('Content-type: image/png');
$image = new Imagick($file);
$image->adaptiveResizeImage($w,$h);
$image->writeImage($upload_dir.'large_'.$timestamp . ".png");
$image->clear();
$image->destroy();
?>
I am using this code to generate the image
I got the idea that it can be print by leaflet easyprint but now need to print it with originalState in bigger size. please let me know how is it posible.
I have a button called rename that when pushed, executes in jQuery a rename.php file. Inside that php file the program selects data from a mysql, creates an array with that data, and processes an array in to json_encode($array);. How can I then get that json encoded array and echo it out into javascript?
I'm trying to echo the array out so that javascript displays my images src's.
This is my second line of ajax so I just wrote the javascript out as if it were php because I'm not sure of the commands or structure in js.
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
/*alert(result);*/
document.getElementById("images_to_rename").innerHTML = foreach(jArray as array_values)
{
"<img src=\""array_values['original_path']"/"array_values['media']"/>";
}
}
}
);
and my jQuery php file:
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if(empty($_GET['image_name']))
{
echo '<div class="refto" id="refto">image_name is empty</div>';
}
else
{
echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach($_GET['image_name'] as $rowid_rename)
{
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE ".$username." SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arri[] = $row;
}
foreach($arri as $rows) //put them into workable variables
{
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
?>
<script type="text/javascript">
var jArray= <?php echo json_encode($arri); ?>;
</script>
<?php
}
echo "something2";
?>
My PHP file is a jQuery url:"test4.php", type: "GET", and is not the main file. The main file is called main.php and the test4.php is something that's called in jQuery when the user clicks on rename.
Somebody suggested console log so here's what chrome says:
<div class="refto" id="refto">image_name is not empty</div>[{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}] <script type="text/javascript">
var jArray= [{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}];
</script>
something2
Your ajax php file isn't render in browser, then the variable jArray is undefined. With your case, let return php file to json and you can get it as variable in result.
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if (empty($_GET['image_name'])) {
//echo '<div class="refto" id="refto">image_name is empty</div>';
} else {
//echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach ($_GET['image_name'] as $rowid_rename) {
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE " . $username . " SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$arri[] = $row;
}
foreach ($arri as $rows) { //put them into workable variables
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
//stop render here
die();
}
?>
php file need return only json string. Then we'll get result as json variable in javascript.
And Js:
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
var jArray = JSON.parse(result);
/*alert(result);*/
var txt = "";
jArray.forEach(function(array_values){
txt += `<img src=\""array_values.original_path."/"array_values.media"/>`;
})
document.getElementById("images_to_rename").innerHTML = txt;
}
}
);
I am in need to send an ajax call to a function in following directory structure
Yii::$app->request->absoluteUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile";
my view function
function uploadImage(){
var url = '<?php echo Yii::app()->request->baseUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile"; ?>';
console.log(url);
return false;
$.ajax({
url:'<?php echo Yii::$app->createUrl("Post/UploadMusicFile"); ?>',
method:'post',
data:{file:$('input[type="file"]')},
dataType:'',
contentType:false,
processData:false,
success:function(data){
var parsed_data = $.parseJSON(data);
},
error:function(data){
console.log("Error "+data);
}
});
}
function which i am posting to
public function UploadMusicFile(){
$file = Yii::$app->request->post('file');
echo "<pre>";
print_r($file);
echo "</pre>";
exit();
$target_dir = "/home/jmwglobaladmin/public_html/melmory/uploads/music_memory/";
$target_file = $target_dir . basename($_FILES["files"]["name"][0]);
foreach ($_FILES["files"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["files"]["tmp_name"][$key];
move_uploaded_file($tmp_name, $target_file);
$connection = Yii::$app->getDb();
$command = $connection->createCommand('select id from post order by id desc limit 1');
$result = $command->queryAll();
$new_id = $result[0]['id']+1;
$file_name = "abc.mp3";
$connection = Yii::$app->getDb();
$command_insert = $connection->createCommand('insert into memory_music (post_id,memory_music) values ("'.$new_id.'","'.$file_name.'")');
$result = $command_insert->execute();
}
}
}
I get the error of 404. How to pass proper url in yii to a function which is present in directory structure like mentioned above?
Basics. Your function is not an action.
Change this:
public function UploadMusicFile()
To this:
public function actionUploadMusicFile()
Hi I try to load a JSON data from a php link in a js file whith this
$.getJSON('link to rempl.php', function(data) {
cn =data.nom;
});
this is the code of rempl.php
<?php
header('Content-Type: text/plain; charset=utf-8');
require_once ('connectDB.php');
if ($_POST['nom']== 0){
header("Location: http://localhost/geopp/editer.php");
}else{
$id = $_POST['nom'];
}
$sql = "SELECT id , id_archi , nom , archithect , adresse , date_construction , dateconst , resume FROM patri where id=".$id.";";
$req = mysqli_query ($link,$sql);
$feature = array();
//echo "lon\tlat\ttitle\tdescription\ticon";
while ($row = mysqli_fetch_assoc($req)) {
$res['id_archi'] = $row['id_archi'];
$res['id'] = $row['id'];
$res['date'] = $row['dateconst'];
$res['nom'] = $row['nom'];
$res['archithect'] = $row['archithect'];
$res['adresse'] = $row['adresse'];
$res['date_construction'] = $row['date_construction'];
$res['resume'] = $row['resume'];
$feature[] = json_encode($res);
}
echo implode(', ',$feature);
header("Location: http://localhost/geopp/empl.php");
?>
but when I alert the variable cn it show me undefined and thanks for helping me.
I am trying to create a PHP file that the browser will see as a js file, and are using the content-type header. But there's something not working, even though. So my question is, should this be interpreted as a valid .js file?:
<?php
header('Content-Type: application/javascript');
$mysql_host = "localhost";
$mysql_database = "lalalala";
$mysql_user = "lalalalal";
$mysql_password = "lalalallaala";
if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
die("Can't connect to database");
if (!mysql_select_db($mysql_database))
die("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
jQuery(document).ready(function() {
var urlsFinal = [
<?php
$result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
while($nt = mysql_fetch_array($result)) {
?>
"<?php echo $nt['url']; ?>",
<?php
};
?>
"oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
];
scriptLoaded();
});
In order for your Browser to see your PHP file like a .js file, echo or print the entire PHP page into a string, there will be no need to use any headers, just something like:
// First let's make a secure page called database.php - put in a restricted folder
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
while($nt = $db->fetch_object()){
$output[] = $nt->url;
}
}
else{
die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
var urlsFinal = ['$out'];
// more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>
Now just make sure your script tag looks like:
<script type='text/javascript' src='page.php'></script>