How can I pass html array to laravel controller using ajax request? I did like below in my view:
<form>
<table class="table table-striped border-top" id="modalTable">
<thead>
<tr>
<th>start-time</th>
<th></th>
<th>end-time</th>
<th>reserve</th>
</tr>
</thead>
<tbody id="change">
<tr>
<td name="startTime[]"></td>
<td></td>
<td name="endTime[]"></td>
<td name="reserved[]"></td>
</tr>
</tbody>
</table>
<input type="hidden" id="token" value="{{ csrf_token() }}">
</form>
and the ajax code is below:
<script>
$(document).on('click','.btn',function(){
var startTime = $('#startTime').text();
//alert(startTime);
var endTime = $('#endTime').text();
//alert(endTime);
var token = $('#token').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
$.ajax
({
url:'reservePrivateChat',
type:'post',
data:{startTime:startTime,endTime:endTime,'_token':token},
success:function()
{
alert('success');
},
error:function()
{
alert('error');
}
})
});
</script>
and in controller I did like below :
public function reservePrivateChat(Request $request)
{
$startTime = $request->startTime;
print_r ($startTime);
$endTime = $_POST['endTime'];
print_r($endTime);
}
In controller there is no difference between $request
and $_POST
. Both return just one column of the table that sent by ajax but I want all values of the columns...
You can't do what you're trying to do. You have to manually construct the array based on the correct names of the table data. The #startTime
selector does not exist because it's looking for an element with id startTime
but you only have an element with name startTime[]
.
You an probably create an array as follows:
var startTime = [];
$("[name='startTime[]]'").each(function () {
startTime.push($(this).text());
});
var endTime = [];
$('[name='endTime[]]'').each(function () {
endTime.push($(this).text());
});
var token = $('#token').val();
//No need for ajax setup if you're sending the token as a parameter
$.ajax({
url:'reservePrivateChat',
type:'post',
data:{ startTime:startTime,endTime:endTime,'_token':token},