Nijn
Nijn

Reputation: 400

Javascript form submit doesn't submit properly

I have this very simple form using Sweet Alert and for some reason can't get it to work. When I click on the link it triggers the alert and when the alert is confirmed it reloads the page because it submits the form.

But for some reason when $_POST['delete_alert'] is undefined.

My code to trigger the alert:

<a id="sa-warning">Delete</a>

My form:

<form id="form" action="index.php" method="POST">
    <button type="submit" name="delete_alert" value="delete">Delete</button>
</form>

And my Javascript:

$('#sa-warning').click(function() {
  swal({
    title: "Are you sure?",
    text: "You will not be able to recover this alert.",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!",
    closeOnConfirm: false
  }, function() {
    document.forms["form"].submit();
  });
});

I'm testing wheter the form has been submitted properly using this PHP code which is located on index.php:

<?php 
if(isset($_POST['delete_alert'])) { 
    echo "form is submitted correctly"; 
} else { 
    echo "something is wrong"; 
} 
?>

Upvotes: 1

Views: 619

Answers (3)

Nijn
Nijn

Reputation: 400

Just a slight change in my form was needed. The submit button is not clicked when the form is submitted via Javascript. Thus the value of 'delete_alert' is never set.

Removing the submit button and adding an input field resolved the problem.

The correct form:

<form id="form" action="index.php" method="POST">
    <input type="hidden" name="delete_alert' value="delete" />
</form>

Thanks to Barmar for pointing this out.

Upvotes: 0

Rahman
Rahman

Reputation: 1061

maybe is work : http://rachmanzz.github.io/AlertlightJS

$('#sa-warning').click(function(){
    alertlightJS.$swalPost({     // $swalGet for GET Method
        title : "Are you sure?",
        text  : "You will not be able to recover this alert.",
        type  : "warning",
        confirmText:"Yes, delete it!",
        cancelText:"No!"
    },{
        url : "index.php",
        input   : {
            delete_alert:'delete'
        }
    },function(isConfirm,data,swal){
        if(isConfirm){
                swal(['receive',data['data']]);
        }else{
            swal(['cancel','thanks']);
        }
    });
});

Upvotes: 0

JTC
JTC

Reputation: 3464

I think the problem is in document.forms["form"].submit();

HTML forms send the submit name=value only if button is clicked. In this case it is not.

So i think you should use click instead of submit, but in your case it wont work, because the click will be catched by your javascript function.

So this is why the best solution si to use input

Upvotes: 1

Related Questions