php中使用ajax

时间:2015-06-04 11:17:10

标签: php jquery ajax forms

<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>

变量显示由警报消息显示的值,但不会传递给test.php页面。它在以下语句中显示未定义的索引错误

test.php 如下

<?php

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

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

    }
    echo  $contact;

我曾参考过很多展示相同内容的网站。它适合我。我认为ajax的合成是正确的,并尝试了所有的可能性,但仍然很有效。请帮忙

2 个答案:

答案 0 :(得分:1)

您发布了{cc: contact},但是您正在检查未发送的$_POST['submit']。回调也不会停止事件,因此您可能希望return false(停止默认和传播)。这样的事情可以解决问题:

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

然后,在PHP中:

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

也不是这个:

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

只会替换1个空格,而不是所有空格,因为您需要使用带有g(全局)标记的正则表达式:

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

答案 1 :(得分:0)

您正在使用ajaxform submit

并使用$_POST['submit']检查它是$_POST['cc']

test.php

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