-2

I am trying to submit forms through jQuery. If I submit my form normally(without jquery) I am able to get submit button in POST array PHP like this (Array ( [name] => dfgd [submit1] => Submit )).But if I submit my form using jquery .submit() I am getting only the input values,I am not able to get submit button in POST array PHP.

<form action="valu.php" id='form' method='POST'>
    <input type="text" name="name" id="name">
    <input type="submit" value="Submit" name='submit1'>
</form>

$(document).ready(function(){
        $('#form').submit(function(e){
            e.preventDefault();
            if($('#name').val() !== ''){
                e.currentTarget.submit();
            }
        })
    })

If I print POST array values using print_r($_POST) I am getting only

Array ( [name] => fgd )

I am not getting submit value in array.

Then how do I check in my validation like if(isset($_POST['submit'])).

Vijay
  • 116
  • 1
  • 7
  • You should not expect to get the submit button value. This looks like an [XY problem](http://xyproblem.info/) or at least there's something a bit off with your code. Why do you need to check if `submit1` is set? You can just check for `$_POST['name']` . This is usually a side-effect of trying to use the same file to do different things which violates the [single responsibility principle](https://en.wikipedia.org/wiki/Single-responsibility_principle) – apokryfos Jun 18 '20 at 08:28
  • So,if there are 30 inputs,then I may need to check each and every input whether it has been set.Do I need to check like that or is there any better way. – Vijay Jun 18 '20 at 08:36
  • The better way is my answer below. Don't check for the contents, check for the method of the submitted form. In your case it's POST. – mixable Jun 18 '20 at 08:42
  • Submit to a page that is only responsible to handle the submission of this form. That way you can validate the values as needed. If you have 30 inputs all of them need validation even you do have a single submit button, because you shouldn't trust user data . – apokryfos Jun 18 '20 at 08:43

1 Answers1

1

Jquery does not send the submit value, because nobody 'clicked' on the submit button. You can check for the POST request in php (as mentioned in this post) by using:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

If there are multiple forms on your page, you can add a hidden input and in addition check for it's value.

mixable
  • 1,068
  • 2
  • 12
  • 42