Jack Maessen Jack Maessen - 3 months ago 9
PHP Question

how to differentiate between 2 input tags in a form

I am having an issue with 2 input tags in a form.
What i want to achieve is that when one certain input is choosen, an echo must be generated.

My form:

<form method="post" id="quickpoll">
......
<input class="quickpollsubmit" type="submit" name="quickpollsubmit" value="View">
<input class="quickpollsubmit" type="submit" name="quickpollsubmit" value="Vote">


The js:

$(document).on('submit', '#quickpoll', function()
{
var data = $(this).serialize();
$.ajax({

type : 'POST',
url : 'quickpoll_vote.php',
data : data,
success : function(data)
{
$("#quickpoll").fadeOut(500).hide(function()
{
$(".quickpollwrapper").fadeIn(500).show(function()
{
$(".quickpollwrapper").html(data);

});


});

}
});
return false;
});


quickpoll_vote.php:

if($_POST)
{
if($_POST['quickpollsubmit'] == 'View') {
echo 'you choose View';
}
}


The echo does not appear at all, whether i choose View input or Vote input.
The echo should only appear when i choose View input
What i am doing wrong?

Answer

citation of stephen nielsen :

"The serialize method will NEVER return a value from the submit button. It does not return the submit button in the post. You will do best to just use a hidden form field and adding a click event to the button"

To check this point, add a :

print_r($_POST);

in the begin of quickpoll_vote.php

You will see that the argument "quickpollsubmit" has no value, whatever button you click.

Here's a way of solving this.

 $(document).on('click', '.quickpollsubmit', function()
    {
    $('#quickpollsubmit').val($(this).val());
    var data = $("#quickpoll").serialize();
       
        $.ajax({

        type : 'POST',
        url  : 'quickpoll_vote.php',
        data : data,
        success :  function(data)
                   {                        
                        $("#quickpoll").fadeOut(500).hide(function()
                        {
                            $(".quickpollwrapper").fadeIn(500).show(function()
                            {
                                $(".quickpollwrapper").html(data);
    
                            });
    
    
                        });
    
                   }
        });
        return false;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" name="quickpollsubmit" id="quickpollsubmit" readonly>
<input class="quickpollsubmit" type="submit" value="View">
<input class="quickpollsubmit" type="submit" value="Vote">

I edited the code so it will be compatible with your PHP part, but this way some element are really bad named, sorry about this.

In your script, use a hidden input instead of the text one, here for demonstration.

Comments