Help Needed Inserting Form Validation.

Highlighted
New Member
1 0 0

Hi, I'm pretty new to Javascript but I'm looking for someone to help me put these two pieces of code together. I'm currently using the Debut theme by Shopify but I needed to have a file upload option for my products. I understand that AJAX doesn't allow for file uploads so I found a site with a tutorial on how to get around this. 

https://www.cloudlift.app/blogs/shopify/how-to-add-a-file-upload-on-shopify-product-pages

I added the first piece of script just fine but I'm getting syntax errors when I try inserting the second piece of code which is supposed to do form validation.

This is the first piece of code:

 // NEW: implementation to allow ajax file uploads & required checks
    _addItemToCart: function($form) {

      // You need to use standard javascript object here
      // create form data with all the fields from the form
      // FormData is >=IE10
      var formData = new FormData($form[0]);

      var params = {
        type: 'POST',
        contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
        processData: false, // NEEDED, DON'T OMIT THIS
        url: '/cart/add.js',
        data: formData,
        dataType: 'json',
        success: function(item) {
          this._hideErrorMessage();
          this._setupCartPopup(item);
        }.bind(this),
        error:  function(response) {
          this.$previouslyFocusedElement.focus();
          var errorMessage = response.responseJSON
              ? response.responseJSON.description
              : theme.strings.cartError;
          this._showErrorMessage(errorMessage);
          this._handleButtonLoadingState(false);
        }.bind(this)
      };

      // execute ajax add to cart
      $.ajax(params);
    },

And here's the second:

    _addItemToCart: function($form) {

      var valid = true;

      // required fields validation
      $.each($form.find('input.required'), function (index, element) {
        if(!$(element).val()){
          valid = false;
        }
      });

      if(!valid){
        this._showErrorMessage('missing required fields');
        this._handleButtonLoadingState(false);
        return;
      }
      
      ...
   }

I keep returning syntax errors or the program won't run. Let me know if you have any suggestions on how to combine these scripts.

 

The password to the site is iadrao

0 Likes