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 whole city in Japan in the selection options menu. I want to load cities when the page loads. I am sending an ajax request as above, but I am not getting any result. The ajax above works fine when I use it on a button. Sends an ajax request other than a button click and a finished document. Any suggestion on how to make an ajax request on a finished document is appreciated

+5
source share
1 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>'); } } }); }); 
+5
source

Source: https://habr.com/ru/post/1212852/


All Articles