Update table via ajax in Laravel view with table join - javascript

My goal is get the attribute "nombreSubdireccion" of the table "subdireccion" show when insert/update a new registry of "area" via AJAX, the only way I got it is reloading the page because of DB::table. I don´t know where declare the join, pls help me (sorry for my speak)
there are the models:
class subdireccion extends Model
{
public $table = "subdireccion";
protected $primaryKey = 'idSubdireccion';
public $timestamps = false;
public $fillable=['nombreSubdireccion'];
}
class area extends Model
{
public $table = "area";
protected $primaryKey = 'idArea';
public $timestamps = false;
public $fillable = [
'nombreArea',
'subdireccion_idSubdireccion',
];
}
The AJAX file:
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
console.log(data);
var area = '<tr id="area' + data.idArea + '">';
area += '<td>' + data.idArea + '</td><td>' + data.subdireccion_idSubdireccion + '</td><td>' + data.nombreArea + '</td>';
area += '<td><button class="btn btn-primary btn-detail open_modal" value="' + data.idArea + '">Editar</button>';
area += '<button class="btn btn-danger btn-delete delete-subdir" value="' + data.idArea + '">Eliminar</button></td>';
area += '</tr>';
if (state == "add") {
notify('¡ Área creada con éxito !', 'success');
$('#area-list').append(area);
} else {
notify('¡ área actualizada con éxito !', 'success');
$("#area" + area_id).replaceWith(area);
}
$('#form_area').trigger("reset");
$('#myModal').modal('hide')
},
error: function (data) {
notify('¡ ERROR !', 'error');
console.log('Error:', data);
}
});
The web.php (controller)
Route::get('areas', function () {
$subdirecciones = App\subdireccion::All();
$areas = DB::table('subdireccion as s')
->join('area as a', 's.idSubdireccion', '=', 'a.subdireccion_idSubdireccion')
->select('a.*', 's.nombreSubdireccion as subdireccion')
->paginate(10);
return view('admAreas', compact('areas','subdirecciones'));
});
Route::get('areas/{area_id?}',function($area_id){
$area = App\area::find($area_id);
return response()->json($area);
});
Route::post('areas',function(Request $request){
$area = App\area::create($request->input());
return response()->json($area);
});
Route::put('areas/{area_id?}',function(Request $request, $area_id){
$area = App\area::find($area_id);
$area->subdireccion_idSubdireccion = $request->subdireccion_idSubdireccion;
$area->nombreArea = $request->nombreArea;
$area->save();
return response()->json($area);
});
page-view

Best way is to define method in controller and make model calls for DB queries there so that you can use laravel functionalities properly.

Related

Passing List String from C# to JavaScript

I am currently trying to check if a value of a string variable is "Apple". Now I need to pass a list of fruits to javascript from C#.
C# Code
List<String> fruits = new List<String>{"Apple","Mango","Orange"}
JavaScript Code
$(document).on('click','#dvAppContent input:checkbox[id*=chkfunction]', function () {
ToggleApplication(this);
});
function ToggleApplication(currentFunction) {
var fruitName = $(currentFunction).closest('ui').parent('label').text().trim();
If(fruitName == "Apple")
{
return true;
}
}
Use Ajax call in JavaScript.
Something like this:
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/api/StudentAPI/GetAllStudents",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
$.each(data, function (i, item) {
var rows = "<tr>" +
"<td id='RegdNo'>" + item.regNo + "</td>" +
"<td id='Name'>" + item.name + "</td>" +
"<td id='Address'>" + item.address + "</td>" +
"<td id='PhoneNo'>" + item.phoneNo + "</td>" +
"<td id='AdmissionDate'>" + Date(item.admissionDate,
"dd-MM-yyyy") + "</td>" +
"</tr>";
$('#Table').append(rows);
}); //End of foreach Loop
console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
});
</script>
And in the backend in c#, something like this:
public class StudentAPIController : Controller
{
// GET: api/GetAllStudents
[HttpGet]
public IEnumerable<PersonalDetail> GetAllStudents()
{
List<PersonalDetail> students = new List<PersonalDetail>
{
new PersonalDetail{
RegNo = "2017-0001",
Name = "Nishan",
Address = "Kathmandu",
PhoneNo = "9849845061",
AdmissionDate = DateTime.Now
},
new PersonalDetail{
RegNo = "2017-0002",
Name = "Namrata Rai",
Address = "Bhaktapur",
PhoneNo = "9849845062",
AdmissionDate = DateTime.Now
},
};
return students;
}
}

GET Method always receives null value

I´m trying to get a list with Ajax when a modal shows up, but for some reason my method always receives a null variable. I´m sure that the issue is on the Ajax call, because if I test my method using 1 as an argument instead of the value from Ajax, it returns the list the way I wanted.
JS:
$("#visualizacao").on('show.bs.modal', function (e) {
var data = $(e.relatedTarget);
var idAviso = data.context.dataset.avisoid;
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/' +idAviso,
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});
C#
[HttpGet]
public JsonResult ListaVisuAviso(string avisoId)
{
//var avisoid = 1;
var avisoid = Convert.ToDecimal(avisoId);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
}
I discovered what was causing the "issue". To use this way of sending the parameter, my route config on the backend was expecting it to be a parameter called "id". So I would either change my receiving parameter to "id" instead of "avisoId" like the following:
[HttpGet]
public JsonResult ListaVisuAviso(string id)
{
//var avisoid = 4;
var avisoid = Convert.ToDecimal(id);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
Or, I would have do specify the name of the parameter on the JS, like this "?usuarioId=", this way the route would know that it´s not the id parameter:
$("#visualizacao").on('show.bs.modal', function (e) {
var idAviso = $(e.relatedTarget).attr('data-avisoid');
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/?usuarioId =' + idAviso,
dataType: 'json',
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});

Cannot retrieve data from PHP array, which is returned by a function() that uses JQuery Ajax

I have this "click Listener" that calls and sends a userId parameter to the function-"getModalData" which then returns an array value to the variable-"arrayedUserData".
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '',
arrayedUserData = getModalData(userId);
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
This is the function-"getModalData". The returned php array from the Ajax's "success" will then be passed to the variable-"UserData" that is then returned by the function.
function getModalData(passedUserId) {
var UserData;
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
UserData = data;
}
}
);
return UserData;
}
this is the "get_modal_data.php".
<?php
include "../includes/connect.php";
if (isset($_POST['passedUserId'])) {
$UserId = mysqli_real_escape_string($con, $_POST['passedUserId']);
$getUserData = mysqli_query($con, "SELECT * FROM tblUserAccounts WHERE uaUserId = '".$UserId."'");
$uaRow = mysqli_fetch_assoc($getUserData);
$UserDataArr = array("UserId" => $uaRow['uaUserId'],
"EmailAddress" => $uaRow['uaEmailAddress'],
"FirstName" => $uaRow['uaFirstName'],
"LastName" => $uaRow['uaLastName'],
"BirthDate" => $uaRow['uaBirthDate'],
"Address" => $uaRow['uaAddress'],
"Gender" => $uaRow['uaGender'],
"ContactNumber" => $uaRow['uaContactNumber'],
"BloodTypeId" => $uaRow['uaBloodTypeId'],
"AccountStatus" => $uaRow['uaAccountStatus'],
);
echo json_encode($UserDataArr);
exit();
}
?>
this error appears on the console:
Uncaught TypeError: Cannot read property 'LastName' of undefined get_user_accounts.js:66
this is the line 66 of get_user_accounts.js, which is present on the "click listener".
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
but, I am confused because the php array appears on the browser's Network Response:
Successful Connection{"UserId":"1","EmailAddress":"paulanselmendoza#gmail.com","FirstName":"Paul Ansel","LastName":"Mendoza","BirthDate":"1998-12-17","Address":"Phase 1B Block 8 Lot 20 Olivarez Homes South, Sto. Tomas, Binan City, Laguna","Gender":"Male","ContactNumber":"2147483647","BloodTypeId":"0","AccountStatus":"ACTIVE"}
Did you see that you get: Successful Connection before the JSON data? You have to remove that, if not it will be an invalid JSON response. The code you have shared doesn't have the particular stuff.
I believe you have to check your database connection, where on successful connection, it is set to output Successful Connection, which breaks your response. Please remove that bit of code.
include "../includes/connect.php";
It can be something like:
$conn = mysqli_connect() or die("Error");
echo "Successful Connection";
Because getModalData fucntion return the UserData before it asign by ajax(UserData = data;). use a callback function:
using callbacks
function getModalData(passedUserId,callback) {
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
callback(data);
}
}
);
}
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '';
getModalData(userId, function (arrayedUserData) {
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
});

Ajax data do not show in table?

I have Allocate_classRoom DB table where I want to show data using ajax
function departmentQuery()
{
var department = $('#department' ).val();
if(department!=" ")
{
var urls = "{{ URL::to('roomAjax') }}";
var request = $.ajax({
url: urls+"/"+department,
type: "GET",
dataType: 'json'
});
request.done(function(data){
var allRoom ="";
for (var i=0; i<data.length;i++)
{
// room +="<option value=' " +data[i].id+ " ' >"+data[i].name+ "</option>";
allRoom +=" <tr> " +
"<td>"+data[i].id+"</td>"+
"<td>"+data[i].course_id+"</td>"+
/*"<td>"+ course->name+"</td>"+*/
"<td>"+data[i].Room_No+"</td>"+
"<td>"+data[i].date+data[i].start_time+data[i].end_time+"</td>"+
"</tr>";
}
$("#allRoom").html(allRoom);
});
request.fail(function(){
alert('failed to get items for that department');
});
}else {
alert('Select Department');
}
}
And I am uploading controller code
public function ajaxRoom($id)
{
$allRoom = AllocateClassroom::where('department_id',$id)-
>with('course')->get();
return response()->json($allRoom);
}
.Data return from the database but I could not show it my view table please I want your suggestion.

Why servlet don't send json custom string or Ajax don't receive it?

I made this servlet that response with a simple json list:
public void aggiungiCategoria(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
logger.log(Level.INFO, "Aggiungo la categoria");
ObjectifyService.register(Studente.class);
ObjectifyService.register(Categoria.class);
String idS=req.getParameter("ids");
String idC= req.getParameter("idc");
Studente s=ofy().load().type(Studente.class).id(Long.parseLong(idS)).now();
System.out.println(s.getNome());
if(s!=null){
Categoria c=ofy().load().type(Categoria.class).id(Long.parseLong(idC)).now();
System.out.println(Key.create(Categoria.class, c.id));
s.addCategoria(Key.create(Categoria.class, c.id));
ofy().save().entity(s).now();
StringBuilder sb= new StringBuilder();
// sb.append("[");
for(Key k : s.getCategorie()){
Categoria c1=ofy().load().type(Categoria.class).filterKey(k).first().now();
System.out.println(c1.getNome());
sb.append("{");
sb.append("id: ");
sb.append("'"+c1.getId()+"', ");
sb.append("nome: ");
sb.append("'"+c1.getNome()+"'},");
}
sb.append("{}");
System.out.println("Aggiunto: "+sb.toString());
resp.setContentType("application/json"); // Set content type of the response so that jQuery knows what it can expect.
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write(sb.toString());
}
}
the example output for only one item in the DB is:
{id: '4749890231992320', nome: 'c2'},{}
In my javascript code there is a right menu click on a table. When a user add an item of the table, start the ajax request who if success update another table with the data of the servlet.
<script type="text/javascript">
$(document).ready(function() {
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
console.log();
$('#contacts tbody tr').contextMenu('myMenu1', {
bindings: {
'open': function(t) { AddAction(t, "Open"); },
'email': function(t) { ShowAction(t, "Email"); },
'save': function(t) { ShowAction(t, "Save"); },
'delete': function(t) { ShowAction(t, "Delete"); }
}
});
function AddAction(t, a) {
$.ajax({
url : 'studenteServlet? action=aggiungiC&ids='+$.urlParam('id')+'&idc='+t.id,
type : "POST",
async : false,
success : function(data) {
console.log(data);
$('#catAssociate tbody > tr').remove();
var html = '';
for(var i = 0; i < data.length; i++)
html += '<tr><td id='+data[i].id +'>' + data[i].nome + '</td></tr>';
$('#catAssociate').append(html);
}
});
}
function ShowAction(t, a) {
alert('Trigger was ' + t.id + '\nAction was ' + a + "\nHtml is " + $(t).html());
}
});
If i change the content type with "text/html" the data is sent. I made this example using this example Thanks!
EDIT - I resolved with:
sb.append("[");
for(Key k : s.getCategorie()){
Categoria c1=ofy().load().type(Categoria.class).filterKey(k).first().now();
sb.append("{");
sb.append("\"" +"id" + "\" : \"" + c1.getId() + "\",");
sb.append("\"" +"nome" + "\" : \"" + c1.getNome() + "\",");
sb.deleteCharAt(sb.lastIndexOf(","));
sb.append("},");
}
sb.deleteCharAt(sb.lastIndexOf(","));
sb.append("]");
But now i have problem with draw the table. It stamp nothing on the web page.
I edited my answer. The example works fine now!

Categories