Struggling to store the canvas data, the file ends up blank

I've been attempting to upload an image from a canvas to a server using ajax, but every time I end up with an empty image file that is only 879 bytes. I can't seem to figure out what I'm doing wrong. If someone could take a look, I would greatly appreciate it.

document.getElementById('input').addEventListener("change",function (e) {
  var file = e.target.files[0];
  var reader = new FileReader();
  var output = document.getElementById('test');
  reader.onload = function () {
    var data = this.result;
    var img = new Image();
    img.src = data;
    img.onload = function() {
var ctx = canvas.getContext("2d");
output.innerHTML = 'width: ' + img.width + '\n' + 'height: ' + img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);

    };
  };
  reader.readAsDataURL(file);
  var canvasData = canvas.toDataURL("image/png");

Below is the Ajax code

$.ajax({ type: "POST", url: "upload_images.php", data: { canvasData:canvasData }, success:function() { } });

$upload_dir = 'uploads/';  //you will need to implement this function yourself
$img = $_POST['canvasData'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir."image_name.png";
$success = file_put_contents($file, $data);
header('Location: '.$_POST['return_url']);

Answer №1

Success, everything is resolved... I took your suggestions and relocated the toDataUrl function within the unload event, as well as the ajax upload, and everything is working perfectly now. Thank you once again.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Harnessing the power of JavaScript functions to display an image when clicked

Looking for help with making an image appear when clicking on one of three images? Despite trying different approaches, the desired result is still not achieved. I'm aware of using if else statements but exploring other methods. Any insights on what m ...

unable to locate express router

Recently, I set up an express project using the express generator with the following commands: express project_name and npm install Here is a snippet from my app.js file: var express = require('express'); var path = require('path') ...

Establishing the highest allowable value limit in cleave

I've integrated cleave.js into my Vue.js project to create a date input field. Here's the option configuration I used: <cleave :options="{ date: true, datePattern: ['m', 'd','Y'] ...

Issue with Iconify icon not updating when "data-icon" is set using setAttribute()

I'm having trouble trying to animate or replace an icon using the "setAttribute" method. Can someone take a look at my code and help me figure out what's wrong? <!DOCTYPE html> <html> <script src="https://code.iconify.design/1/1 ...

Merge the variables extracted from an array of objects

I need to extract specific data from an array of objects and perform a calculation. For example, the provided data is as follows: const item = [{ "act": "Q", "line": 1, &quo ...

Implementing setTimeout with the copy button: A guide

How can I implement a setTimeout function in the copy button so that when a user clicks on it, the text will change to "copied" and then revert back to "copy" after 3-4 seconds? Please help me find a solution to this problem and also optimize the JavaScrip ...

Challenges with JavaScript fetching JSON information

Resolved: To enable AJAX functionality, I needed to upload the files to my server. Currently, I am attempting to retrieve stock information from a JSON file, but no data is being displayed. Upon alerting ajax.status, it returned 0 as the result, indicatin ...

Stop unauthorized access to php files when submitting a contact form

I have implemented a contact form on my HTML page that sends an email via a PHP script upon submission. However, when the form is submitted, the PHP script opens in a new page instead of staying on the current page where the form resides. I have tried usin ...

Utilizing a switch statement for form validation

Currently, I am in the process of creating a form validation that involves two conditions for validation. I'm considering using a combination of switch case and if else statements. Would this be an appropriate approach or is it generally discouraged? ...

Transferring a CSV file to the server from a React application using multi-part form

In order to post a CSV file to an API using React, I have attempted to do so in multipart form. While many tutorials and websites suggest using the fetch() method for sending files to a server, I am encountering some challenges. The issue lies with my RES ...

Learn how to utilize Jquery to create a dynamic slide effect that toggles the

I am looking to change a banner on click functionality. Currently, I have hidden the 2nd banner and banner 1 is displayed. When the arrow is clicked, I want banner 1 to hide and banner 2 to show. The challenge is that I attempted using HTML for this task. ...

How can I include JavaScript in an HTML document?

My folder structure is as follows: Inside webapp/WEB-INF/some.jsp, I also have a javascript file located in the same directory at webapp/WEB-INF/js/myform.js. I referenced it in some.jsp like this: <script type="text/javascript" src="js/myform.js"> ...

Tips for generating a .csv document using data from an array?

I am currently utilizing a PHP class to validate email addresses in real-time. The PHP Script is functioning as expected: validating the emails and displaying the results on the same page by generating a <td> element for each validated email. Howeve ...

What is the best way to display a unique image in a div based on the size of the

Being new to web design, I have a question about creating a webpage with a large image in the center like on GitHub's Windows page. How can I work with the image inside that particular div or area based on different screen sizes? Is it possible to mak ...

"Optimizing website performance with Ajax and securing data with

As I work on developing an Ajax chat application, I have found the need to periodically call a PHP script that checks for new messages in the database. I recently learned about PDO prepared statements and thought they could be useful since only one variab ...

How can I fill in 3 textboxes with the selected Autocomplete value in MVC 4?

I am trying to implement autocomplete functionality in my form, where a text box is already attached to autocomplete. However, I am unsure how to trigger the ActionResult (which returns JSON) when a value is selected, extract the JSON result, and populate ...

"Enhance User Experience with Autoplay.js for Interactive Content and Sound Effects

I'm trying to get both the animation and audio to start playing automatically when the page loads. Currently, the animation pauses when clicked, but I want it to load along with the audio playback. I attempted to use var playing=true; to enable autop ...

Issue with rendering Base64 image array strings in FlatList component in React Native

In my RN App, I am trying to display a FlatList with Image Items but it seems like I have missed something. I am retrieving blob data from my API, converting it to a String using Buffer, and then adding it to an Array. This Array is used to populate the F ...

Updating the display text length on vue-moment

Currently, I am attempting to showcase an array of numbers const days = [1, 7, 14, 30, 60] in a more human-readable format using vue-moment Everything is functioning correctly {{ days | duration('humanize') }} // 'a day' // '7 d ...

Capture latitude and longitude using HTML5 Geolocation and store the values in a PHP variable

In the midst of a project, I am tasked with obtaining the longitude and latitude of a user in order to pinpoint their location. The challenge lies in storing this data in PHP variables, which will ultimately be saved in a MySQL database. Can anyone offer ...