简体   繁体   中英

Form not submitting on ajax request

So I'm comparing the value of the input field entered by the user to the value of the mysql DB (using an Ajax request to the checkAnswer.php file). The request itself works fine, it displays the correct "OK" or "WRONG" message, but then it does not submit the form if "OK". Should I put the.submit() somewhere else?

HTML code:

            <form id="answerInput" action="index" method="post">
              <div id="answer-warning"></div>
              <div><input id="answer-input" name="answer" type="text"></div>
              <input type="hidden" id="id" name="id" value="<?=$id?>">      
              <div><button type="submit" id="validate">Valider</button></div>
            </form>
        </div>

JS code

$("#validate").click(function(e){
    e.preventDefault(); 
    $.post(
        'includes/checkAnswer.php',
        {            
           answer : $('#answer-input').val(),
           id : $('#id').val()
        }, 
        function(data){ 
            if(data === '1'){ 
                 $("#answer-warning").html("OK");
                 $("#answerInput").submit();
             }
            else{
                 $("#answer-warning").html("WRONG");
             }         
        },
        'text'
     );
});

I think it is because you set your button type as submit . Why?

When you do $("#validate").click(function(e){ , you implicitly replace the default submit behavior of the form.

As you want to interfere in the middle of the process for extra stuff, I suggest you change the button type to button or simply remove the type attribute.

Then the $("#validate").click(function(e){ will alter behavior of click , not the submit of form.

<form id="answerInput" action="index" method="post">
    <div id="answer-warning"></div>
    <input id="answer-input" name="answer" type="text">
    <input type="hidden" id="id" name="id" value="<?=$id?>">      
    <button onlcick="validate()">Valider</button>
</form>

/******** JS ************/

function validate(){
var post = {};
    post['answer'] = $('#answer-input').val();
    post['id'] =  $('#id').val();
    $.ajax({
        url: 'includes/checkAnswer.php',
        type: 'POST',
        data: {data: post},
        success:function (data) {
            console.log('succsess');
        },
        error:function (jQXHR, textStatus, errorThrown) {
            console.log('failure');
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM