Is there a way for me to verify the validity of the src attribute for an image?

I'm currently in the process of building a meme generator. The idea is that when a user clicks a button, a meme will be generated. However, if the user has not selected an image, an empty image is created instead. To prevent this, I need to implement some sort of check to verify whether the image has been chosen.

Below is the code used to select the image:

function readURL(input) {
       if (input.files && input.files[0]) {
           var reader = new FileReader();

           reader.onload = function (e) {
               $('.blah')
                   .attr('src', e.target.result);
           };

           reader.readAsDataURL(input.files[0]);
       }
   }

Following this, I am attempting to create a check to determine if the src attribute is set. Despite my efforts, the code continues to execute and produce an empty image:

function createMeme(){
  let make = $('.blah');
  let out = $('#img-out > img');

  if (make.src) {
    return "oijoijojioij";
  } else {
    html2canvas([document.getElementById('gen-img')], {
      onrendered: function (canvas) {
        var imagedata = canvas.toDataURL('image/png");
        var imgdata = imagedata.replace(/^data:image\/(png|jpg);base64,/, "");
        
        //ajax call to save image inside folder
        $.ajax({
          url: 'save-image.php',
          data: {
            imgdata:imgdata
          },
          type: 'post',
          success: function (response) {
            console.log(response);
            out.attr('src', response);
          }
        })
      }
    });
  }
}

Answer №1

Instead of using FileReader(), you have the option to utilize the Javascript Image class.

var img=new Image();
img.onload=function(){
   ...
};
img.onerror=function(){
   ...
};
img.src=URL;

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

Unable to store the data retrieved from MySQL into an array

Every time I try to add the object result1 to the array a, it ends up empty. Can someone help me figure out what I'm doing wrong? app.get('/freezer', (req, res) => { var a = []; var sql = `SELECT freezer_id FROM freezer_data`; ...

Using Javascript to dynamically add variables to a form submission process

Looking to enhance my javascript skills, I've created a script that locates an existing id and exchanges it with a form. Inside this form, I'm aiming to incorporate javascript variables into the submit url. Unsure if this is feasible or if I&apo ...

Can ReactJS and jQuery be used together or are they mutually exclusive?

As a beginner in the world of ReactJS, I am intrigued by how this library essentially handles all DOM node rendering without any need for interference from other libraries like jQuery. However, this does pose a challenge as many convenient jQuery plugins ...

creating a custom type with enums in Angular can lead to implicit 'any' issues

Why does the key of [type] require a type? It may sound strange, but I am facing an issue. Here is some example data: export enum ENUM_Bike { suzuki = 'suzuki', yamaha = 'yamaha', kawasaki = 'kawasaki' } export type T ...

The next.js Head component that is imported from next/head is not functioning correctly when used on share pages

I recently switched my website from create-react-app to create-next-app, but I'm having issues with the Head(app/head) component. Let's say I have a blog section with pages structured as follows: pages/blog/index.js and pages/blog/[slug].js. In ...

Leveraging the power of Angular.js to generate random user profiles

I am attempting to utilize the RUG (Random User Generator) API for a project, but I am struggling to make it function correctly. I have been trying to initiate an HTTP request after a click event, but unfortunately, it does not seem to be working as expect ...

The bar graph dataset is not correctly configured when utilizing ng2 charts and ng5-slider within an Angular framework

Currently, I am working with a range slider and bar graph. My goal is to dynamically change the color of the bar graph using the range slider. While I have managed to successfully alter the color of the bars, I am facing an issue where the data displayed ...

Activating controllers with 2 independent sliders

(Using the WordPress Slider Revolution plugin) I have set up two sliders next to each other - one displaying the service name and description, and the other showing images. The goal is for clicking a specific bullet on the service slider to also trigger t ...

Master the art of zeroing in on your drawing once it's complete

Please review the Demo and provide instructions on how to enhance the zoom function for Google Maps after the map is drawn. let map; let drawingManager; $(document).ready(function () { const latlng = new google.maps.LatLng(49.241943, -122.889318); ...

What is the best way to use JavaScript to click on a block and retrieve its attribute value?

Struggling to capture the data-id attribute value of each item on click, despite researching online. Seeking guidance as I navigate the learning process and encounter programming frustrations. document.addEventListener("click", handle); const demo = e. ...

Consider using React Components as an alternative to implementing pagination dots within Swiperjs, as it may help resolve the issue displaying

I seem to be encountering a small issue and I believe I am making a mistake somewhere. How can I replace the default dots with custom elements for pagination in Swiperjs for React? The custom element should return an SVG from an array of icons. Initially ...

How to modify the color of the placeholder text in a select dropdown using Material-ui

I have a material-ui select component that displays a dropdown menu of options for the user to choose from. The placeholder text, which currently reads "select option," appears in light grey to prompt the user to make a selection. However, I am concerned t ...

NGRX Store: Unable to modify the immutable property '18' of the object '[object Array]'

While attempting to set up an ngrx store, I encountered 7 errors. Error Messages: TypeError: Cannot assign to read only property '18' of object '[object Array]' | TypeError: Cannot assign to read only property 'incompleteFirstPass ...

Error in the syntax of the express router.get() function

I'm attempting to develop a pathway for retrieving JSON data from a JSON-RPC API. Here is my current code: router.get('/balance', function(req, res, client) { res.json({ client.getBalance('*', 1, function(err, balance ...

Experimenting with the input type generated by the Form Helper tool

Before generating the form using Form Helper, is there a method to preview the type of input it will produce? I would like to confirm whether it will result in a select or multi-select element before loading the page. ...

What is the reason for needing to refresh when submitting form data in a Node application with an HTTP POST

Code Snippet - Angular .state('studentInfo.newStudent', { url : '/new/student', templateUrl: 'students/new-student.html', controller : function($state, $http){ this.saveStudent = func ...

Is it advisable to use an autosubmit form for processing online payments?

Situation: In the process of upgrading an outdated PHP 4 website, I am tasked with implementing an online payment system. This will involve utilizing an external payment platform/gateway to handle transactions. After a customer has completed their order ...

Ways to resolve the issue of missing data display in Angular when working with the nz-table

Below is the code snippet: <nz-table #listTable nzSize="middle" [nzData]="data"> <thead> <tr> <th nzShowExpand></th> <th>Location</th> <th>Device</th> ...

What is the process of developing a straightforward Node.js script to encapsulate a binary or executable file?

I am looking to develop a Node.js file that can seamlessly execute an executable binary file and handle all inputs and outputs, specifically targeting Windows operating systems. Reason for this: I aim to install an executable tool via npm install -g in or ...

In JavaScript, it is important to adjust the parameters of the anonymous function and store them in a global variable for efficient code

Is there a way to access the value returned by an anonymous function used as a parameter in another JavaScript function? In the scenario where registerDevice method is called, how can I retrieve the "status" value of the anonymous function outside of its ...