Creating captchas seems like a mistake in reasoning to me

I am encountering an issue with my code. I created a basic newbie-level captcha using Javascript. Below is the code snippet:

<!DOCTYPE html>
<html>
<head>
    <style>
    </style>
</head>

<body>
    <h1>Testing captcha</h1>
    <hr> 
    <img id="firstImage" img src="pictureOne.jpg"> 
    <input type="text" id="firstInput"></input>
    <button type="button" onclick="checker()">Confirm</button>
    <hr> 
    <p id="cone">Please type what you see in this picture, This is a captcha to prevent over-spamming</p>
</body>
<script>
    function checker() { 
        var checkPic = document.getElementById('firstImage').src = 'pictureOne.jpg'
        var takePic = document.getElementById('firstInput').value;
        checkPic.toString()
        if (checkPic === "pictureOne" && takePic === 'c' ) { 
            document.getElementById('firstImage').src = 'pictureTwo.jpg';
            alert("Please confirm the second captcha");
        } else if (checkPic === 'pictureTwo.jpg' && takePic === 'u') { 
            alert("Ready to download.")
        }
    }
</script>
</html>


How does the captcha function? It's designed to be simple - after completing the first captcha, the second image will appear, and upon completion of that captcha, a specific task will be displayed. However, there seems to be an error in the code. I'm unsure if it's a problem with my conditional statements or something else entirely. I've been stuck on this for about 7 hours now and would appreciate any assistance.

Answer №1

The code you provided has several issues that need to be addressed for it to work properly.

  1. It is recommended to remove the unused attribute img from

    <img id="firstImage" img src="pictureOne.jpg">

  2. To ensure the correct functionality, remove = 'pictureOne.jpg' from

    var checkPic = document.getElementById('firstImage').src = 'pictureOne.jpg'
    and retrieve the actual content of element #firstImage instead of setting it to 'pictureOne.jpg' every time

  3. There is a line checkPic.toString() that can be removed as it is unnecessary (and also missing a ; at the end)

  4. Use == instead of ===, as === will compare if both sides are the same object, not just equal. For example, if i=5 and x=5, i==x is true but i===x is false and i===i is true

  5. Consider using .endsWith(" to compare image locations, as they begin with http://xyz.abc/ and only the end needs to be checked

<!DOCTYPE html>
<html>
<head>
    <style>
    </style>
</head>

<body>
    <h1>Testing captcha</h1>
    <hr> 
    <img id="firstImage" src="pictureOne.jpg"> 
    <input type="text" id="firstInput"></input>
    <button type="button" onclick="checker()">Confirm</button>
    <hr> 
    <p id="cone">Please type what you see in this picture, This is a captcha to prevent over-spamming</p>
</body>
<script>
    function checker() { 
        var checkPic = document.getElementById('firstImage').src;
        var takePic = document.getElementById('firstInput').value;
        if (checkPic.endsWith("pictureOne.jpg") && takePic == 'c' ) { 
            document.getElementById('firstImage').src = 'pictureTwo.jpg';
            alert("Please confirm the second captcha");
        } else if (checkPic.endsWith('pictureTwo.jpg') && takePic == 'u') { 
            alert("Ready to download.")
        }
    }
</script>
</html>

Let's discuss the CAPTCHA further or has your query been resolved?

Answer №2

Make sure to only use the image filename in your code, rather than the full URL path. To do this, you'll need to extract the substring from the end of the URL.

<!DOCTYPE html>
    <html>
    <head>
        <style>
        </style>
    </head>

    <body>
    <h1>Testing Captcha</h1>
    <hr>
    <img id="firstImage" src="image.jpg">
    <input type="text" id="firstInput"/>
    <button type="button" onclick="checker()">Confirm</button>
    <hr>
    <p id="cone">Please enter the text shown in the image above. This is a captcha feature to prevent spam.</p>
    </body>
    <script>

        function checker() {
            alert(123);
            var checkPic = document.getElementById('firstImage').src;
            var takePic = document.getElementById('firstInput').value;

            checkPic = checkPic.substring(checkPic.lastIndexOf('/')+1);

            if (checkPic === "image.jpg" && takePic === 'c') {
                document.getElementById('firstImage').src = 'new-image.jpg';
                alert("Please confirm the second captcha.");
            } else if (checkPic === 'new-image.jpg' && takePic === 'u') {
                alert("Ready for download.");
            }
        }

    </script>
    </html>

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

Eliminate the JSON object within jqGrid's posted data

The web page I'm working on features Filters with two buttons that load data for jqGrid when clicked. Clicking 'Filter' generates a postData json object and sends it to the server, which is working perfectly. However, I'm facing an is ...

Angular 2 is throwing an error: Unhandled Promise rejection because it cannot find a provider for AuthService. This error is occurring

My application utilizes an AuthService and an AuthGuard to manage user authentication and route guarding. The AuthService is used in both the AuthGuard and a LoginComponent, while the AuthGuard guards routes using CanActivate. However, upon running the app ...

Retrieve the property value from a nested object using a key that contains spaces

Presenting my object: let obj = { innerObj: { "Key with spaces": "Value you seek" } } Upon receiving, I am unaware of the content within obj. I possess a string variable holding the key to access the value. It appears as follows: let ke ...

AngularJS directive ngShow not working properly

It seems like I'm encountering some scope issues that I can't seem to resolve. Here's a rundown of the problem: I'm trying to create a custom directive called "my-create-content" that will insert an "img" HTML template into the element ...

Formatting in Cx framework: Configuring right alignment and decimal precision on NumberField

Currently, I am involved in a project that involves UI development using Cx, a new FrontEnd framework based on React. You can find more information about Cx at One of the tasks in my project involves creating a Grid with filter fields located at the top ...

Stable Banner with Automatic Scroll to Sections

I have implemented a script that allows for smooth scrolling to different sections within a webpage when clicking on links in the top navigation menu. In the HTML, I've assigned IDs to each section (section1, section2, section3, etc.) and linked these ...

What is the most efficient method for appending /.json to the conclusion of express routes?

I am currently transitioning a DJANGO API to Node.js and have been tasked with ensuring that routes support the .json extension at the end. For instance, sending a GET request to /users/:id/.json should return a JSON object representing the user. The cha ...

Having trouble updating Vuejs array with new values

Currently, I am facing an issue with the template code for my survey builder. I am successfully receiving responses from the server, but the addAnotherQuestion value is not updating as expected. Despite trying various approaches, I have been unable to reso ...

Stream of information that triggers a specific action based on a specified condition

I'm dealing with an observable stream where I need to make two calls after retrieving the initial object using two id's found within the object. One of these id's, siteId, is optional and may or may not be present. If it is present, I need t ...

The data in AngularJS is not being successfully incorporated into the service

Utilizing angularjs and ajax, I am attempting to retrieve data from a webservice and pass it to the controller. To accomplish this, I am using a holder (a factory method or service). The setup works fine without the webservice, but when trying to fetch dat ...

Ways to retrieve Data obtained in response using superagent

I am currently working on hitting an API and extracting the data received in response. To achieve this, I am utilizing superagent to retrieve the data from the API. I have inspected my network tab, however, I am encountering an issue where I want to extra ...

What is the best method to compare dates in JavaScript/JQuery to determine if one comes before the other?

I am completely new to JavaScript development and I need to accomplish the task below: I have 2 input tags containing 2 strings representing dates in the format 01/12/2014 (DAY/MONTH/YEAR). These input tags are used to search for objects with a date field ...

best practices for transferring object data to a table with ng-repeat

I have an object called 'SEG-Data with the following structure. I am attempting to display this data in a table using ng-repeat. SEG_Data Object {ImportValues: Array[2]} ImportValues: Array[2] 0: Object ImportArray: "004 ...

What is the reason that JavaScript does not run the code sequentially?

Looking for a solution with a simple function like this: function getArticles(page){ page = page || 1; loading = false; var articlesCache = getArticlesCache(page); if(articlesCache){ articles = articlesCache.data; }else{ make a request a ...

Show the total of a JavaScript calculation in a designated input box

Is there a way to show the total sum of this calculation in an input field? function calculateSum1() { var sum = 0; //loop through each textbox and add their values $("input.miles").each(function() { //only add if the value is a number ...

In order to access the localStorage from a different component, a page refresh is required as it is

UPDATE: Just to clarify, this question is NOT duplicate of how to retrieve the value from localstorage. My scenario is unique and the issue lies with Angular itself rather than localStorage. I am currently developing an Angular7 application. In one of my ...

Is there a way to retrieve the HTML code of a DOM element created through JavaScript?

I am currently using java script to generate an svg object within my html document. The code looks something like this: mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); myPath = document.createElementNS("http://www.w3.org/2000/svg", ...

"I am sending a JSON object to a PHP script and extracting the

I have created a form with PHP like this: <?php include '../db/baza.php'; ?> <?php include 'vrh.php' ?> <div id="page"> <div id="pageFrame"> <form action="up ...

Verifying file types with HTML5 drag and drop feature

Is it possible to change the drop zone's background color to green or red based on whether the dragged payload contains supported file types (JPEG)? Do Gecko and Webkit browsers have the ability to determine the file type of drag and drop files? ...

Challenge encountered when attempting to remove elements from an array within a for loop

There seems to be an issue with deleting elements from an array within a for loop. var div = document.querySelector('div'); var array = [ "iPad", "iPod", "iPhone" ]; for (let i = 0; i < array.length; i++) { let p = document.createElement ...