Form data is not sent with Event.preventDefault()

Asked

Viewed 143 times

0

When submitting a form, I am using ajax and event.preventDefault() so that the screen is not recharged. In my project, I made a small MVC structure, where the URL that I pass is the path that leads to the desired controller.

When I submit the form via POST without event.preventDefault() everything works normally. But when I put such code, nothing happens in the system, as if the form data were not sent. I’m racking my brain with this.

Follow the code excerpt:

$(document).ready(function() {

    $('form').submit(function(event){ 
            var formDados = jQuery(this).serialize();

            $.ajax({
                type        : 'POST', 
                url         : 'http://127.0.0.1/projeto/index.php?path=capacitacao/adm',
                data        : formDados,
                dataType    : 'json',
                encode      : true,
                success:function(result){
                    console.log(result);
                }
            })
            event.preventDefault();

    });
});
  • The reason surely has nothing to do with preventDefault. The console.log(result); in the success run ? If you don’t run try implementing Handler error with error: function(a, b, c) { console.log(a,b,c); } and see the result

  • I was able to visualize the error message by making this change. Now I will try to solve the error that appeared: parsererror" Syntaxerror: Unexpected token < in JSON at position 0

1 answer

0

Try this, replace "Success" with "done" and add "fail", you can take the "action" from your form so when activating "Submit" it will have nowhere to go.

$(document).ready(function() {    
    $('form').submit(function(event){

            event.preventDefault();

            var formDados = $(this).serialize();

            $.ajax({
                type        : 'POST', 
                url         : 'http://127.0.0.1/projeto/index.php?path=capacitacao/adm',
                data        : formDados

            }).done(function(response){

                 console.log(response);

            }).fail(function(result) {

                  console.log(result);

            });
});
  • I was able to visualize the error message: parsererror" Syntaxerror: Unexpected token < in JSON at position 0

  • takes that and arguments, dataType and Encode

  • It worked. Thank you!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.