Skip to content

Instantly share code, notes, and snippets.

@procarrera
Created October 19, 2021 19:52
Show Gist options
  • Save procarrera/6f23091738a12039fdfc0105de1a7d7c to your computer and use it in GitHub Desktop.
Save procarrera/6f23091738a12039fdfc0105de1a7d7c to your computer and use it in GitHub Desktop.
Form with file Upload Shopify
<form method="post" action="/cart/add" id="product_form_6149192941727" accept-charset="UTF-8" class="shopify-product-form" enctype="multipart/form-data"><input type="hidden" name="form_type" value="product"><input type="hidden" name="utf8" value="✓">
<label for="upload">Upload Your Logo</label>
<input id="upload" type="file" name="properties[_upload]" class="product-form__input">
</form>
@procarrera
Copy link
Author

      $('[data-add-to-cart]').on('click', function(e) {
        var isFocusEnabled = $('body').hasClass('focus-enabled') ;
        if (isFocusEnabled) {
          return;
        }
        e.preventDefault();
        var form = $(this).closest('form')
        var hasFileInput = false
        if (form.find('[type="file"]').length){
          hasFileInput = true;
        }
        if(hasFileInput){
          var formData = new FormData($('.shopify-product-form')[0]);
          formData.append('upload_file', $('input[type=file]')[0].files[0]);
          $.ajax({
            type: 'POST',
            url: '/cart/add.js',
            dataType: 'json',
            contentType: false,
            processData: false,
            data: formData,
            error: addError,
            success: addSuccess,
            complete: updateHeaderTotal
          });
        }
        else {
          var form_serialized = form.serializeArray();
          var form_object = {};
          $.map(form_serialized, function(val, i){
            form_object[val.name] = val.value;
          });
          ajaxAddItem(form_object);
        }
      });
      var ajaxAddItem = function(data) {
        $.ajax({
          type: 'POST',
          url: '/cart/add.js',
          dataType: 'json',
          data: data,
          error: addError,
          success: addSuccess,
          complete: updateHeaderTotal
        });
      }

@yulia27-mendoza
Copy link

Hey. I realized that this is a code for the product. In fact, I got a form by default. I just need to add an input file and it doesn't appear in the automated message that arrives after the customer has filled out the form. Could you help me?

@procarrera
Copy link
Author

Have you tried with the Ajax function?

@sgoel785
Copy link

Hi @procarrera ,

I tried the code above you shared, but it doesn't upload the file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment