简体   繁体   中英

Ajax send my form when it's being submitted

I am working on a little project where I have an ajax call that should submit my form without refreshing the page (or redirect me to another page), the problem I however stumble upon is: The ajax function doesn't respond when I click on submit.

The ajax code looks a bit odd (for example the }); in the eBlock call, but that is because it contains code in that part aswell... but not code that would be usefull for this post I think.

my ajax code:

function saveExercise() {
$('.eBlock').each(function (i, contents) {
    //lots of code here
});

$.ajax({
    url: 'saveJson.php',
    type: 'POST',
    data: eBlock,
    dataType: 'json',
}).done(function (response) {

});
}

my form:

<form  id='my_form' class="container-fluid" action="" method="POST" required>
   <button id='resetInputs' type='button' onclick='getResetInputs()' class='btn btn-danger fa fa-refresh fa-2x resetInputs'></button>
   <button type='submit' id='saveBtn' class='btn btn-info fa fa-download fa-2x saveBtn' required name="submit" onclick="saveExercise()"></button>
</form>

not sure if this is any info you could use, but the ajax call is in a javascript file.

EDIT: Yes, I have been researching preventdefault(); I even looked for the same problem and found Form not submitting with AJAX this post related to the same problem I have.

Further changes have been: took out the window.location part. kept the .done however in case needed.

You can use jquery to listen to the submit event of your form element and then run the ajax request like this:

$("#my_form").submit(function(e){
     $.ajax({
         url: 'saveJson.php',
         type: 'POST',
         data: eBlock,
         dataType: 'json',
     }).done(function (response) {
        window.location = 'index.php';
     });
})

Do like this: JS code:

    $('#my_form').submit(function(event){
        event.preventDefault();

        var data = yourFunctionToGetTheData();

        $.ajax({
            url: url,
            type: "POST",
            dataType: 'json’,
            data: data,
            success: function(result){
            }
        });
    });

HTML code:

  <form  id='my_form' class="container-fluid" action="" method="post" required>
       <button id='resetInputs' type='button' onclick='getResetInputs()' class='btn btn-danger fa fa-refresh fa-2x resetInputs'></button>
       <input type='submit' class='btn btn-info fa fa-download fa-2x saveBtn' required name="submit"></button>
  </form>

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