Undefined index error in php using ajax

2019-09-04 08:18发布

问题:

<form role="form" method="post" action="test.php">
<label for="contact">Mobile No:</label><br>
      <input type="tel" class="form-control" name="contact" title="Mobile number should not contain alphabets. Maxlength 10" placeholder="Enter your phone no" maxlength="15" required  id='contact_no'>
      <br><br>
<button type="submit" class="btn btn-success" name="submit" id="submit">Submit</button>
    <button type="reset" class="btn btn-default" id='reset'>Reset</button>
  </form>

Ajax and Javascript Code
script type="text/javascript">
    $(document).ready(function(){
        $("#submit").click(function(){
        var dialcode = $(".country-list .active").data().dialCode;
        var contact = $("#contact_no").val().replace(" ","");
        var countrycode = $('.country-list .active').data().countryCode;
            var cn;
            var cc;
            var dc;
            $.ajax({
            url: "test.php",
            type: "POST",
            data: {'cc' : contact},
            success: function(data) 
            {
                alert("success"); 
              }  
            });
        });
    });
    </script>

The variables show the values if displayed by alert message but are not passed on to the test.php page. It shows undefined index error at the following statement

test.php is as follows

<?php

    if(isset($_POST['submit'])){

         $contact = $_POST['cc'];       //it shows the error here

    }
    echo  $contact;

I had referred to many websites which show the same thing. It dosent work for me. I think the syntz of ajax is correct and have tried all possibilities but still dosent work. Please help

回答1:

You're posting {cc: contact}, but you're checking for $_POST['submit'] which isn't being sent. The callback also doesn't stop the event, so you might want to return false (stops default and propagation). Something like this should do the trick:

$('#submit').on('click', function()
{
    //do stuff
    $.ajax({
        data: {cc: contact},
        method: 'post',
        success: function()
        {
            //handle response here
        }
    });
    return false;
});

Then, in PHP:

if (isset($_POST['cc']))
{
    //ajax request with cc data
}

Also not that this:

$("#contact_no").val().replace(" ","");

Will only replace 1 space, not all of them, for that you'll need to use a regex with a g (for global) flag:

$("#contact_no").val().replace(/\s+/g,"");


回答2:

You are using ajax to form submit

and you use $_POST['submit'] to check it would be $_POST['cc']

test.php

<?php
    if(isset($_POST['cc'])){// change submit to cc
      $contact = $_POST['cc'];//it shows the error here
    }
echo  $contact;