使用Ajax的PHP中的未定义索引错误 [英] Undefined index error in php using ajax

查看:81
本文介绍了使用Ajax的PHP中的未定义索引错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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页面.在以下语句中显示未定义的索引错误

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

<?php

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

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

    }
    echo  $contact;

我曾经提到过许多展示相同内容的网站.它为我工作.我认为ajax的语法是正确的,已经尝试了所有可能性,但仍然有很多工作要做.请帮助

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

推荐答案

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

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;
});

然后,在PHP中:

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

不是这样的:

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

将仅替换1个空格,而不是全部替换,因为您将需要使用带有g(用于全局)标志的正则表达式:

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,"");

这篇关于使用Ajax的PHP中的未定义索引错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆