简体   繁体   中英

Unable to get drop-down box to auto-populate AJAX PHP

I am trying to set up a form where clients can enter their shipping information for items they order from my site. I ship to the US and Canada, so I would like to have them select either "United States" or "Canada" from the country drop-down box, and then use ajax and php to create a select option list of states/provinces for the selected country without reloading the page.

My Code so far:

<?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';

?>

My process-request.php file:

<?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>";
    }
}
?>

My header.php and footer.php just contain formatting divs for the page layout, as well as links for css and the javascript href " http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js ".

I have no idea what is missing, or what I am doing wrong, as this is my first time dealing with javascript, and I have tried several tutorials on how to do this, all of which did not work when I change the selection.

If I change the selection for country, nothing updates at all for the state/province section, #response.

UPDATE: I was able to get everything working with the following code snippets:

<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('./');
}
?>

I converted all the states / provinces, and the countries to entries in my MySQL database, and with the queries above, it now works. I also had to manually download the jquery.min.js file to my js folder to get it to actually work, as it did not want to read the remote file.

Problem is probably with your AJAX call. You specify:

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

You are sending back HTML from your PHP page. Try that. The /echo/html/ and other edits are for JSFiddle. Just put back you old values for that, change the dataType and take out the 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>");
}

Give this a try.

Do a return json_encode($countryArr[$country]) in your php script. Remove the echo part.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM