Create select with html using ajax

2

I try to create a select in HTML5 by bringing the data from a .js file that has a $.ajax that calls a URL that has data in JSON.

But always throws for error: function(data) and I do not know why, the url is fine for what I imagine will be the code, I'll let you see if someone can help me.

index.html

<!DOCTYPE html>
<html>
<head>


    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="funciones_app.js"></script> 
</head>
<body onload="getData()">

<p>Sessions: 
<select id="Select"></select>


</body>
</html> 

functions_app.js

function getData(){
	    $.ajax({
	    	type: "GET",
	    	url: 'http://.../json_tipo_productos.php', 
	    	async: false,
	    	dataType: "json",
	    	success: function(data){
	    		alert("pepe");
	    		$.each(data,function(key, registro) {
	    			var id = "";
	    		    var nombre = "";
	    		    
						$.each(registro, function(key, value) {
							//alert(campo + ": " + valor);
							if (key == "id") { id = value; }
							if (key == "nombre") { nombre = value; }
														
						});
                 }); 
			$("#select").append('<option value='+id+'>'+nombre+'</option>');		 
	    	},
	    	error: function(data) {
	    		alert('error');
	    	}
	    });
}

The Json has this format:

[{"id":"6","nombre":"FLORISTERIA"},{"id":"8","nombre":"JOYERIA"}

I try to create the select in html as you see but it always appears empty.

    
asked by akenateb 15.11.2016 в 14:09
source

2 answers

2
  

Your code had the following errors:

     
  • $("#select").append('<option value='+id+'>'+nombre+'</option>'); , is out of the first $.each
  •   
  • The id of <select> starts with capital, that is, you should type $("#Select") .
  •   
  • async: false, is deprecated, do not use it.
  •   

    Try this:

    function getData(){
      $.ajax({
        type: "GET",
        url: 'http://../json_tipo_productos.php', 
        dataType: "json",
        success: function(data){
          $.each(data,function(key, registro) {
            $("#Select").append('<option value='+registro.id+'>'+registro.nombre+'</option>');
          });        
        },
        error: function(data) {
          alert('error');
        }
      });
    }
    

    Note : I do not leave a functional snippet because your server does not support CORS

        
    answered by 15.11.2016 / 14:23
    source
    0

    Good as a suggestion the order of your <script>

    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="funciones_app.js"></script> 
    

    Second, your <select> id is Select and not select and third, you are doing each more

    $.each(data,function(key, registro) {
        $("#Select").append('<option value='+registro.id+'>'+registro.nombre+'</option>');                                          
    }); 
    
        
    answered by 15.11.2016 в 14:22