I am trying to take selected option from <select>
, pass it through to method show()
in controller, use it to retrieve data from database, and then return it as json to the success method in $.ajax
. All this is happening through jquery.ajax
.
How can i get/receive data i pass from $.ajax
request to manipulate the database?
Here is the code I am using:
Route::post('rate/units',array('as'=>'unitRoute','uses'=>'RateController@show'));
public function show()
{
$row[] = $_POST['deg'];
return json_encode($row);
}
<select class="form-control choosedegree" name="sem" id="semester">
<option value="" selected="selected" disabled>Select Semester</option>
<option value="1">Year 1, Semester 1</option>
<option value="2">Year 1, Semester 2</option>
<option value="3">Year 2, Semester 1</option>
<option value="4">Year 2, Semester 2</option>
<option value="5">Year 3, Semester 1</option>
<option value="6">Year 3, Semester 2</option>
<option value="7">Year 4, Semester 1</option>
<option value="8">Year 4, Semester 2</option>
</select>
<script>
$(document).ready(function() {
$('select#semester').on('change', function() {
var optionSelected = $(this).find("option:selected");
semesterSelected = optionSelected.val();
console.log(semesterSelected);
$.ajax({
type: "POST",
cache: false,
url : "rate/units",
data: { sem : semesterSelected },
success: function(data) {
var obj = $.parseJSON(data);
var i = 0;
console.log(data.iyo);
$.each(obj, function() {
console.log(this[0]);
console.log(this[1]);
console.log(this[2]);
console.log(this[3]);
console.log(this[4]);
i++;
});
}
})
.done(function(data) {
alert('done');
})
.fail(function(jqXHR, ajaxOptions, thrownError) {
alert('No response from server');
});
});
});
</script>
You post data can be retrieved using Input:
public function show()
{
$semester = Input::get('sem');
return json_encode($semester);
}
To debug it you can:
public function show()
{
Log::info(Input::all());
$semester = Input::get('sem');
return json_encode($semester);
}
And then execute at the console
php artisan tail
I'm using Laravel version 5.4.36 and I used this method to retrieve data from ajax request.
Controller:
public function processData(Request $request){
$data = $request->all();
print_r($data);
echo $data['email'];
}
View:
function someMethod(prm){
$.get("{!! route('routename') !!}",{email:prm},function(res){
console.log('Response:',res);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With