How doo I resolve getting a 500 error when calling $.post - javascript

My website has a drawing tool. This drawing tool help met create an image (.png) from the drawing. Has been working for years now, but recently changed the wordpress theme.
Now I can't figure out what's going wrong.
I have the following code which is doing a POST request to a file in my theme folder
var templateUrl = 'https://example.nl/wp-content/themes/generatepress';
var strDataURI = canvas.toDataURL("image/jpg",'',1.0);
var jsnDataJSON = encodeURIComponent(JSON.stringify(canvas));
$('input[name=json]').val(jsnDataJSON);
strDataURI = strDataURI.substr(22, strDataURI.length);
var ajax_urll= templateUrl+"/ajax.php";
$.post(ajax_urll,
{
str: strDataURI
},
function(data){
var obj=jQuery.parseJSON(data);
if(obj.status!="ERROR"){
jQuery("#drawing").html(obj.image);
jQuery("#drawingsaveresult").html("Drawing has been successfully saved");
jQuery("#drawingsaveresult").fadeOut(10000);
jQuery("input[name='drawing']").val(obj.imagename);
}else{
jQuery("#drawingsaveresult").html("Else error in saving drawing");
jQuery("#drawingsaveresult").fadeOut(10000);
}
});
So this code is calling ajax.php file (file in theme folder) which does the following
<?php
session_start();
// require_once( $_SERVER['DOCUMENT_ROOT'] . '/example.nl/wp-load.php' ); localhost
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
global $wpdb;
$data = base64_decode($_POST["str"]);
$urlUploadImages = "oefeningen/";
$nameImage = rand()."drawing.png";
$img = imagecreatefromstring($data);
imageAlphaBlending($img, true);
imageSaveAlpha($img, true);
$response=array();
if($img) {
imagepng($img, $urlUploadImages.$nameImage, 0);
imagedestroy($img);
get_stylesheet_directory_uri();
$response['image']="<img src='".get_stylesheet_directory_uri()."/oefeningen/".$nameImage."' width=100 height=150>";
$response['imagename']=$nameImage;
$response['status']="success";
}
else {
$response['status']="ERROR";
}
echo json_encode($response);
But for some reason it's not working anymore. In the console it's giving the following error back
POST https://example.nl/wp-content/themes/generatepress/ajax.php 500
I can't find a resolution. Can someone assist me with this?

Related

Uploading capture image and store it in a folder changing it's filename to be unique using the userID

I have this code from this reference https://github.com/jhuckaby/webcamjs/blob/master/DOCS.md?fbclid=IwAR0Q3W5mw8qWlJEdiabmyZJiw7wGJ5YDPRl2Ej0IKF3GCt_78HXeqAEjI6Y
it will display the webcam and take snapshots and make it to an image element using the data_uri but the problem is I want to get that file and store it with a declared filename into a folder here's the script I use
<script src="webcam.js"></script> <!--source code script from github for webcam config-->
<div id="my_camera" style="width:320px; height:240px;"></div>
<div id="my_result"></div>
<script type=text/javascript>
Webcam.attach( '#my_camera' );
function take_snapshot() {
Webcam.snap( function(data_uri) {
document.getElementById('my_result').innerHTML = '<img src="'+data_uri+'"/>';
} );
}
</script>
Take Snapshot
I have a button called register that functions like get all information being input and store it into the database like username first name etc together with the image taken by snapshot, here's my upload script in uploading images from a folder and I want to use it as getting the image data_uri and store it in a folder when I click the register button
<?php
session_start();
include_once'database.php';
$uid = $_SESSION['u_id'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
//check if ang uploaded file allowed i upload//
if (in_array($fileActualExt, $allowed)){
if ($fileError == 0){
if ($fileSize < 1000000){
$fileNameNew = "profile".$uid.".".$fileActualExt;
$fileDestination = 'uploads/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE profileimg SET status=0 WHERE userID ='$uid';";
$result = mysqli_query($conn, $sql);
header("location:../pages/userpage.php");
}
else {
echo "Your file is too big";
}
} else {
echo "There was an error uploading you file!";
}
} else {
echo "You cannot upload files of this type";
}
}
I'm going to use this function as stated in the documentation
Webcam.upload( data_uri, 'myscript.php', function(code, text) {
// Upload complete!
// 'code' will be the HTTP response code from the server, e.g. 200
// 'text' will be the raw response content
} );
} );
and have this in my php script
move_uploaded_file($_FILES['webcam']['tmp_name'], 'webcam.jpg');
any idea how should I turn this script into the one I use above in my upload.php? thanks in advance
You need to create image first by image src and then need to save that in a specific folder. You can follow below code:
file_put_contents("fileNameWithLocation.png",file_get_contents($imageSrc));
Here fileNameWithLocation.png will be $fileNameNew = "profile".$uid.".".$fileActualExt; $fileDestination = 'uploads/'.$fileNameNew; You need to make modification accordingly. And $imageSrc will be the image src which you can post via Ajax or form submission.
Hope it helps you.

trigger click automatically using jquery to export all graphs as image

I have multiple graphs in a single html page.I am trying to export all the graphs after the complete loading of all the graphs on that page.
I have the script to trigger the click event, but it's not working as I want it.
I want to trigger click button so that it pushes the graph image in an array as base64 encoded then send the data to a php file and save it as an image.
Two images are being created but only one image is proper and the other image is corrupt.
here is my code to graph generation:
https://jsfiddle.net/a1so23dh/2/
here is my php file code:
<?php
$data = urldecode($_POST['imageData']);
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$filename = "images/image".rand(1000,10000).".jpg";
file_put_contents($filename, $data);
?>
Any other approach may also work.
A better approach would be to just use the API methods in AmCharts' events and the AmCharts export plugin API instead of using fake clicks, similar to the first example in this tutorial. It uses the rendered event, but animationFinished works as well:
"listeners": [{
"event": "animationFinished",
"method": function(e) {
//wait for fabric
var interval = setInterval(function() {
if (window.fabric) {
clearTimeout(interval);
e.chart.export.capture({}, function() {
this.toJPG({}, function(data) {
//post base64 string in data to your endpoint directly
});
});
}
});
}
]
Updated fiddle - note that for debugging purposes I added the exported image to the bottom of the screen to validate that this works.
Your sendAllData() is not called. so I propose some changes, well it's not a full solution but help you.
$('*').click(function(e){
sendAllData();
});
function sendAllData(){
console.log(dataArray);
var arsize = dataArray.length;
console.log("here");
//execute this function and use the dataArray here
//send data to php file
if(arsize != 0){
for(i=0;i<=dataArray.length;i++){
jQuery.post( "a.php", {imageData: encodeURIComponent( dataArray[i] )})
.done(function( data ) {
if(data != 1){
console.log( "Data Loaded: " + data );
}else{
console.log("error");
}
});
}
}
}
In PHP use below code.
<?php
$data = urldecode($_POST['imageData']);
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
//$filename = "images/image".rand(1000,10000).".jpg";
//file_put_contents($filename, $data);
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/jpeg');
imagejpeg($im, "uploads/png3.jpeg");
imagedestroy($im);
}else{
echo '1';
}
?>
I am able to save the image of first graph i.e bar chart but in the pie chart, I am getting the error.please try this.

Summernote image upload not working in codeigniter

I have integrated summernote in my website (built with Codeigniter) and for texts it is working fine. But for image upload, there arises the following problem.
Summernote reads the image as base64. Now this works perfectly fine for small images, but once images are large, the image finally does not render due to the huge string created by the base64 in the database.
So I am trying to save the image in my server and then use the link of that image.
Following are the codes:
Script for summernote:
<script type="text/javascript">
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
onImageUpload: function(files) {
sendFile(files[0]);
}
});
function sendFile(file) {
data = new FormData();
data.append("files", file);
upload_url = "<?php echo base_url(); ?>" + "general/upload_image";
$.ajax({
data: data,
type: "POST",
url: upload_url,
cache: false,
contentType: false,
processData: false,
success: function(url) {
$(this).summernote("insertImage", url);
}
});
}
});
the php upload_image function:
public function upload_image()
{
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = 'http://sitename.com/dist/img/blogimg/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'http://sitename.com/dist/img/blogimg/' . $filename;//change this URL
}
else
{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
}
now, when I click on insert image in summernote or drag and drop an image multiple instances of the following error is shown in the console:
>Uncaught TypeError: Cannot read property 'nodeType' of undefined
This is what I want to achieve,
N.B. This editor is for a blog.
1. User clicks on insert image and uploads an image from his computer.
2. the image is shown in the editor (but not uploaded to server at this step).
3. When user clicks on submit button, then the image should be saved as an image file in a predefined folder.
4. When the page renders the it should have
<img src="mysite.com/path_to_image">
now it is something like
<img src="data:image/jpeg;base64,/9j/4AAQSkZJR....">)
Please note, I tried using onImageUpload within callbacks but the result was nothing was actually happening, neither the image was geting uploaded to the editor nor to the folder in the server.
Where am I going wrong....?? Please help me fix this...
if your summernote version after 0.7
following this
$('#summernote').summernote({
height: 400,
callbacks: {
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0]);
}
}});
Okay, although I could not find a solution to my problem, I have implemented an alternation solution and it works perfectly, although pt. 3 is not catered to and the image is uploaded to the server in an earlier step. That too can be catered with some js scripts...Will do that later... What I did is I targeted the summernote ids and classes and added my codes in place of theirs...
I removed their upload image field by this code:
<style>
/*to disable the upload image from computer uncomment this css code.*/
.note-group-select-from-files {
display: none;
}
</style>
Next I inserted my HTML below their insert link field this way:
document.getElementsByClassName('note-group-image-url')[0].insertAdjacentHTML('afterend','<p class="sober"><p>Click here to upoad image</p></i></p>');
Next I handled the image upload through a modal and wrote a custom js script that copied the image url to the field of .note-image-url
Also I had to customise the javascript of the insert image button of summernote with js so that users can directly click on insert image.
You can add this to your store/ update controller.
It will detect images in your editor, convert and save it in your server.
$body = $data['content'];
$doc = new DomDocument;
libxml_use_internal_errors(true);
$doc->loadHTML($body);
$images = $doc->getelementsbytagname('img');
define('UPLOAD_DIR', 'assets/images/announcement_img/');
foreach($images as $k => $img){
$datas = $img->getattribute('src');
if (strpos($datas, 'data:image')!==false){
list($type, $datas) = explode(';', $datas);
list($media, $format) = explode('/', $type);
list(, $datas) = explode(',', $datas);
$datas = str_replace(' ', '+', $datas);
$datas = base64_decode($datas);
$file= UPLOAD_DIR . time().$k.'.'.$format;
$success = file_put_contents($file, $datas);
print $success ? $file : '<br><br>Unable to save the file.<br><br>';
$img->removeattribute('src');
$img->setattribute('src',base_url().$file);
}
}
$body = $doc->savehtml();
$data['content']=$body;

Saving a file on server using JavaScript

Js code
var server = '';
var orig_chat = chatUpdateSucess;
chatUpdateSucess = function(o){
if (o.GlobalChats && o.GlobalChats.length > 0) {
//TODO: Add setting to enable/diosable this
console.log(JSON.stringify(o.GlobalChats));
var xhr = new XMLHttpRequest();
xhr.open("POST", server+"/api.php?request=log_gc");
xhr.send(JSON.stringify(o.GlobalChats));
}
orig_chat.apply(this, arguments);
};
Server code named api.php
<?php
header("Access-Control-Allow-Origin: *");
if(!empty($_POST['o.GlobalChats'])){
$data = $_POST['o.GlobalChats'];
$fname = time() . ".txt";//generates random name
$file = fopen("" .$fname, 'w');//creates new file
fwrite($file, $fclose($file);
}
?>
console.log output
[{"PlayerId":237186,"toPlayerId":0,"chatid":16606292,"added":"/Date(1451764948837)/","addedText":"20:02","PlayerLink":"p=Kodabear|237186|T?|78|1|0|0-144-0-240-186-0-0-0-0-0-0-0-0|#IKnowAFighter|Neurofibromatosis Awareness day/Month|5-404-282-59","text":"Exmaple of a real chat"}]
I created a js that sends a file to my server every time the chat in the game is updated. But I am having problems with the server side code any advice would be great help. (PHP code was founded here
Saving a text file on server using JavaScript
Try to var_dump($_POST['o.GlobalChats']) to see if your data is reaching the server.
It seems like you are not writing the file to the system properly. Please read the examples at the manual (http://php.net/manual/pt_BR/function.fwrite.php)
Also, using time() is not safe, because two files may be created at the same UNIX timestamps in extreme cases, and one will overwrite the other
Try something like this:
$data = $_POST['o.GlobalChats'];
$fname = time() . "-" . rand ( 1 , 10000 ) . ".txt";
$handle = fopen($fname, 'w');
fwrite($handle, $data);
fclose($handle);

Need Help Handling a XML HTTP File Upload Request

So, I looked up a tutorial for uploading and sending files to a server with an XML HTTP Request. I followed the tutorial, however, I think I must be missing something. While the file appears to be uploaded and sent, nothing in the "handler" file is ever accessed. Is there a PHP function I need to write to process it? For context, here is what I wrote:
$(document).ready(function()
{
$('#upload-button').click(function(event)
{
$('#upload-button').removeClass("btn-danger");
});
$( "#report-form" ).submit(function( event )
{
var form = document.getElementById('report-form');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
event.preventDefault(); // Stop the event from sending the way it usually does.
uploadButton.value = 'Submitting...'; // Change text.
var files = fileSelect.files;
var maxfiles = <?php echo $config['Report_MaxFiles'] ?>;
var mfs = <?php echo $config['Report_MaxFileSize'] ?>;
if(files.length > maxfiles) // Make sure it's not uploading too many.
{
uploadButton.value = 'You uploaded too many files. The limit is ' + maxfiles + '.'; // Update button text.
$('#upload-button').addClass('btn-danger'); // Make the button red, if so.
return;
}
var formData = new FormData(); // Make a "form data" variable.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Add the file to the request.
if(file.size / 1000 > mfs)
{
uploadButton.value = 'One of the files is too big. The file size limit is ' + (mfs) + 'kb (' + (mfs / 1000) + 'mb).';
$('#upload-button').addClass('btn-danger');
return;
}
formData.append('files[]', file, file.name); // Not really sure what this does, to be honest,
// but I think it makes a file array.
}
var xhr = new XMLHttpRequest(); // Construct an XML HTTP Request
xhr.open('POST', 'assets/class/FileHandler.php', true); // Open a connection with my handler PHP file.
xhr.onload = function ()
{
if (xhr.status === 200)
{
uploadButton.value = 'Files Submitted!'; // NOTE: I do get this message.
}
else
{
uploadButton.value = 'An error occurred.';
$('#upload-button').addClass("btn-danger");
}
};
xhr.send(formData); // I think this is where it dies.
});
});
At the "send(formData)" line, I'm not actually sure if it's sending. Do I set up some sort of listener in FileHandler.php that is activated when the files are sent via XML HTTP request? Or more specifically, how to I save the uploaded files to the server using my FileHandler.php file?
EDIT: I haven't been able to come up with any other PHP code in the FileHandler.php file than this, which I thought might be called when the form is sent (but it isn't):
EDIT 2: Okay, now I have something, but it isn't working (didn't expect it to). I think I may be using the variables wrong:
<?php
$uploaddir = 'data/reports/uploads/' . $_POST['id'] . "/";
$uploadfile = $uploaddir . basename($_FILES['files']['name']);
echo "<script>console.log('RECEIVED');</script>";
echo '<pre>';
if (move_uploaded_file($_FILES['files']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
It's not saving the file to the directory, nor is it printing the script message. How do I get my report.php file to execute these things in FileHandler.php?
Thanks to the help and patience of #Florian Lefèvre, I got it fixed. :)
The problem was with the path. It wasn't locating the path to the folder data/uploads/ and wasn't making the directory. Here is what I did:
$uploaddir = '../../data/reports/uploads/' . $_POST['id'] . "/";
echo "NAME: " . $_FILES['files']['name'][0] . "\n";
foreach($_FILES['files']['name'] as $filenumber => $filename)
{
$uploadfile = $uploaddir . basename ($filename);
echo "UploadDir " . $uploaddir . "\n";
echo "UploadFile " . $uploadfile . "\n";
echo '<pre>';
echo "MKDir for UploadDir which is: ". $uploaddir . "\n";
mkdir ($uploaddir);
if (move_uploaded_file ($_FILES['files']['tmp_name'][$filenumber], $uploadfile))
{
echo "File is valid, and was successfully uploaded.\n";
}
else
{
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print "</pre>";
}
var_dump ($_FILES);
I haven't gotten rid of some of the debug stuff yet, but that's the general solution.

Categories