Trying to pass variable from $.post to php

I have one big file (for right now) that is supposed to:

The problem is, the variable never seems to reach the php code.

Can anyone tell me what I'm doing wrong, please?

My code:

(all on one page)

    <script type="text/javascript">
        $(function() {
        $("select").change(function () {
              var str = "";
        $("select option:selected").each(function () {
     str += $(this).text() + " ";
        });   
        $.post("index.php", { zip: str}, function(data){
        $('result').text(str); }, "json" );

    });//end select
    });//end function
    </script>

    <?php include_once ('../cons.php'); ?>
    <?php 
    if (isset($_POST['zip'])){
    $value = $_POST['zip'];   
    }else{
    $value = "nada";
    }
    echo $value;

    //I only get "nada"
    ?>
</head>

<body>

<div id="body">
<form id="findzip"><!-- jQuery will handle the form -->
<select name="zip">
<option value="">Find your zip code</option>
    <?php //use php to pull the zip codes from the database
    $mysqli_zip = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    if (mysqli_connect_errno()) {
            printf("Connect failed: %s", mysqli_connect_error());
            exit();
    }
    $q_zip = "select distinct(zip) from mc m group by zip";
    $r_zip = $mysqli_zip->query($q_zip);
    if ((!$r_zip) || ($r_zip == NULL)) {
            echo "no results ";
    }
    while($row_zip = $r_zip->fetch_array(MYSQLI_BOTH)) {
        echo "<option value='". addslashes($row_zip['zip']) . "'>" . addslashes($row_zip['zip']) . "</option>;\n";
    }//end while

    ?>
</select>
</form>
<!-- here's where the results go -->
<result></result>
<br/>
</div>
</body>
</html>

Upvotes: 2

Views: 140

Answers (2)

Patrick at CloudBudgie
Patrick at CloudBudgie

Reputation: 785

Your script as written is echoing out a value like "12345". But your $.post is expecting it to be type json. When I removed the json type it worked perfectly for me.

Upvotes: 2

user542603
user542603

Reputation:

Try putting an ID on it, like so:

<select name="zip" id="zip">

Then getting the value from it like so:

$("#zip").val();

Upvotes: 0

Related Questions