Why does this Javascript code not work?

Asked

Viewed 75 times

1

Why This Javascript Doesn’t Work?

Javascript code:

$('#basic_validate').submit(function(e) {
    document.getElementById('successmsg').style.display = 'none';
    document.getElementById('errormsg').style.display = 'none';
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "../suppliers/resources/controllers/register.php",
        async: true,
        data: $(this).serialize(),
        success: function(data) { 
        },
        complete: function(result){
            if(result == true){
                //clear inputs
                document.getElementById('successmsg').style.display = 'block';
            }else{
                document.getElementById('errormsg').style.display = 'block';
            }
        }
    });
});

HTML code:

<form class="form-horizontal" method="post" name="frmLogin" id="frmLogin">
//text_inputs

1 answer

1

If you are doing Submit by ajax you have to stop Submit by HTML.
For that you have to use the .preventDefault().

Use like this:

$('#frmLogin').submit(function(e) {
    e.preventDefault(); // <------------
    $.ajax({
        type: "POST",
        url: "../controllers/insert.php",
        async: true,
        data: $(this).serialize(),
        success: function(data) { 
        },
        complete: function(result){
            if(result == 10)
                //clear inputs
                //show msg success
            else
                //show msg error
        }
    });
}); 
  • I had an error in this date line: $form.serialize(). In your code there is a }); which I removed so the error was not because of this

  • @Lucas right, that was one of my questions in the previous comment. I guess whatever you want is $(this).serialize(). Corrected in the reply.

  • I updated the main post, it worked but I can’t catch the return. In the case of . php i put true Return when it succeeds and false Return when it gives error @

  • @Lucas makes console.log(data); within the Success function, and console.log(result); inside the complete function. So you know what you receive. What appears in the console?

  • @Lucas makes console.log(data); within the Success function, and console.log(result); inside the complete function. So you know what you receive. What appears in the console?

Browser other questions tagged

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