Dealing with code issues in Subscription forms using AJAX and JQuery

Currently, I am independently studying jQuery and grappling with the Mailchimp Opt-In form code. Despite various existing queries on this topic, I am curious about why my own implementation, as a beginner in jQuery, is not functioning correctly. My intention is to troubleshoot and improve my code rather than copying solutions from others.

I have already included the post-json?u= and &c=? actions within my HTML code:

<div id="mc_embed_signup">
    <form action="https://xxxxxxxxxx.com/subscribe/post-json?u=xxxxxx;id=xxxxx&c=?" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>

        <div id="mc_embed_signup_scroll">

            <div id="colonna-sx">

                <div class="mc-field-group gruppo-email">                       
                    <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
                    <div id="obbligo-email" class="obbligo-form" style="color:red">Campo obbligatorio</div>
                </div>

                <div class="mc-field-group gruppo-nome">
                    <input type="text" value="" name="FNAME" class="required" id="mce-FNAME">
                    <div id="obbligo-nome" class="obbligo-form" style="color:red">Campo obbligatorio</div>
                </div>

                <div class="clear"></div>

                <div class="mc-field-group input-group gruppo-consenso">
                    <input type="radio" value="Acconsento al trattamento dei miei dati personali." name="CONSENSO" id="mce-CONSENSO-0"><label for="mce-CONSENSO-0">Acconsento al trattamento dei miei dati personali.</label>
                    <div id="obbligo-consenso" class="obbligo-form" style="color:red">Campo obbligatorio</div>
                </div>

                <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_6a6f3b7082472f64c07c2cad3_e065e0e3c4" tabindex="-1" value=""></div>
            </div>

            <div id="colonna-dx">
                <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="mc-button"></div>
            </div>

            <div class="clear"></div>
        </div>
    </form>
</div>

In order to display or hide error messages based on the inputs' validation status, I have implemented CSS rules setting "display:none" for the divs associated with the comments "THIS ONE" and the IDs #obbligo-email, #obbligo-nome, and #obbligo-consenso.

Below is the snippet of my jQuery code:

(function($) {
    var $form = $("#mc-embedded-subscribe-form");
    var stato1;
    var stato2;
    var stato3;

    $("#mc-embedded-subscribe").bind("click", function(event) {
        if (event) event.preventDefault();

        if ($("#mce-EMAIL").val() != "") {
            $("#obbligo-email").css({"display":"none"});
            stato1=true;
        } else {
            $("#obbligo-email").css({"display":"block"});
            stato1=false;
        }

        if ($("#mce-FNAME").val() != "") {
            $("#obbligo-nome").css({"display":"none"});
            stato2=true;
        } else {
            $("#obbligo-nome").css({"display":"block"});
            stato2=false;
        }

        if ($("#mce-CONSENSO-0").is(":checked")) {
            $("#obbligo-consenso").css({"display":"none"});
            stato3=true;
        } else {
            $("#obbligo-consenso").css({"display":"block"});
            stato3=false;
        }

        if (stato1 == true && stato2 == true && stato3 == true) {
            register($form);
        }
    });

    function register($form) {
        $.ajax({
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $form.serialize(),
            cache: false,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
        });
    };

}(jQuery));

Despite researching similar issues on StackOverflow without success, I seek assistance to comprehend any mistakes in my approach.

My goal is to maintain visible error messages when input fields are empty and set boolean variables accordingly for form submission. The form should be sent via Ajax without page reload upon successful validation, clearing the input fields simultaneously.

Some unanswered queries:

If I switch the "method" to "get," it results in a 404-page error.

If I include "$(document).ready( funtion(){", the JavaScript file fails to execute properly, which remains unclear to me despite attempts with alerts.

Answer №1

Your jQuery code contains a syntax error that is causing issues. You are ending your if/else statement with a comma, which is incorrect. The correct way to end an if/else statement in jQuery is to use curly braces {} without any commas after them.

Additionally, there is a mistake in your jQuery check:

if ($("#mce-CONSENSO-0").is("=checked"))

You should be using :checked, not =checked. The correct syntax should be:

if ($("#mce-CONSENSO-0").is(":checked"))

In response to your PS question:

PS: It seems you are making a POST request to an external API endpoint

https://xxxxxxxxxx.com/subscribe/post-json[...]
. It appears that this endpoint may only handle POST requests and not GET requests, resulting in a 404 error (The server cannot find the requested resource). For more information about status codes, you can visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404

Answer №2

ensure that the Json object's last key/value pair does not have a comma at the end

              $.ajax({
                 type: $form.attr('method'),
                 url: $form.attr('action'),
                 data: $form.serialize(),
                 cache: false,
                 dataType: 'json',
                 contentType: 'application/json; charset=utf-8'
          })

Make sure to remove the trailing comma on this line

contentType: 'application/json; charset=utf-8'

Snippet of the provided code:

            $(function(){

                $("[type=submit]").on("click", function(e){

                    // ---Prevent form submission

                    e.preventDefault();

                    let errors = false;


                    // --- Check for empty fields and display an exclamation mark icon if found

                    if($("[type=text]").val() == ""){
                        $("[type=text]").css("background", "url('exclamation-outline.svg') no-repeat right");
                        errors = true;
                    }
                    
                    if($("[type=text]").val() == ""){
                        $("[type=text]").css("background", "url('exclamation-outline.svg') no-repeat right");
                        errors = true;
                    }
                    

                    // --- Process form
                    if(errors == false)
                    register($("form"));

                });

                function register($form) {

                    

                    $.ajax({
                        
                            type: $form.attr('method'),
                            url: $form.attr('action'),
                            data: $form.serialize(),
                            cache: false,
                            dataType: 'json',
                            contentType: 'application/json; charset=utf-8'

                    });

                };

            });
            * { margin: 0px; padding: 0px; box-sizing: border-box; }
            ul{ list-style: none; }
            body, html { height: 100vh;  }
            input{ outline: none; border: none; background: none;  }
            h1, h2, h3, h4, h5, h6{ font-weight: normal; }
            p, li, a, h1, h2, h3, h4, h5, h6{ user-select: none; } 
            body{ display: flex; justify-content: center; align-items: center; }
            input{ height: 48px; display: block; width: 320px; margin-bottom: 24px; }
            input:not([type=submit]){ border-bottom: 1px dashed grey;  }
            input[type=submit]{ background: grey; border-radius: 4px; cursor: pointer; color: white; }
        <form action="?user=login" method="POST" >
            <input type="text" placeholder="Username" />
            <input type="password" placeholder="password" />
            <input type="submit" />
        </form>

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

Unexpected output received from PHP form

I'm new to coding and I have a question, even though it may seem silly. I've been following a tutorial on YouTube, but my code isn't working as expected compared to what the mentor is demonstrating. <?php if (isset($_POST['subm ...

Having trouble with jQuery animate function?

I have been struggling to get my animate function to work, despite looking at multiple similar posts and making modifications to my code. My goal is to make an image of a plane move from left to right across the screen and stop halfway. Here is the code I ...

Adjusting the selected state of an HTML/CSS checkbox with JavaScript

After downloading a theme with a tailored switch component that replaces the standard checkbox functionality, I noticed that the 'checked' status of the underlying checkbox does not change upon click or touch events. Here is the HTML structure: ...

How to retrieve the correct instance of "this" from a callback function within an array of functions nested inside an object

Trying to access the "helperFunction" from within a function in the "steps" array has been quite challenging. It seems that using "this" does not point to the correct object, and I have been struggling to find the right solution. const bannerAnimation = { ...

Is there a permanent solution to fixing the error code -4094 that is repeatedly occurring during React Native startup?

When attempting to execute react-native start, an error occurred which has not been encountered before. The error message is as follows: ERROR ENCOUNTERED Loading dependency graph...events.js:287 throw er; // Unhandled 'error' event ...

Having issues with the input event not triggering when the value is modified using jQuery's val() or JavaScript

When a value of an input field is changed programmatically, the expected input and change events do not trigger. Here's an example scenario: var $input = $('#myinput'); $input.on('input', function() { // Perform this action w ...

Learn how to toggle between two different image sources with a single click event in JavaScript

If the button is clicked, I want to change the image source to one thing. If it's clicked again, it should change back to what it was before. It's almost like a toggle effect controlled by the button. I've attempted some code that didn&apos ...

Unable to present information retrieved from REST API, despite data being provided by the server

I'm attempting to make a REST call using a token in the header to retrieve information. To include the required header token, my code is structured as follows within my restClient.js, app.js, and users.js files. //restClient.js import { jsonServerR ...

What could be causing React onclick events to not trigger when wrapped within a Vue application? (No additional libraries)

As I dive into the world of combining React and Vue components, I encountered an interesting challenge... const RootTemplate = () => { return ( <div id="vue-app"> ... <IconButton color="inherit" onClick={thi ...

What sets npm install apart from manual installation?

I've been exploring requirejs recently. I'm trying to decide between installing it using npm install requirejs or manually downloading it from the website. Are there any differences between the two methods? Are there any advantages or disadvantag ...

How can I move a complete range of values up using the Google Sheets API in Node.JS?

I'm working with a Google Spreadsheet that is being accessed and modified by a Node.JS app. There's a specific situation where I need to shift an entire range up (moving A3:D up by one cell), but due to my limited experience with the Google Shee ...

Using NodeJS and ExpressJS to send the HTTP request response back to the client

After creating a website using Angular 2 and setting up node.js as the backend, I successfully established communication between the Angular client and the node.js server. From there, I managed to forward requests to another application via HTTP. My curren ...

HTTP request in Angular with specific body content and custom headers

My goal is to access the sample API request from , as demonstrated in the documentation: curl -H "api-key: 123ABC" \ -H "Content-Type: application/json" \ -X POST \ ...

Unable to receive a response in React-Native after sending a post request

My current challenge involves sending a response back after successfully making a post request in react-native. Unfortunately, the response is not arriving as expected. router.route("/addUser").post((req, res) => { let name= req.body.name; connection ...

"Implement a function in Node.js/JavaScript that creates a new JSON object if the ID matches with the ID of another

const data = [ { system: { id: "4gSSbjCFEorYXqrgDIP2FA", type: "Entry", content: { type: { name: "Author" } }, }, DataDetails: { shortSlugOption: { "en-us": "some value", "za-op": "random value" }, ...

Typedoc Error: Attempted to assign a value to an undefined option (mode)

After installing typedoc with the command npm install typedoc --save-dev, I proceeded to add typedocOptions to tsconfig.json: { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", // ...some lin ...

Employ jQuery to send data to a php script

I am currently developing a search engine and I am trying to send data from jQuery to PHP. Below is the jQuery code I am using: <script> $(document).keypress(function(e) { if(e.which == 13 && $('#textfield').val()) { $ ...

Can data be transferred between browsers, such as from Google Chrome to Mozilla Firefox?

I have a dilemma with two separate pages—one for Admin and the other for User. The Admin page is named index.html <!DOCTYPE html> <html lang="en"> <head> <style> * { padding: 0; ...

What is the best way to extract a thumbnail image from a video that has been embedded

As I work on embedding a video into a webpage using lightbox, I'm looking for advice on the best design approach. Should the videos be displayed as thumbnails lined up across the page? Would it be better to use a frame from the video as an image that ...

Encountering a "Module not found" error while trying to run npm start in a Create React App

I'm attempting to initiate a React project using create-react-app. Encountered an error when running npm start: Failed to compile. multi ./node_modules/react-scripts/config/polyfills.js ./node_modules/react-dev-utils/webpackHotDevClient.js ./src/i ...