Himani
Himani

Reputation: 265

select value not getting changed using jQuery and Ajax

I have two Dropdowns City and Zipcode in my form. When a Zipcode is selected by the user, I want to change the City Dropdown to the appropriate City w.r.t Zipcode. I am trying to accomplish this using Ajax.

jQuery Code:

$(document).on('change','#zip_id', function(e){
e.preventDefault(); 
var zipID = jQuery(this).val();
if(zipID){
jQuery.ajax({
    url: ajaxschoolajax.ajaxurl,
    data: {'zip_id': zipID, 'action':'cityOptions_Process'},
    type: 'POST',
    success: function(data){
        jQuery('#temp').html(data); 
},

error: function (exception) {
    console.log("Error");
            console.log(exception);
        }
});

PHP Function

    function cityOptions_Process() {
    if(isset($_POST["zip_id"]) && !empty($_POST["zip_id"])){
        $selectedZip = $_POST["zip_id"];
        global $wpdb;

        $sql = "SELECT `city_id` FROM `wp_gj73yj2g8h_hills_zipcodes` WHERE zip_id = '$selectedZip'";
        $data = $wpdb->get_row($sql);
        $output = $data->city_id;
        echo $output;
        die();
}
}

add_action( 'wp_ajax_nopriv_cityOptions_Process', 'cityOptions_Process' );
add_action( 'wp_ajax_cityOptions_Process', 'cityOptions_Process' );

Showing Inappropriate Data

Inappropriate responseText Ajax data showing in Ajax Error function

Upvotes: 0

Views: 125

Answers (2)

shahzeb akram
shahzeb akram

Reputation: 926

First of all check the value of city may be your query is not returning the valid value. After that you can simply use this code to set the drop down value.

 $('#city_id').val(city);

Also remove single quotes from data

 data: {zip_id: zipID, action:'cityOptions_Process'},

Upvotes: 1

xhulio
xhulio

Reputation: 1103

Do not echo the $cityId, return it.

function cityOptions_Process() {
if(isset($_POST["zip_id"]) && !empty($_POST["zip_id"])){
    $selectedZip = $_POST["zip_id"];
    global $wpdb;
    $cityId = $wpdb->get_results($wpdb_prepare("select city_id from `wp_gj73yj2g8h_hills_zipcodes` WHERE zip_id=%d",$selectedZip));
    return $cityId;

}
}

also remove the select in $("#city_id select").val('city');

Upvotes: 0

Related Questions