-1

I have the following:

SignUp.prototype.submitForm = function() {
    let that = this;

    $(document).on('click', this.buttonSubmitSelector, function(e) {
        e.preventDefault();

        let current = $(this).closest('form'),
            data = current.serialize();

            console.log(JSON.parse(data));

        // if(that.isEmailValid(emailVal)) {
        //  that.removeError(emailInput);

        //  $.ajax({
        //      type: "POST",
        //      url: current.attr('action'),
        //      data: data,
        //      success: function(){
        //          that.displaySuccess(current);
        //          that.resetForm(current);
        //      }
        //  });
        // }
        // else {
        //  that.showError(emailInput);
        // }

    });
}

However, I am getting the following error:

VM26559:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at HTMLInputElement.<anonymous> (signUp.js:60)
    at HTMLDocument.dispatch (jquery.js:5206)
    at HTMLDocument.elemData.handle (jquery.js:5014)

DATA is "form_build_id=form-wKUSwxF8He0krHpGo4N_vzyT9CuUD2HCWNF0dp3tpvk&form_id=sign_up_alert_form&nid=12&title=Production%20Training%20Scheme&email=as-web%40hotmail.com"

I have never come across this error before. How can it be fixed?

Aessandro
  • 5,517
  • 21
  • 66
  • 139

2 Answers2

4
data = current.serialize();
console.log(JSON.parse(data));

The serialize method converts the data in a form to a URL Encoded string.

It does not convert it to JSON so you can't parse it with a JSON parser.

You can decode it with the URLSearchParams API (which is new and shiny and may require a polyfill to work in your browser).

data = current.serialize();
var searchParams = new URLSearchParams(data);
for (let p of searchParams) {
    console.log(p);
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

serialize() does not output JSON format... If you are using jQuery:

data = JSON.stringify(current.serializeArray());