Send the customer to a new page following an account creation error during submission

Whenever the user clicks on the "create" label, I have set up a redirection to another page. However, an issue arises when I activate the code snippet below for the redirection:

<script>
  (function() {
    var REDIRECT_PATH = '/pages/become-a-partner-submit';

    var selector = '#create_customer, form[action$="/account"][method="post"]',
        $form = document.querySelectorAll(selector)[0];

    if ($form) {
      $redirect = document.createElement('input');
      $redirect.setAttribute('name', 'return_to');
      $redirect.setAttribute('type', 'hidden');
      $redirect.value = REDIRECT_PATH;
      $form.appendChild($redirect);
    }
  })();
</script>

The form error parameters do not seem to be functioning correctly. For instance, if the password field is empty and the user clicks on the "create" button, it still redirects to the specified path. Disabling the JavaScript code resolves this issue as it prohibits users from creating an account if essential fields are left empty. How can I maintain both the form error handling and redirecting the customer after successful account creation?

Below is my complete code:

<script src="https://www.google.com/recaptcha/api.js?render=6LeJp8EgAAAAAN2IymRMhGeete2PDs2hOsRHCWvB"></script>

<div class="central py-medium" id="template">
  <div id="customer">
    <!-- Create Customer -->
    <div id="create-customer">
      <div class="template_header">
        <h1 class="h2 feature-header" data-cc-animate>{{ 'customer.register.title' | t }}</h1>
      </div>

      ...

{% comment %}
<script>
  (function() {
    var REDIRECT_PATH = '/pages/become-a-partner-submit';

    var selector = '#create_customer, form[action$="/account"][method="post"]',
        $form = document.querySelectorAll(selector)[0];

    if ($form) {
      $redirect = document.createElement('input');
      $redirect.setAttribute('name', 'return_to');
      $redirect.setAttribute('type', 'hidden');
      $redirect.value = REDIRECT_PATH;
      $form.appendChild($redirect);
    }
  })();
</script>

{% endcomment %}

Answer №1

Solution

Below is the code to be included under the {% 'create_customer' %} form.

<div class ="errors"> </div>

Insert the script below and customize the URL as needed.

<script>
  jQuery(function() {
jQuery('#create_customer').submit(function(event) {
  event.preventDefault();
  var data = jQuery(this).serialize();

 //create new account
  jQuery.post('/account', data)
    .done(function(data){
    var logErrors = jQuery(data).find('.errors').text();

    //display errors in the HTML form if there are any
    if (logErrors != "" && logErrors != 'undefined'){
        jQuery('#create_customer .errors').html(logErrors);
        jQuery('#create_customer .errors').show();

    //redirect to checkout page upon successful account creation
    }else{
       console.log('success');
      document.location.href = 'CHANGE URL';
    }
    }).fail(function(){console.log('error');});
   return false;
}); 
});
</script>

Full code provided below:

    {% form 'create_customer'%}
        
      <div class ="errors"> </div>
      
      {{ form.errors | default_errors }}
      <div class="form">
        <div class="input-row" data-cc-animate data-cc-animate-delay="0.2s">
          <input aria-label="{{ 'customer.register.first_name' | t }}" placeholder="{{ 'customer.register.first_name' | t }}" type="text" value="" name="customer[first_name]" id="first_name" class="large" size="30" />
        </div>

        <div class="input-row" data-cc-animate data-cc-animate-delay="0.35s">
          <input aria-label="{{ 'customer.register.last_name' | t }}" placeholder="{{ 'customer.register.last_name' | t }}" type="text" value="" name="customer[last_name]" id="last_name" class="large" size="30" />
        </div>

        <div class="input-row" data-cc-animate data-cc-animate-delay="0.5s">
          <input aria-label="{{ 'customer.register.email' | t }}" placeholder="{{ 'customer.register.email' | t }}" type="email" value="" name="customer[email]" id="email" class="large" size="30" />
        </div>

        <div class="input-row" data-cc-animate data-cc-animate-delay="0.65s">
          <input aria-label="{{ 'customer.register.password' | t }}" placeholder="{{ 'customer.register.password' | t }}" type="password" value="" name="customer[password]" id="password" class="large password" size="30" />
        </div>

        <div class="wide-action">
          <input type="submit" value="{{ 'customer.register.submit' | t }}" data-cc-animate data-cc-animate-delay="0.8s"/>
          
          <a href="https://arditicollection.com/account/login?return_url=%2Faccount">
          <p style="padding-bottom:5px;">Back to Login Page</p>
          </a>
          
          <span class="note" data-cc-animate data-cc-animate-delay="0.95s">
            <a data-cc-animate-click href="{{ routes.root_url }}">
              {{ 'customer.register.cancel' | t }}
            </a>
          </span>
        
        </div>
      </div>
      {% endform %}


<script>
  jQuery(function() {
jQuery('#create_customer').submit(function(event) {
  event.preventDefault();
  var data = jQuery(this).serialize();

 //create new account
  jQuery.post('/account', data)
    .done(function(data){
    var logErrors = jQuery(data).find('.errors').text();

    //if there are errors show them in the html form
    if (logErrors != "" && logErrors != 'undefined'){
        jQuery('#create_customer .errors').html(logErrors);
        jQuery('#create_customer .errors').show();

    //if account creation is successful show checkout page
    }else{
       console.log('success');
      document.location.href = '/pages/create-account-submit';
    }
    }).fail(function(){console.log('error');});
   return false;
}); 
});
</script>

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

Module exists; however, command could not be located

I am experiencing an issue with the rimraf node module. Despite being able to access its folder within the node_modules directory, I am receiving errors indicating that the command for rimraf cannot be found. I have attempted to delete the entire node_mod ...

What is the best approach to creating a versatile JavaScript module that can be easily customized for various scenarios?

I am in the process of developing a JavaScript module that will submit data via an AJAX request when a button (next or previous) is clicked at the bottom of a modal. Once the data is submitted, the next modal out of a total of 4 will be displayed. The cha ...

Unraveling HTML elements within a string using MongoDB: A step-by-step guide

Currently, I am in the process of creating a blog from scratch as a way to enhance my skills. The posts' content is stored as a long string in MongoDB with some random HTML tags added for testing purposes. I am curious about the conventional method fo ...

Creating an HTML layout or template directly within a JavaScript bookmarklet

Currently, I am using a bookmarklet that generates a user interface for interaction. The method I have been using involves creating elements using $('<element>').addClass().css({..});, but this approach is proving to be difficult to maintai ...

The Interactive Menu Toggler: A jQuery Solution

$(window).on('resize', function() { if ( $( window ).width() > 768 ) { $('#menu-main-navigation').show(); } }); $('#nav-toggle').on('click', function() { // start of the nav toggle $('#m ...

Animation that responds to scrolling movements

Is there a way to animate text based on scrolling? <p class="class">TEXT</p> transform:translateX(-500px);opacity:0; transform:translateX(0px);opacity:1; ...

Send nodejs express static request over to secure https server

Is there a way to ensure all HTTP requests, including those for static files, are redirected to HTTPS? This is the code I currently have: app.use(express.static(__dirname + '/public')); app.get('*', function(req, res) { if (!req. ...

Animate custom scrollbars with jQuery for a unique browsing experience

I am experimenting with creating a scrolling animation using mCustomScrollbar Currently, I have managed to obtain the current scrollTop and animate it to a specific height using the code below: $("#content").mCustomScrollbar({ scrollButtons:{ ...

Unexpected border-bottom styling issue observed on adjacent div elements

This is my unique code: <!DOCTYPE html> <html> <head> <style> </style> </head> <body> <div style="border-bottom:1px solid black"> <div style="width=50%;float:left">A new paragraph with u ...

What steps can I take to properly center and repair my web page that is currently a mess

This web page I'm working on is giving me a headache. The #titlediv just won't center and the navbar keeps disappearing randomly. It seems like a big issue that I can't wrap my head around. If anyone out there can help salvage it, here' ...

Tips for displaying user-entered information from a form after submitting it with PHP

How can I display the email in the email text input field with this code? It doesn't seem to work correctly when there is a failed login attempt. value= "if(isset($_POST['submit'])){ ?PHP echo $_POST[''email']?>"; ...

How can we determine in JavaScript whether a certain parameter constitutes a square number?

I've developed a function that can determine whether a given parameter is a square number or not. For more information on square numbers, check out this link: https://en.wikipedia.org/?title=Square_number If the input is a square number, it will ret ...

Vue.js is displaying an error message stating that the data property is

I am struggling to access my data property within my Vue.js component. It seems like I might be overlooking something obvious. Below is a condensed version of my code. The file StoreFilter.vue serves as a wrapper for the library matfish2/vue-tables-2. &l ...

Implement a maximum height restriction on the children of the Select component in Material-UI

Currently, I am working with the Material-UI react library to create Dropdown menus by utilizing components like <FormControl>, <Select>, and <MenuItem>. The options array for these dropdown menus is quite extensive, and I am looking to s ...

Tips for removing red borders on required elements or disabling HTML validation

I am on a mission to completely eliminate HTML validation from my project. Although this question suggests that having all inputs inside forms can help, I am using angularjs and do not require a form unless I need to validate all fields in a set. Therefore ...

Implementing a hamburger menu across various webpages

I recently followed a tutorial on adding a hamburger menu from this YouTube video. The menu works perfectly on the INDEX.html page, but when I try to add the same code to other pages like "contact" or "about", none of the menu features seem to work. I rea ...

Searching for a specific set of rows within an array? Look no further than jQuery and JavaScript

I'm struggling to find the right title for my project, but I'm doing my best to capture its essence. I am in the process of developing a calculator that compares values within multiple arrays. Each data item in my array consists of 34 rows, wit ...

A guide on retrieving an object and showcasing it in HTML using JavaScript

Can someone share a method to iterate through an object array in JavaScript? I have an array called sample where the property options needs to be displayed using lit-HTML for each object. var sample = [{ "trans": [{ "id": "trans", "fee": 20, ...

Convert information into an Observable

I have a scenario where I am fetching a list of items from an Observable in my Angular service. Each item contains an array of subjects, and for each subject, I need to make a separate API call to retrieve its details such as name, description, etc. Data ...

What is the most secure approach for defining the file path of an HTML file within an express.js application?

In my directory setup, I have the index.js file located at: path/to/home-page/src/routes This is also where you can find the __dirname. The html file resides at: path/to/home-page/public/bootstrap/Homepage/page.html To serve the html document by relati ...