简体   繁体   中英

Why is code in AJAX success call is not working?

I have an AJAX script to insert data from a form to MySQL database. This is the AJAX.

<!-- SUBMIT FORM VIA AJAX -->
$("#f_product").on('submit',function(event){ 
    event.preventDefault();

    data = $(this).serialize();

    $.ajax({
    type: "POST",
    url: "<?php echo site_url('con_product/ins_product'); ?>",
    data: data
    }).success(function() {
        alert("Products list is ready to be printed");
        window.open("<?php echo site_url('con_product/print_product'); ?>","_blank");
        window.open("<?php echo site_url('con_product/form_product'); ?>","_self");
    });
});
<!-- END SUBMIT FORM VIA AJAX -->

The AJAX script successfully insert data from the form to database. But somehow, the script on success is not working. Why?

The behavior of this AJAX are:

  • Insert data to database - success
  • Show alert
  • Open new page for print purpose.
  • Refresh current page to a new form.

The success is the name of the callback function and not the promise .

You should use:

$.ajax({
    type: "POST",
    url: "<?php echo site_url('con_product/ins_product'); ?>",
    data: data,
    success: function() {
        alert("Products list is ready to be printed");
        window.open("<?php echo site_url('con_product/print_product'); ?>","_blank");
        window.open("<?php echo site_url('con_product/form_product'); ?>","_self");
    }
});

Or the done promise:

$.ajax({
    type: "POST",
    url: "<?php echo site_url('con_product/ins_product'); ?>",
    data: data
}).done(function() {
    alert("Products list is ready to be printed");
    window.open("<?php echo site_url('con_product/print_product'); ?>","_blank");
    window.open("<?php echo site_url('con_product/form_product'); ?>","_self");
});

I'm not sure if there is .success function. But you can try this:

$.ajax({
    type: "POST",
    url: "<?php echo site_url('con_product/ins_product'); ?>",
    data: data,
    success: function(){
        alert("Products list is ready to be printed");
        window.open("<?php echo site_url('con_product/print_product'); ?>","_blank");
        window.open("<?php echo site_url('con_product/form_product'); ?>","_self");
    }
});

According to http://api.jquery.com/jquery.ajax/

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

What if your replace success with done ?

Otherwise, success should be a property of the object you throw into $.ajax({...}) with the anonymous function as its value.

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