-
-
Save placecodex/9b80a01667a65e242bf758b4492a70f5 to your computer and use it in GitHub Desktop.
Laravel + Jquery Ajax Country and City
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE `paises` ( | |
`id` int(11) NOT NULL AUTO_INCREMENT, | |
`nombre` varchar(50) DEFAULT NULL, | |
PRIMARY KEY (`id`) | |
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; | |
CREATE TABLE `ciudades` ( | |
`id` int(11) NOT NULL AUTO_INCREMENT, | |
`pais_id` int(11) DEFAULT NULL, | |
`nombre` varchar(50) DEFAULT NULL, | |
PRIMARY KEY (`id`) | |
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Script | |
------------------------------ | |
<script type="text/javascript"> | |
$('select#country').change(function(){ | |
var countryId = $(this).val(); | |
$ciudaditems = $('.cityItems').remove(); | |
$.get('/ciudades/'+countryId, function(data){ | |
$.each(data, function(index, element){ | |
//console.log(element); | |
$('select#city').append('<option value="'+element.id+'" class="cityItems">'+element.nombre+'</option>') | |
}); | |
}, 'json'); | |
}); | |
}); | |
</script> | |
View | |
------------------------------ | |
Country : | |
<select name="country" class="country" id="country"> | |
<option selected="selected">--Seleccionar Pais--</option> | |
@foreach($paises as $pais) | |
<option value="{{ $pais->id }}">{{ $pais->nombre }}</option> | |
@endforeach | |
</select> <br/><br/> | |
Ciudad : | |
<select name="city" class="city" id="city"> | |
<option selected="selected">--Seleccionar Ciudad--</option> | |
</select> | |
Route | |
-------------------------- | |
Route::get('/ciudades/{id}', function($id) | |
{ | |
$pais_id = $id; | |
$ciudades = Pais::find($pais_id)->ciudades; | |
return Response::json($ciudades); | |
}); | |
Model Pais | |
------------------------ | |
class Pais extends \Eloquent { | |
protected $table = 'paises'; | |
public function ciudades() | |
{ | |
return $this->hasMany('ciudad'); | |
} | |
} | |
Model Ciudad | |
----------------------- | |
class Ciudad extends \Eloquent { | |
protected $table = 'ciudades'; | |
public function pais() | |
{ | |
return $this->belongsTo('pais'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment