user9689724
user9689724

Reputation:

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.

Upvotes: 0

Views: 67

Answers (2)

david890ch
david890ch

Reputation: 197

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>

Upvotes: 0

Yousef_Shamshoum
Yousef_Shamshoum

Reputation: 822

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';
     });
})

Upvotes: 1

Related Questions