无法获得下拉框以自动填充AJAX PHP

时间:2019-06-30 02:19:29

标签: php ajax

我正在尝试建立一个表单,客户可以在该表单中输入从我的网站订购的商品的运送信息。我运送到美国和加拿大,因此我希望他们从国家/地区下拉框中选择“美国”或“加拿大”,然后使用ajax和php创建州/省的选择选项列表选择的国家/地区,而无需重新加载页面。

到目前为止,我的代码:

<?php

require_once 'includes/functions.php';

include_once 'header.php';

?>

<h1>Shipping Information</h1>

<p>Please use the form below to add a shipping address to your account.  You MUST have a shipping address on file to be able to access our store.  For a list of accepted state/provice and country codes, please visit <a href="https://www.ups.com/worldshiphelp/WS14/ENU/AppHelp/Codes/State_Province_Codes.htm" target="_blank">here</a>.  We only ship to the United States and Canada at this time.</p>

<div id="form">
<form action="" method="post">
<table cellspacing="2" cellpadding="2" width="550">
    <tr>
        <th colspan="2">Add Shipping Address</th>
    </tr>

    <?php
    if($error)
    {
        echo '<tr><td colspan="2">';
        echo $error;
        echo '</td></tr>';
    }
    ?>

    <tr>
        <td align="right"><label for="fname">First Name</label></td>
        <td><input type="text" name="fname" /></td>
    </tr>

    <tr>
        <td align="right"><label for="lname">Last Name</label></td>
        <td><input type="text" name="lname" /></td>
    </tr>

    <tr>
        <td align="right"><label for="addr1">Address</label></td>
        <td><input type="text" name="addr1" /></td>
    </tr>

    <tr>
        <td align="right"><label for="addr2">Apt/Suite/Unit</label></td>
        <td><input type="text" name="addr2" /></td>
    </tr>

    <tr>
        <td align="right"><label for="city">City</label></td>
        <td><input type="text" name="city" /></td>
    </tr>

    <tr>
        <td align="right"><label for="cc">Country</label></td>
        <td>
            <select name="cc" id="cc">
                <option value="">Select One...</option>
                <option value="US">United States</option>
                <option value="CA">Canada</option>
            </select>
        </td>
    </tr>

    <tr>
        <td align="right"><label for="sp">State/Province</label></td>
        <td id="response"></td>
    </tr>

    <tr>
        <td align="right"><label for="pcode">Postal Code</label></td>
        <td><input type="text" name="pcode" /></td>
    </tr>

    <tr>
        <td align="right"><label for="active">Set Default</label></td>
        <td><input type="checkbox" name="active" /></td>
    </tr>

    <tr>
        <td colspan="2"><hr /></td>
    </tr>

    <tr>
        <td colspan="2" align="center"><input type="submit" name="submit" value="Add Address" /></td>
    </tr>
</table>
</form>
</div>

<script>
$("#cc").on("change",function(){
    var selected = $(this).val();
    $.ajax({
        type:POST,
        url:"process-request.php",
        data: { cc : selected },
        contentType:"application/json; charset-utf-8",
        dataType:"json",
        async:false,
        success: ccSuccess,
        error: AjaxFailed
    });
});

function ccSuccess(result)
{
    $("#response").html(result);
}

function AjaxFailed(result)
{
    $("#response").html("<p class='error'>Failed to Load State/Province Codes</p>");
}
</script>

<?php

include_once 'footer.php';

?>

我的process-request.php文件:

<?php
// process-request.php

if(isset($_POST['cc']))
{
    $country = $_POST['cc'];
    $countryArr = array(
        "US" => array(
        'AL',
        'AK',
        'AZ',
        'AR',
        'CA',
        'CO',
        'CT',
        'DE',
        'DC',
        'FL',
        'GA',
        'HI',
        'ID',
        'IL',
        'IN',
        'IA',
        'KS',
        'KY',
        'LA',
        'ME',
        'MD',
        'MA',
        'MI',
        'MN',
        'MS',
        'MO',
        'MT',
        'NE',
        'NV',
        'NH',
        'NJ',
        'NM',
        'NY',
        'NC',
        'ND',
        'OH',
        'OK',
        'OR',
        'PA',
        'RI',
        'SC',
        'SD',
        'TN',
        'TX',
        'UT',
        'VT',
        'VA',
        'WA',
        'WV',
        'WI',
        'WY'
        ),
        "CA" => array(
        'AB',
        'BC',
        'MB',
        'NB',
        'NL',
        'NT',
        'NS',
        'NU',
        'ON',
        'PE',
        'QC',
        'SK',
        'YT'
        )
    );
    if($country !== 'Select One...')
    {
        echo "<select name='sp'>";
        foreach($countryArr[$country] as $value)
        {
            echo "<option value='".$value."'>".$value."</option>";
        }
        echo "</select>";
    }
}
?>

我的header.php和footer.php仅包含页面布局的格式div,以及CSS和javascript href“ http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”的链接。

我不知道缺少了什么,或者我做错了什么,因为这是我第一次使用javascript,并且我尝试了一些有关如何执行此操作的教程,但是当我更改javascript时,所有这些都无法正常工作选择。

如果更改国家/地区的选择,则州/省#response的任何内容都不会更新。

更新: 我可以使用以下代码段使一切正常工作:

<div id="form">
<form action="" method="post">
<table cellspacing="2" cellpadding="2" width="550">
    <tr>
        <th colspan="2">Add Shipping Address</th>
    </tr>

    <?php
    if($error)
    {
        echo '<tr><td colspan="2">';
        echo $error;
        echo '</td></tr>';
    }
    ?>

    <tr>
        <td align="right"><label for="fname">First Name</label></td>
        <td><input type="text" name="fname" /></td>
    </tr>

    <tr>
        <td align="right"><label for="lname">Last Name</label></td>
        <td><input type="text" name="lname" /></td>
    </tr>

    <tr>
        <td align="right"><label for="addr1">Address</label></td>
        <td><input type="text" name="addr1" /></td>
    </tr>

    <tr>
        <td align="right"><label for="addr2">Apt/Suite/Unit</label></td>
        <td><input type="text" name="addr2" /></td>
    </tr>

    <tr>
        <td align="right"><label for="city">City</label></td>
        <td><input type="text" name="city" /></td>
    </tr>

    <tr>
        <td align="right"><label for="cc">Country</label></td>
        <td>
            <select name="cc" id="country">
                <option value="">Select One...</option>
                <?php
                $sql = $db->query('SELECT * FROM country');
                if(is_object($sql) && $sql->num_rows > 0)
                {
                    while($row = $sql->fetch_array())
                    {
                        echo '<option value="'.$row['id'].'">'.$row['cn'].'</option>';
                    }
                }
                ?>
            </select>
        </td>
    </tr>

    <tr>
        <td align="right"><label for="sp">State/Province</label></td>
        <td><select name="sp" id="state"><option>Select One...</option></select></td>
    </tr>

    <tr>
        <td align="right"><label for="pcode">Postal Code</label></td>
        <td><input type="text" name="pcode" /></td>
    </tr>

    <tr>
        <td align="right"><label for="active">Set Default</label></td>
        <td><input type="checkbox" name="active" /></td>
    </tr>

    <tr>
        <td colspan="2"><hr /></td>
    </tr>

    <tr>
        <td colspan="2" align="center"><input type="submit" name="submit" value="Add Address" /></td>
    </tr>
</table>
</form>
</div>

<script type="text/javascript">
$(document).ready(function(){
    $("#country").change(function(){
        var country_id = $(this).val();
        if(country_id != ""){
            $.ajax({
                url:"get-states.php",
                data: {c_id:country_id},
                type:"POST",
                success:function(response){
                    var resp = $.trim(response);
                    $("#state").html(resp);
                }
            });
        } else {
            $("#state").html("<option value=''>Select One...</option>");
        }
    });
});
</script>

<?php
require_once 'includes/functions.php';

if(isset($_POST['c_id']))
{
    $sql = $db->query('SELECT * FROM states WHERE ccid = "'.$_POST['c_id'].'"');
    if(is_object($sql) && $sql->num_rows > 0)
    {
        echo '<option value="">Select One...</option>';
        while($row = $sql->fetch_array())
        {
            echo '<option value="'.$row['id'].'">'.$row['sname'].'</option>';
        }
    }
    else
    {
        echo '<option value="">ERROR</option>';
    }
}
else
{
    redirect('./');
}
?>

我将所有州/省和国家/地区都转换为我的MySQL数据库中的条目,并且通过上面的查询,现在可以使用了。我还必须手动将jquery.min.js文件下载到我的js文件夹中,以使其真正起作用,因为它不想读取远程文件。

3 个答案:

答案 0 :(得分:0)

您的AJAX调用可能存在问题。您指定:

    contentType:"application/json; charset-utf-8",
    dataType:"json",

您正在从PHP页面发回HTML。试试看/ echo / html /和其他编辑用于JSFiddle。只需为此放回旧值,更改dataType并取出contentType。

$("#cc").on("change",function(){
    var selected = $(this).val();
    $.ajax({
        type:"POST",
        url:"process-request.php",
        data: { cc : selected },
        dataType:"html",
        async:false,
        success: ccSuccess,
        error: AjaxFailed
    });
});

function ccSuccess(result)
{       alert(result);
    $("#response").html(result);
}

function AjaxFailed(result)
{
    $("#response").html("<p class='error'>Failed to Load State/Province Codes</p>");
}

答案 1 :(得分:0)

尝试一下。

在您的php脚本中执行return json_encode($countryArr[$country])。删除回声部分。

function ccSuccess(result)
{       
 alert(result);

var country = JSON.parse(result);
var html = "";
   html += "<select name='sp'>";
    for(var i =0; i < country.length; i++)
    {
        html +="<option value='"+ country[i] +"'>"+ country[i] +"</option>";
    }
    html += "</select>";
    $("#response").html(html);
}

答案 2 :(得分:0)

dataType:"json", 您需要删除此行,因为您不是从process-request.php返回json,它只是返回html代码。