guradio guradio - 4 months ago 29
Ajax Question

Run ajax request on document.ready jquery

Ajax

$(document).ready(function() {
$.ajax({
type: 'POST',
url: '../include/ListOfCities.php',
dataType: "json",
data: {
Country: "Japan"
},
success: function(data) {
console.log(data);
var city = ('#city');
$(city).empty();
for (var i = 0; i < data.length; i++) {
$(city).append('<option id=' + data[i].sysid + ' value=' + data[i].city_name + '>' + data[i].city_name + '</option>');

}
}

});
});


php

$country = mysql_real_escape_string($_POST['Country']);
$stmt = $dbh->prepare("SELECT * FROM city_tbl WHERE country_name = ? ");
$stmt->bindValue(1, $country, PDO::PARAM_STR);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
while ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$citylist[] = array('sysid' => $selected_row['sys_id'], 'code' => $selected_row['city_code'], 'name' => $selected_row['city_name'], 'parentid' => $selected_row['parent_id']);
}
$input = array_map("unserialize", array_unique(array_map("serialize", $citylist)));
echo json_encode($input, JSON_UNESCAPED_UNICODE);
}
}


I want to display the all the city in japan in a select option menu i want to load the cities when the page loads i am sending the ajax request like above but i don't get any result the ajax above works fine when i use it on button. Is sending ajax request different from on button click and on document ready..Any suggestion how to make ajax request on document ready is appreciated

Answer

Just try setting async:false in your ajax request. So the final code will be

$(document).ready(function() {
    $.ajax({
        type: 'POST',
        url: '../include/ListOfCities.php',
        dataType: "json",
        async:false,
        data: {
            Country: "Japan"
        },
        success: function(data) {
            console.log(data);
            var city = ('#city');
            $(city).empty();
            for (var i = 0; i < data.length; i++) {
                $(city).append('<option id=' + data[i].sysid + ' value=' + data[i].city_name + '>' + data[i].city_name + '</option>');

            }
        }

    });
});