简体   繁体   中英

Form not using Ajax, posting directly to PHP

I am posting a form to a php file using ajax but for some reason which I can't figure out, it is not using ajax but directly posting to php.

My form:

  <form id="editform" name="editform" action="ajaxeditform.php" method="post">
      <input type="hidden" name="aid" id="aid" readonly class="form-control col-md-7 col-xs-12"/>
      <input type="text" name="number" id="tailnumber" readonly class="form-control col-md-7 col-xs-12"/>
      <input type="text" name="type" id="type" class="form-control col-md-7 col-xs-12" placeholder="e.g. C172" />
      <input type="text" name="colormarkings" id="colormarkings" class="form-control col-md-7 col-xs-12" />
      <button type="submit" class="btn btn-success">Update info</button></div>
  </form>

My jquery:

 $('#editform').on('submit', function(e){
    e.preventDefault();

    $.ajax({
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serialize(),
        dataType: 'json',
        cache: false,
    })
    .success(function(response) {
        // remove all errors
        $('input').removeClass('error').next('.errormessage').html('');

        if(!response.errors && response.result) {

                new PNotify({
                            title: 'Success',
                            text: 'Info updated successfully',
                            type: 'success'
                        });

        } else {

            $.each(response.errors, function( index, value) {
                // add error classes
                $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
            });

        }
    });
});

Changes:-

Form opening tag is not proper , change like below:-

<form id="editform" name="editform" action="ajaxeditform.php" method="post">

try to change your jquery code first line like below:-

$('Form#editform').on('submit', function(e){ OR $('.btn-success').click(function(e){

Add jquery library also (check that it is added or not?). for example add this code before jQuery code:-

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>

add $(document).ready(function(){ in your code.like below:-

$(document).ready(function(e){
  ........ //your code
});

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