The Magento newsletter AJAX request is returning a null value

My attempts to submit a newsletter subscription request to Magento are failing, as it returns null and no action is taken.

I have looked into various URLs for posting the request and even copied the code from the base template file.

It seems that I might not be sending the correct parameters or something else is wrong.

This is the current code being used:

<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
    <input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
    <button type="submit" id="ajax-newsletter-submit" title="CADASTRAR" 
    class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>

    </div>
</form> 

Javascript:

   var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');

   $j(function() {
       $j("#ajax-newsletter-submit").click(function() {        
        var email =$j("#newsletter").val();
        var url=$j(".url").val();
        var dataString = 'email='+ email;
            if(email=='') {
               $j("#newsletter").focus();
            } else {
                var a = email;
                var filter = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
                if(filter.test(a)){
                    $j.ajax({
                        type: "POST",
                        url: url,
                        data: dataString,
                        success: function(){                
                            alert('Subscription successful!');
                            $j("#newsletter").val('');
                        }
                    });
                } else {
                    $j("#newsletter").focus();
                }
            }  
            return false;
        });
    });

Answer №1

Give this code a try:

 var form_validator = new FormValidator('your_form_id');
jQuery("#your_form_id").submit(function(e)
{
    if (form_validator.validator && form_validator.validator.validate())   
    {        
        var form_data = jQuery(this).serializeArray();
        var form_action_url = jQuery(this).attr("action");
        jQuery.ajax(
        {
            url : form_action_url,
            type: "POST",
            data : form_data,
            success:function(data, textStatus, jqXHR)
            {   
                alert('Submission successful');
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                alert('Submission failed');
            }
        });
        this.reset(); // Reset form fields
        e.preventDefault(); // Prevent default action
        e.unbind(); // Unbind to prevent multiple form submissions.
    }
});

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

The curtains fail to load when transitioning to a new page

Currently, I am using curtainjs on my website. The issue I am facing is that when I navigate from my landing page to the about page, curtainjs doesn't work initially. However, upon refreshing the page, everything starts working as expected. Below is ...

Error encountered: Unable to compute centroids with Three.js / Collada due to an undefined value

There seems to be an issue when utilizing the ColladaLoader JavaScript, as it throws an error stating "undefined is not a function" in line 2403 of ColladaLoader.js. Despite following the example provided by simply loading the .dae file: var loader = new ...

Leverage the version attribute within package.json within one of its scripts

Is there a way to access the version attribute of my package.json file within one of its scripts? I want to include the version number in the name of the JS bundle, instead of using a hash as an identifier. This is what I currently have: "build-js": "bro ...

jquery causing issues with content loading

Greetings everyone, I have been attempting to load content into a div using this tutorial with the help of jQuery. However, I am encountering an issue where when I click on the link <a href="about.html" class="panel">Profile</a> , it loads ...

Display content from an external HTML page within a div using Ionic

Currently, I am facing an issue where I am utilizing [innerHtml] to populate content from an external HTML page within my Ionic app. However, instead of loading the desired HTML page, only the URL is being displayed on the screen. I do not wish to resort t ...

Spherical outline in the void (threejs) (3D)

Is there a way to remove the line in this image and only keep the contour? Click here to view the figure. const intersection = (a, b, c, heightC) => { return (u, v) => { const height = heightC || c; const size = 5; u = u ...

Tips on assigning a value to a dynamically generated drop-down element

I used arrays of strings to populate drop-down menus. Is there a way to automatically set the value of each option to match the text content? el.value = opt; seems to be ineffective. var validCoursesKeys = ['opt 1','opt 2','opt ...

Creating a new attribute within a JavaScript object by utilizing the properties of its sibling elements

Imagine a scenario where you have a complex array of objects structured like this: [ { "title": "Fundamentals", "order": 1, "lessonRef": "fundamentals", "children": [ { "title": "History", "order": 1, "lesso ...

How to determine if a variable has been declared in JavaScript but not assigned any value

Is there a way to check if a variable has been declared but not assigned a value? I've looked at similar questions and they all seem to recommend using typeof myVar !== 'undefined' However, this always returns false because even when decl ...

Discovering the most recent Node.js version: A step-by-step guide

Is it possible to check the latest available Nodejs version using npm? While node -v allows us to see the current version, I am curious if there is a way to access the most recent version through JavaScript. For example, process.version can be used to vi ...

Adjust the sizing of all fonts following the switch in font styles

Seeking help for adjusting font-size across a responsive web page design using different font families. font-family:Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", serif; To achieve responsiveness, various media queries were applie ...

Discovering the Error Message within the Error Object transmitted by NodeJS to Angular

When handling errors in Nodejs functions using a try/catch scope, an error may be returned in cases such as when the user doesn't exist or when the database is unreachable. The code snippet below demonstrates this scenario: router.delete('/delete ...

After a brief period of running, my AJAX request begins to malfunction

I'm attempting to automatically update two sections of my webpage every 4 seconds. Currently, my AJAX setup looks like this: setInterval(function () { autoUpdate() }, 4000); function autoUpdate() { $.get('/hello&a ...

Storing values from a content script into textboxes using a button press: a simple guide

I am new to creating chrome extensions and currently utilizing a content script to fetch values. However, I am facing difficulty in loading these values into the popup.html. Here is the code snippet: popup.html <head> <script src ...

How to implement file upload using CodeIgniter and jQuery AJAX

Currently, I am in the process of developing a simple CRUD application using jQuery and AJAX. Here are snippets of the code I've been working on: welcome.php public function add_contestant() { $this->validate(); $path = 'img/'; ...

"Exploring the density of the xAxis in Highcharts

Currently, I am incorporating Highcharts into my jsp. Typically, when using Highcharts, we are able to create charts with all points evenly spaced along the x-axis. However, in this instance, I am interested in setting the points based on their x-values ...

Encountered an error with the POST request - TypeError: Unable to access the 'name' property as it is undefined

I'm currently facing some issues with using nodemailer to send emails. I believe I have everything set up correctly. I came across some posts mentioning deprecated code with the body parser, and I attempted their solutions...I think I've implemen ...

Enhance the loading time for ajax-based Select2 functionality

Attempting to utilize a select2 feature with approximately 40,000 searchable entries is causing significant delays in loading. Is there a more efficient method of transferring the dataset to a quicker source like memcache or redis to enhance the performa ...

Using a locally hosted HTML page to update a JSON file stored on my computer

In my current project, I need to reorganize data stored in an array named unknown. Each item in this array needs to be moved either to a new array called good or another one called bad. let data = { "bad":[], "unknown": ["b", "a", "d", "g", "o", ...

Ways to halt a CSS animation when it reaches the screen boundary

I put together this demo: By clicking, a red box falls down. The issue arises when trying to determine the screen size using only CSS. In my demo, I set the box to fall for 1000px regardless of the actual screen height. Here is the keyframe code snippet ...