Upload an image converted to `toDataURL` to the server

I've been attempting to integrate the signature_pad library, found at signature_pad, but I am struggling to grasp its functionality.

Can someone guide me on how to retrieve an image value and send it to my server?

Edit:

I have experimented with decoding:

In JavaScript "app.js":

saveButton.addEventListener("click", function (event) {
    if (signaturePad.isEmpty()) {
        alert("Please provide signature first.");
    } else {
        saveSignature(signaturePad.toDataURL());
    }
});

function saveSignature(dataURL) {
$.ajax({
  type: "POST",
  url: "script.php",
  data: { 
     imgBase64: dataURL
  }
}).done(function(o) {
  console.log('saved'); 
});
}

In PHP, "script.php":

<?php
    // requires php5
    define('UPLOAD_DIR', 'images/');
    $img = $_POST['img'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = UPLOAD_DIR . uniqid() . '.png';
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';
?>

Answer №1

Ensure to retrieve $_POST['imgBase64'] in your PHP code instead of using $_POST['img'].

Your PHP script is not outputting data in json format.

Consider updating your code like this:

echo json_encode(['result' => $success ? $file : 'Unable to save the file.'])

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

Tips for aligning text in MUI Breadcrumbs

I am currently utilizing MUI Breadcrumb within my code and I am seeking a solution to center the content within the Breadcrumb. Below is the code snippet that I have attempted: https://i.stack.imgur.com/7zb1H.png <BreadcrumbStyle style={{marginTop:30}} ...

tsc and ts-node are disregarding the noImplicitAny setting

In my NodeJS project, I have @types/node, ts-node, and typescript installed as dev dependencies. In the tsconfig.json file, "noImplicitAny": true is set. There are three scripts in the package.json file: "start": "npm run build &am ...

Instead of loading JSON contents using jQuery AJAX at page load, consider loading it dynamically while typing in the search box

It's odd that there is an XHR request for search results as soon as my page loads. Even though it's hidden from the user, a substantial amount of json data is being loaded. Take a look at my code: $.ajax({ type: "POST", url: "http://localho ...

issue with Laravel dependency dropdown causing issues with ajax request

I've encountered an issue with the dependency dropdown feature in Laravel. <div class="form-group col-md-12{{ $errors->has('professional_id') ? 'has-error' : '' }}"> <label for="profe ...

Is there a way for me to extend an absolute div to the full width of its grandparent when it is within an absolute parent div?

Here is a structured example of my HTML and CSS: <div class="grandparent"> <div class="row">...</div> <div class="absolute-parent"> <div class="absolute-child">...</div> ...

Efficient method of delivering cohesive information from database to user without the need for continuous querying

Within the database, there is stored data about each user that typically remains constant. However, occasionally a user may update their information, such as changing their name. This data includes the user's name, username, and company details. The ...

The next image is crashing on every device except for mine

On my device, the next image works perfectly, but it crashes on every other device. Here is the JSX code: <div className="img-container-homePage"> <Image src="/catI.jpg" alt="Cat" layout="fill" /> < ...

Adding inline SVGs to a Nuxt 3 Vite project: A step-by-step guide

Hey there, I've been struggling with importing inline SVGs into my Nuxt3 Vite project. Any advice would be greatly appreciated. I discovered that using <img src="~/assets/images/icons/push-icon-chatops.svg" /> works, but I actually ne ...

Issue with my JavaScript code for customizing checkboxes: the else condition is not being triggered

I'm currently in the process of customizing my own version of "checkboxes" by styling label elements and moving the actual checkbox off-screen. This is the approach I decided to take based on the design and functionality requirements presented to me. ...

Maximizing Efficiency: Utilizing a Single Panel across Multiple HTML Files with jQueryMobile

Can a panel defined in index.html be used on another page, such as results.html? Or do I have to define the panel on every page and duplicate the HTML code on each page? Because I want the panel to be consistent across all pages. This is the panel in my ...

Implementing pagination in Webgrid using AJAX post method

I've developed this JavaScript code: function PartialViewLoad() { $.ajaxSetup({ cache: false }); $.ajax({ url: "/ControllerAlpha/MethodBeta", type: "GET", dataType: "html", data: { s ...

Tips for removing unnecessary debugging code from JavaScript when compiling or minifying your code

Back in the day, I would always include tons of debug code in my JavaScript app. However, I'm now searching for a method that will eliminate debug code during the compilation/minification phase. Does the world of JavaScript have something similar to ...

Is it possible for you to pinpoint the mistake in the code below?

I've been trying to locate an error in the function but have been unable to do so. As a beginner in this area, I would appreciate your patience. <html> <head><title>print names</title> <script langua ...

What is the method for conducting an Ajax request?

Currently, I am deeply involved in a personal project to enhance my skills with Rails. The project involves developing a task management application that encompasses three primary states: todo, in progress, and done. After numerous days of trial and error, ...

Utilizing a refreshed array of elements within a component directive

When working within a view, I am utilizing ng-repeat inside a directive to iterate over an array of objects from my controller. However, as the objects in the array undergo value changes, I encounter a dilemma when transitioning to a new instance of the sa ...

The Concept of Interface Segregation Principle within jQuery

Could someone provide a clear explanation of how this function operates using jQuery? Especially in reference to the response found here. It seems similar to the Single Responsibility Principle (SRP) in Object-Oriented Programming. What sets it apart? ...

"Dealing with cross-origin resource sharing (CORS)

When calling an API using isomorphic-fetch and the Fetch API, I encountered a CORS issue because the API was hosted on a different domain (this worked fine in production). To work on development locally, I had to run Chrome browser in non-secure mode and ...

The collection is not an array

I am currently running the following code: var n = []; jQuery.toJSON( n ); Interestingly, on one page I receive "[]", while on another I get ""[]"". Both pages are utilizing the same version of jQuery along with a toJson Plugin. Upon inspecting the arra ...

My navigation menu has a nested ul, but on mobile devices, it doesn't display all the items in the list. What could be causing

When I click on "Products" in my main navigation, only the first 6 items are displayed from a nested ul. How can I make all of them display when the user clicks on "Products"? Is this a CSS issue or a problem with the script? Here's a screenshot for r ...

Exploring Firebase's Collection Retrieval through Vue.js

Trying to retrieve a specific collection from Firebase Firestore is giving me an error that I haven't been able to resolve yet. Below is the code snippet from my boot file: import { initializeApp } from "firebase/app"; import { getFirestore ...