1

Before posting to this question i checked below links. How do I use two submit buttons, and differentiate between which one was used to submit the form?

Two submit buttons in one form

but i am still facing issue. Below are the codes. html code

<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
    <input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
    <input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>

Here is the php code on posting_bk.php

    if (isset($_POST['publish'])) {
        # Publish-button was clicked
array_push($res['errors'], 'Publish button');
    echo json_encode($res);
    }
    elseif (isset($_POST['save'])) {
      # Save-button was clicked
array_push($res['errors'], 'Save button.');
    echo json_encode($res);
    }

Issue is i am not getting any output. i was suppose to get test publish or test save.

i am planning to use ajax and below is the code i have written for ajax.

<script type="text/javascript">
    $('document').ready(function() {
        $("#posting").on("submit", function(e) {
            e.preventDefault;
            var btn = $('#publish');

            $.ajax({
                type: 'post',
                url: $('form#posting').attr('action'),
                cache: false,
                dataType: 'json',
                data: $('form#posting').serialize(),
                beforeSend: function() {
                    $("#validation-errors").hide().empty();
                },
                success: function(data) {
                    if (data.success == false) {
                        var arr = data.errors;
                        $.each(arr, function(index, value) {
                            if (value.length != 0) {
                                $("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');


                            }
                        });
                        $("#validation-errors").show();
                        btn.button('reset');
                    } else {
                        $("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto <a href="edit.php">Edit</a>. <div>');
                        $('#title').val('');

                    }
                },
                error: function(xhr, textStatus, thrownError) {
                    alert('Something went to wrong.Please Try again later...');

                    btn.button('reset');
                }
            });
            return false;
        });
    });
</script>

If i didn't use ajax then it is working fine. It seems like issue with Ajax

Community
  • 1
  • 1
Roxx
  • 3,738
  • 20
  • 92
  • 155

2 Answers2

2

You can't do it the way you're trying to do it because publish and save will both always be set no matter which button you click on.

You need to do it on the client side. Bind an event listener to each button and that listener will pass whatever "action" variable you want.

If you were using jQuery for example:

$('#publish').on('click', function(e){
   e.preventDefault();
   // Set some hidden form variable called action to a value of publish
   // submit form or make an ajax call.
});

$('#save').on('click', function(e){
   e.preventDefault();
   // Set some hidden form variable called action to a value of save
   // submit form or make an ajax call.
});

Now your PHP can check if $_POST['action'] == 'save'|'publish' and act accordingly.

Matt
  • 5,315
  • 1
  • 30
  • 57
  • If both the buttons are set then why there is no result? See OP has used `if elseif` so one condition must be satisfied if both are set. That's not case here. OP's code just works fine. – Mr. Engineer Feb 25 '16 at 05:07
  • @Mr.Engineer For a couple of reasons. 1. He's set the dataType to json and he's echoing out plain text. 2. He's not actually outputting anything in the data returned within his success callback. data.success will be undefined which is falsey. – Matt Feb 25 '16 at 05:16
  • I'm not talking about `ajax` which OP has edited. I'm talking about simple form submission without ajax. – Mr. Engineer Feb 25 '16 at 05:18
2

I will go with a click submit, take the id of the clicked button and pass it to the php :

$('#posting input[type="submit"]').on("click", function(e) {                
                e.preventDefault;
                var btn = $('#publish');
                var el = $(this).attr('id');
                $.ajax({
                    type: 'post',
                    url:$('form#posting').attr('action'),
                    cache: false,
                    dataType: 'json',
                    data: {data:$('form#posting').serialize(),action:el},
                    beforeSend: function() { 
                        $("#validation-errors").hide().empty(); 
                    },
                    success: function(data) {
                        if(data.success == false)
                            {
                                var arr = data.errors;
                                $.each(arr, function(index, value)
                                {
                                    if (value.length != 0)
                                    {
                                        $("#validation-errors").append('<div class="alert alert-danger"><strong>'+ value +'</strong><div>');


                                    }
                                });
                                $("#validation-errors").show(); 
                                btn.button('reset');                            
                            } else {
                                $("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto <a href="edit.php">Edit</a>. <div>');
                                $('#title').val('');

                            }
                    },
                    error: function(xhr, textStatus, thrownError) {
                        alert('Something went to wrong.Please Try again later...');

                        btn.button('reset');
                    }
                });             
                return false;
            });
        });

php:

    if ($_POST['action'] == 'publish') {
            # Publish-button was clicked
echo 'test publish';
        }
        elseif ($_POST['action'] == 'save') {
            # Save-button was clicked
echo 'test save';
    }
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
  • I am getting E_NOTICE : type 8 -- Undefined index: action error. – Roxx Feb 25 '16 at 11:04
  • var_dump the value of $_POST – madalinivascu Feb 25 '16 at 11:11
  • your code is working fine but i found issue with post. in firebug i found under post two values action and data. In action i found publish/save but in data it is showing all of the form data. when i try to get the post form data it is comes empty in php file. I am not sure what i am doing wrong. – Roxx Feb 25 '16 at 20:27
  • you should be able to get the values with `$_POST['data']['fieldname']` – madalinivascu Feb 26 '16 at 05:03
  • 1
    Thanks for your answer. i was waiting for you from last 9 hours – Roxx Feb 26 '16 at 05:07