please help me solve this error
i tried too much but it still returns an error i don't know why please help
it returns Uncaught SyntaxError: missing ) after argument list at line that contains
<td>' + item.name + '</td>\
here is my code
<script>
$(document).ready(function(){
fetchpost();
function fetchpost() {
$.ajax({
type: "GET",
url: "/fetchpost",
dataType: "json",
success: function (response) {
// console.log(response);
$('tbody').html("");
$.each(response.posts, function (key, item) {
$('tbody').append('<tr>\
<td>' + item.id + '</td>\
<td>' + item.name + '</td>\
<td>show</td>\
<td><button type="button" value="' + item.id + '" class="btn btn-primary editbtn btn-sm">Edit</button></td>\
<td><button type="button" value="' + item.id + '" class="btn btn-danger deletebtn btn-sm">Delete</button></td>\
\</tr>');
});
}
});
}
})
you forgot to concat the string <td>show</td>\
Anyway try with this code:
$(document).ready(function(){
fetchpost();
function fetchpost() {
$.ajax({
type: "GET",
url: "/fetchpost",
dataType: "json",
success: function (response) {
// console.log(response);
$('tbody').html("");
$.each(response.posts, function (key, item) {
$('tbody').append('<tr>\
<td>' + item.id + '</td>\
<td>' + item.name + '</td>\
<td>show</td>\
<td><button type="button" value="' + item.id + '" class="btn btn-primary editbtn btn-sm">Edit</button></td>\
<td><button type="button" value="' + item.id + '" class="btn btn-danger deletebtn btn-sm">Delete</button></td>\
\</tr>');
});
}
});
}
})
Related
Within a view of Laravel, I generate a report and charge it using ajax. In the report I have three buttons, one of them is "Add".
Clicking on the "Add button does not redirect me to the route (viewAlarmasConfDestinatarios), in which I should show another form with fields that I must complete.
{{route ()}} does not work within ajax
ajax:
function fetch_data()
{
var trHTML ='';
$.ajax({
url: 'reporteAlarmasConfiguracion/',
type: "GET",
data : {"_token":"{{ csrf_token() }}"},
dataType: "json",
success:function(data)
{
if(data)
{
console.log('ENTRE AL FETCH_DATA');
$('#locationA > tbody').empty();
$.each(data, function(key, value)
{
var product_id = value.pais +'-'+ value.servicio +'-'+ value.denominacion;
var url = '{{ route("viewAlarmasConfDestinatarios.index", ":id") }}';
url = url.replace(':id',product_id);
console.log(url);
if($.trim(value.vigente) == '1')
{
console.log('ACTIVO');
value.vigente='<button type="button" class="btn btn-success btn-xs" id="'+ value.pais +'-'+ value.servicio +'-'+ value.denominacion+'">Activa</button>' ;
}
if($.trim(value.vigente) == '0')
{
value.vigente='<button type="button" class="btn btn-xs" id="'+ value.pais +'-'+ value.servicio +'-'+ value.denominacion+'"> Desactivada</button>' ;
}
if($.trim(value.pais) == '1')
{
value.pais='AR';
}
if($.trim(value.pais) == '2')
{
value.pais='UY';
}
if($.trim(value.pais) == '3')
{
value.pais='PY';
}
var data = {
"_token": $('#token').val()
};
var urlparm=value.pais +'-'+ value.servicio +'-'+ value.denominacion;
console.log(urlparm);
trHTML += '<tr id="fila"><td>' + value.pais + '</td><td>' + value.servicio + '</td><td>' + value.denominacion + '</td><td>' + value.descripcion + '</td><td>' + value.vigente + '</td><td>' + '<button type="button" class="btn btn-danger btn-xs delete" id="'+ value.pais +'-'+ value.servicio +'-'+ value.denominacion+'"> Eliminar</button> ' + '<button type="button" class="btn btn-warning btn-xs" id="'+ value.pais +'-'+ value.servicio +'-'+ value.denominacion+'"> Modificar</button>' + '</td><td>' + '<button type="button" class="btn btn-info btn-xs info"" id="'+ value.pais +'-'+ value.servicio +'-'+ value.denominacion+'" onclick="'+url+'">Cargar</button>' + '</td></tr>';
});
$('#locationA').append(trHTML);
}
}
});
}
route:
Route::get('/AlarmaConfDestinatarios/{denominacion?}', 'alarmasController#viewAlarmasConfDestinatarios')->name('viewAlarmasConfDestinatarios.index');
image
Try using {{route()}} within double inverted quotes like:
var url = "{{ route('viewAlarmasConfDestinatarios.index', ':id') }}";
I have a problem in getting the actual values from ids. I can't understand the issue because while storing these values I am getting them using Ajax in a dropdown where it stores its ids from the dropdown. But when I am trying to get these values back, then it shows me those ids and not the actual values. I can't understand how I can get the actual values from these ids. I also plucked them in my index method in the controller, but that's not working because it's Ajax. Below is my code, please let me know if you want to know anything more about this.
Controller actions for creating the form.
public function create()
{
$classes = StudentsClass::pluck('class_name', 'id')->all();
$rep_cat = ReportCtegories::pluck('name', 'id')->all();
return view('admin.reports.create', compact('classes', 'rep_cat'));
}
public function getStudentId($id)
{
$students = DB::table("students")->where("students_class_id", $id)->pluck("student_id", "id");
return json_encode($students);
}
public function getStudentName($id)
{
$students = DB::table("students")->select("id", DB::raw("CONCAT(first_name, ' ', last_name) as name"))
->where("students_class_id", $id)->pluck("name", "id");
return json_encode($students);
}
Ajax for getting values.
<script>
$(document).ready(function () {
//FOR LOADING STUDENTS
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('select[name="class_id"]').on('change', function () {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/reports/ajax/' + classID,
type: "GET",
dataType: "json",
success: function (data) {
var markup = '';
markup = '<thead><tr class="filters"><th style="width: 2%" class="align-middle text-center"><input type="checkbox" id="options"></th><th style="width: 15%" class="text-center">Student ID<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Student Name<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Report Category<input type="text" class="form-control" disabled></th> <th style="width: 15%;" class="align-middle text-center">Actions</th> <tr></thead><tbody>';
$.each(data, function (key, value) {
markup += '<tr> <td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="' + value.id + '"></td> <td><input type="hidden" value="' + value.student_id + '" name="student_id[]">' + value.student_id + '</td> <td><input type="hidden" value="' + value.student_name + '" name="student_name[]">' + value.student_name + '<td><input type="hidden" value="' + value.report_categories_id + '" name="report_categories_id[]">' + value.report_categories_id + '</td>' + '<td style=" width=12%" class="text-center"> <a data-toggle="modal" data-target="#editAttendanceModal' + value.id + '"""><button title="Edit" class="btn btn-outline-primary"><span class="fas fa-pencil-alt"></span></button></a> </td>' + '</td> <tr>';
});
markup += '</tbody>';
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
</script>
First of all i recommend you use,
return response()->json($students)
Second pluck only return an array of ids(in your case)
I think you can try with this.
public function getStudentId($id)
{
$students = DB::table("students")->where("students_class_id", $id)->get();
return response()->json($students);
}
These are my databases, where a division can have many districts (division_id is the foreign key in districts table).
When I submit the modal (using Ajax with laravel) the division name comes as undefined.
However, after I refresh the browser, everything seems to be working okay. Why is this happening and how do I fix it?
This is the code I am using to show the data.
{{ csrf_field() }}
<?php $no=1; ?>
#foreach ($district as $district)
<tr class="post{{$district->id}}">
<td>{{ $no++ }}</td>
<td>{{ $district->division->name}}</td>
<td>{{ $district->code}}</td>
<td>{{ $district->name}}</td>
<td>{{ $district->created_at}}</td>
<td>
<a href="#" class="show-modal btn btn-info btn-sm" data-id="{{$district->id}}" data-division_id="{{$district->division->name}}" data-code="{{$district->code}}" data-name="{{$district->name}}" >
<i class="fa fa-eye"></i>
</a>
<a href="#" class="edit-modal btn btn-warning btn-sm" data-id="{{$district->id}}" data-division_id="{{$district->division->name}}" data-code="{{$district->code}}" data-name="{{$district->name}}" >
<i class="glyphicon glyphicon-pencil"></i>
</a>
<a href="#" class="delete-modal btn btn-danger btn-sm" data-id="{{$district->id}}" data-division_id="{{$district->division->name}}" data-code="{{$district->code}}" data-name="{{$district->name}}" >
<i class="glyphicon glyphicon-trash"></i>
</a>
</td>
</tr>
#endforeach
This is my controller.
use Illuminate\Http\Request;
use App\Division;
use App\District;
use Validator;
use Response;
use Illuminate\Support\Facades\Input;
use App\http\Requests;
class DistrictController extends Controller
{
public function index()
{ $district = District::all();
$divisionDistricts = Division::pluck('name','id');
return view('masterForms.district',compact('district','divisionDistricts'));
}
public function store(Request $request)
{
if($request->ajax())
{
$district = District::create($request->all());
$district->save();
return response($district);
}
}
This is my District Model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Division;
class District extends Model
{
protected $fillable = ['code','name','division_id'];
public function division()
{
return $this->belongsTo(Division::class);
}
}
?>
And this is the javaquery I am using to add my data to the database.
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('content')
}
});
$(document).on('click','.create-modal', function() {
$('#create').modal('show');
$('.form-horizontal').show();
$('.modal-title').text('Add District');
});
$('#ddistrict').on('submit',function(e){
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr('action');
var post = $(this).attr('method');
$.ajax({
type: post,
url: url,
data: data,
dataTy: 'json',
success:function(data)
{
$('.error').remove();
$('#table').append("<tr class='post" + data.id + "'>"+
"<td>" + data.id + "</td>"+
"<td>" + data.division_id.name + "</td>"+
"<td>" + data.code + "</td>"+
"<td>" + data.name + "</td>"+
"<td>" + data.created_at + "</td>"+
"<td><button class='show-modal btn btn-info btn-sm' data-id='" + data.id + "' data-division_id.name='" +
data.division_id.name + "' data-code='" +
data.code + "' data-name='" +
data.name + "'><span class='fa fa-eye'></span></button> <button class='edit-modal btn btn-warning btn-sm' data-id='" + data.id +"' data-division_id.name='" +
data.division_id.name + "' data-code='" +
data.code + "' data-name='" +
data.name + "'><span class='glyphicon glyphicon-pencil'></span></button> <button class='delete-modal btn btn-danger btn-sm' data-id='" + data.id + "' data-division_id.name='" +
data.division_id.name + "' data-code='" +
data.code + "' data-name='" +
data.name + "' ><span class='glyphicon glyphicon-trash'></span></button></td>"+
"</tr>");
}
});
})
</script>
Just returning $disrtict will just give you division_id not division name. And you can't use data.division_id.name in your javascript.
To return division you must append division name with your other attributes of districts. Or you might use Api Resources to provide your custom json response.
To append division name attribute in you district you should use $appends variable.
class District extends Model
{
protected $appends = ['division_name'];
protected $fillable = ['code','name','division_id'];
public function division()
{
return $this->belongsTo(Division::class);
}
public function getDivisionNameAttribute(){
return $this->division->name;
}
}
Now in your ajax resopnse use
success:function(data)
{
$('.error').remove();
$('#table').append("<tr class='post" + data.id + "'>"+
"<td>" + data.id + "</td>"+
"<td>" + data.division_name + "</td>"+
"<td>" + data.code + "</td>"+
"<td>" + data.name + "</td>"+
"<td>" + data.created_at + "</td>"+
"<td><button class='show-modal btn btn-info btn-sm' data-id='"+ data.id + "' data-division_id='" +
data.division_name + "' data-code='" +
data.code + "' data-name='" +
data.name + "'><span class='fa fa-eye'></span></button> <button class='edit-modal btn btn-warning btn-sm' data-id='" + data.id +"' data-division_id.name='" +
data.division_name + "' data-code='" +
data.code + "' data-name='" +
data.name + "'><span class='glyphicon glyphicon-pencil'></span></button> <button class='delete-modal btn btn-danger btn-sm' data-id='" + data.id + "' data-division_name='" +
data.division_name + "' data-code='" +
data.code + "' data-name='" +
data.name + "' ><span class='glyphicon glyphicon-trash'></span></button></td>"+
"</tr>");
}
I would like to close my modalbox, so I return to the same page, after I click the "Select" button.
I am on shuffle.php. I open the modalbox and call the code in updaterecords.php. When I click Select I should return to shuffle.php. The problem is right now that I am redirected to updaterecords.php.
I try to solve that with adding this code to my AJAX call:
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
But I am still redirected. Is the code I added in the wrong place?
shuffle.php
<div class="modal-footer msg">
<form action="updaterecords.php" method="post">
<input type="hidden" id="fantasy-id" value="" name="id" />
<button type="submit" name="selectStore" >Select</button>
<button type="button" data-dismiss="modal">Close</button>
</form>
</div>
updaterecords.php
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});
Please try to use $('.modal').modal('hide'); on updaterecords.php.
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$('.modal').modal('hide');
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});
I am new to Laravel framework but I really like it.
My biggest problem is I have been searching on how I can delete a single record using resource controller.
Controller method:
public function destroy($id) {
$department = Department::find($id);
$department->delete();
}
Delete link I have tried:
<a class="btn btn-xs btn-danger" data-method="delete" href="{{ URL::to('department/' . $department->id) }}"><i class="icon-remove"></i></a>
Javascript:
<script type="text/javascript">
$(function(){
$('[data-method]').append(function(){
return "\n" +
"form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" +
"<input type='hidden' name='_method' value='"+$(this).attr('data-method')+"'>\n" +
"</form>\n"
})
.removeAttr('href')
.attr('style', 'cursor: pointer;')
.attr('onclick', '$(this).find("form").submit();');
});
Now when I click on the delete link, it doesn't work.
Any idea on what am I doing wrong, I have been searching for so long.
Use $.post() to trigger your click instead of that form creation/submission:
$(document).on("click", "[data-method]", function(e) {
e.preventDefault();
$.post($(this).attr('href'), {/* the id goes here */});
});
Apply the cursor style via CSS. I must admit that I'm not sure if laravel expects a HTTP DELETE instead of a post. And I think you missed to submit the id of the department you want to delete.
[edit]
As laravel expects a HTTP DELETE you can't use the $.post() shorthand, but $.ajax() instead:
$(document).on("click", "[data-method]", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('href'),
type: "DELETE",
data: {/* the id goes here */},
success: function(data, textStatus, jqXHR) {
console.log("success");
}
});
});
The destroy() will be called in DELETE request and not in POST request.
So try ,
<a class="btn btn-xs btn-danger" onclick="deleteDepartment($department->id)" href="javascript:void(0)"><i class="icon-remove"></i></a>
And in javascript,
function deleteDepartment(id) {
$.ajax({
url: 'department/'+id,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
}
Thanks for the answers guys, it works just as it is I just forgot the opening < when creating a form ie I was mistakenly wrote:
"form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" +
Instead of:
"<form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" +