Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax success response and select option append

Tags:

jquery

ajax

php

I am trying to make an ajax call to obtain the list of countries from my DB. The following are parts of the code:

country.php:

while ($country = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $country['country'];
   }
echo json_encode(array("response"=>$data));
}    

I am getting following response as:

{"response":["Afghanistan","Albania","Algeria","American-Samoa","Andorra","Angola"......

Ajax code:

//country select
$( "#country" ).focus(function() {
$.ajax({
url: 'country.php',
dataType: 'json',
contentType: 'application/json',
success: function(data) {
//console.log(data);
var formoption = "";
$.each(data, function(v)
{
var val = data[v];
formoption += "<option value='"+val+"'>"+val+"</option>";
});

$('#countries').append(formoption);
      }
   });
});

and in the form:

<select id="country" name="country" class="form_input required">
<div id="countries"></div>
</select>

somehow it is not working and i am unable to find the reason. Please note that i am a JavaScript newbie. I am using it as part of Framework7 code.

Expecting help from experts.

like image 876
Pamela Avatar asked Mar 25 '18 07:03

Pamela


People also ask

How fetch data from database in Dropdownlist in Ajax?

First, Make dropdown in you HTML and create an Ajax method and pass the dropdown selected value into it. Then keep this data in your PHP sides and execute your SQL query and show the result on your HTML page. Now you could execute your SQL the $id variable. Save this answer.


1 Answers

Use $('#countries').append(formoption);

and remove div tag inside select tag & change select id to countries, use below html

<select id="countries" name="countries" class="form_input required">
</select>

you were wrapping options in div tag so thats not proper html. options should directly be appended to select tag.

Refer below sample code

$(function() {
  var resultFromAjax = {response: ["Afghanistan", "Albania", "Algeria", "American-Samoa", "Andorra", "Angola"]}
  var data = resultFromAjax.response

  var formoption = "";
  $.each(data, function(v) {
    var val = data[v]
    formoption += "<option value='" + val + "'>" + val + "</option>";
  });
  $('#countries').html(formoption);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="countries" name="country" class="form_input required">
</select>
like image 69
vinayakj Avatar answered Sep 23 '22 02:09

vinayakj