Filling a form in JSP with ajax - ajax

I know this kind of questions has already been asked, but I totally am a newbie with Ajax and JavaScript.
I have a field (codigo_caso) which I need to be the launcher for the form filling
<input id="codigo_caso" autofocus="autofocus" type="text" name="codigo_caso" value=""/>
I have to retrieve 4 variables after loosing focus on that field (or 1 variable if the other 4 are empty)
And the big problem after retrieving those 4 variables is how to work well with them.
JSP Web Page --> Script
This is the fragment i copied from the internet and modified to receive ONE field
$(document).ready(function() {
$("#codigo_caso").blur(function() {
var cod = $(this).val();
var dataString1 = {"codigo":cod};
$.ajax({
type: "GET",
url: "otros/codigoCasoDependienteNuevaTarea.jsp",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: dataString1,
cache: false,
success: function(response) {
$(".linea_equipo").response("linea_equipo");
$("#selectArea").filter(function() {
return $(this).response("id_area") === response("area");
}).prop('selected', true);
$(".listaCentros").response("nombre_centro");
$("#listaRolNuevaTarea").filter(function() {
return $(this).response("id_rol") === response("rol");
}).prop('selected', true);
}
});
});
});
This is my JSP file launching the SQL [where i need to recover several variables]. I need to know how to return these 3 fields to my previous JSP
JSP FILE --> otros/codigoCasoDependienteNuevaTarea.jsp
String linea = "", centro = "", error = "No existe el caso indicado";
int area, rol;
Connection conex = (Connection) session.getAttribute("conexion");
Statement st = conex.createStatement();
String sql = "";
String cod = request.getParameter("codigo").toString();
if (cod != null && !cod.isEmpty() && !cod.equals("0")) {
sql = "SELECT t1.linea_equipo,t1.id_rol, t2.id_area,t2.nombre_centro "
+ " FROM gen_casos_prisma t1 LEFT OUTER JOIN gen_centros t2 ON "
+ " t1.id_centro = t2.id_centro "
+ " WHERE "
+ " t1.CODIGO_CASO = " + cod;
ResultSet rs = st.executeQuery(sql);
rs.beforeFirst();
if (rs.next()) {
linea = rs.getString("linea_equipo");
area = rs.getInt("id_area");
centro = rs.getString("nombre_centro");
rol = rs.getInt("id_rol");
JSONObject j = new JSONObject();
j.put("linea_equipo", linea);
j.put("id_area", area+"");
j.put("nombre_centro", centro);
j.put("id_rol", rol+"");
} else {
/* return variable error */
}
response.setContentType("application/json");
}
The next step after knowing how to receive these fields is to know what to do with them. i know how can i place linea_equipo in a text-field [with the code I posted in the script above the JAVA code] but i also need to set as "selected" one option in each of these lists (two are dropdown lists and the other is a datalist) taking into account that they are already filled; just need to place selected attribute in the value that matches the field that the form must receive from this ajax-jsp thing.
(selectArea - id_area, listaCentrosDeArea - nombre_centro, listaRolNuevaTarea - id_rol)
<select id="selectArea" >
<%out.print(f.getSelectAreas(conex));%>
</select>
<datalist id="listaCentrosDeArea" id="datalist1">
<% //out.print(f.selectCentrosNOUser(conex, updateTarea));%>
</datalist>
<select id="listaRolNuevaTarea" name="rol">
<% out.print(f.selectRolesNoUser(conex));%>
</select>
Sorry if it seems a bit tricky or heavy, but I've been requested to do this and I have no idea.

when you are doing
success: function(html) {
("#linea_equipo").val(html);
}
you are returning the value to the JSP, so just make sure that all the elements that you want filled in have an id like linea_equipo

In the success part of your code you can write the logic to populate data to your form.
success: function(response)
{
$("#ID").val("value");//find these value from your response
// if your response is JSON you can replace value like response.key
}
see what json is
For selecting a drop down by jQuery use
$('#dropdownid').val('selectedvalue');
//========
code to return response as json in java servlet
response.setContentType("application/json");
response.getWriter().write(jsonobject.toString());

Related

Datatable info is lost after i do a flitered search

I'm having a problem with a data table, whenever I use the search function in my table all the data is lost the moment I input anything on the search bar, I create this data table dynamically using AJAX, first I do a request to the server to get the data for my table.
function traerBecas() {
var ciclo = document.getElementById("ciclo").value;
$.ajax({
url: '/becas/listaBecas',
type: 'GET',
data: {
"ciclo": ciclo,
},
dataType: 'JSON',
success:function(response){
llenarTabla(response);
}
});
}
Once I get the response as a JSON I pass the info to another function to build each table row and insert it into the table.
function llenarTabla(jsonArray) {
var tabla = document.getElementById('becaBody');
tabla.innerHTML = "";
jsonArray.forEach(element => {
var trElement = document.createElement('tr');
var tdCLVBECA = document.createElement('td');
var tdINSTIT = document.createElement('td');
var tdCICLO= document.createElement('td');
var tdSECCION = document.createElement('td');
var tdFECINI = document.createElement('td');
var tdFECFIN = document.createElement('td');
var tdACCIONES = document.createElement('td');
var linkEditar = document.createElement('a');
var linkEliminar = document.createElement('a');
tdCLVBECA.innerText = element.CLV_BECA;
tdINSTIT.innerText = element.INSTIT.toUpperCase();
tdCICLO.innerText = element.CICLO;
tdSECCION.innerText = element.SECCION;
tdFECINI.innerText = element.FEC_INI;
tdFECFIN.innerText = element.FEC_FIN;
linkEditar.setAttribute("href","/becas/editar/"+element.CLV_BECA);
linkEditar.setAttribute("data-bs-toggle", "tooltip");
linkEditar.setAttribute("data-bs-placement", "top");
linkEditar.setAttribute("title", "Eliminar");
linkEditar.innerHTML = "<i class='fas fa-pen'></i>";
linkEliminar.setAttribute("onclick", "eliminacion("+element.CLV_BECA+")");
linkEliminar.setAttribute("data-bs-toggle", "tooltip");
linkEliminar.setAttribute("data-bs-placement", "top");
linkEliminar.setAttribute("title", "Editar");
linkEliminar.innerHTML = " <i class='fas fa-trash'></i>";
tdACCIONES.appendChild(linkEditar);
tdACCIONES.appendChild(linkEliminar);
trElement.appendChild(tdCLVBECA);
trElement.appendChild(tdINSTIT);
trElement.appendChild(tdCICLO);
trElement.appendChild(tdSECCION);
trElement.appendChild(tdFECINI);
trElement.appendChild(tdFECFIN);
trElement.appendChild(tdACCIONES);
tabla.appendChild(trElement);
});
}
Then I have the function to transform my table to a data table, and up to this moment, everything works alright. EDIT: Forgot to mention that this info is run first when the page is loaded, the table at the beginning is empty and then is filled with the info I requested.
$(document).ready(function() {
$('#myTable').DataTable({
responsive: true,
language: {
url: '//cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json'
}
});
});
Then, once I have my table built, I try to use the search function that it generates, but then I run into the problem that the table doesn't find the info, loses the data, and doesn't return to the previous state once I delete the prompt on the search bar.
I'm at a loss of what to do, I have other data tables that don't have this problem, however, those tables aren't built using AJAX, they get their info directly from the controller with the compact() function in the PHP controller, and using Blade directives like #foreach loops.
You should open up your browser's dev tools and inspect the network request to your endpoint:
url: '/becas/listaBecas'
It could be a number of things, the network tab will show you if there is an error with the AJAX request. If the AJAX request has no error, you will want to look at your endpoint and debug the query that is being run to see why it's not returning any results.
Would also be a good idea to add a error catch for the AJAX call:
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request");
}

Kendo UI Large Parameters Value (414 Request-URI Too Long) error

Hy This code is part of my grid.
grid._parameterMap = function (data, type) {
if (type !== "read" && data.models)
return { models: kendo.stringify(data.models) };
var warehouseCodeList = [];
var selectedWarehouse_OnPhysicalCountDefinition = '';
$.each(KendoData('mltWarehouse_OnPhysicalCountDefinition').dataItems(), function (index, value) {
selectedWarehouse_OnPhysicalCountDefinition += value.WarehouseCode + ',';
});
selectedWarehouse_OnPhysicalCountDefinition = selectedWarehouse_OnPhysicalCountDefinition.slice(0, -1);
var parameters = {
warehouseCodeList: selectedWarehouse_OnPhysicalCountDefinition,
periodDateString: $('#dpcPeriodDate_OnPhysicalCountDefinition').val(),
Page: data.page,
PageSize: data.pageSize
}
return kendo.data.transports["odata"].parameterMap(parameters, type);
};
And parameters value is
Page
:
1
PageSize
:
50
periodDateString
:
"17/10/2022"
warehouseCodeList
:
"480176,480172,480003,480166,480109,480025,480090,480089,480002,480088,
480061,480101,480016,480009,480095,480008,480094,480093,480006,480092,480005,480091,480004,
480117,480033,480114,480060,480113,480163,480030,480059,2011,480157,480028,480045,480048,
480039,480029,480120,480046,480156,480049,480072,480063,480062,48006100,480071,480070,480069,
480068,480067,480066,480065,480064,480077,480076,480085,480084,480082,480078,480073,480075,480079,
480074,480083,480127,480128,480057,480129,480058,480081,480080,480141,480132,480131,480130,480140,
480138,480137,480136,480135,480134,480133,480146,480145,480154,480153,480151,480147,480142,480144,
480148,480143,480152,480139,480150,480149,480106,480126,480055,480165,480167,480100,480123,480053,
480096,480168,480162,480159,480158,480038,480102,480017,480013,480122,480047,480116,480032,480034,
480107,480040,480118,480098,480051,480110,480026,480111,480027,480108,480103,480115,480031,480035,
480087,480086,480036,480119,480112,480010,480097,480155,480124,480054,480019,480099,480104,480171,
480164,480041,480042,480121,480043,480044,480014,480052,480170,480037,480050,480012,480105,480169,
480161,480174,480173"
You can see that my data and that large data not going my controller becouse of that large warehouseCodeList.You can see Request below.This request is Send Get Request in Controller.If I can change Post I think gone work bu HOW! =)
Request URL: https://zzzz/Inv/yyy/xxxx/?%24inlinecount=allpages&%24format=json&warehouseCodeList=480176%2C480172%2C480003%2C480166%2C480109%2C480025%2C480090%2C480089%2C480002%2C480088%2C480061%2C480101%2C480016%2C480009%2C480095%2C480008%2C480094%2C480093%2C480006%2C480092%2C480005%2C480091%2C480004%2C480117%2C480033%2C480114%2C480060%2C480113%2C480163%2C480030%2C480059%2C2011%2C480157%2C480028%2C480045%2C480048%2C480039%2C480029%2C480120%2C480046%2C480156%2C480049%2C480072%2C480063%2C480062%2C48006100%2C480071%2C480070%2C480069%2C480068%2C480067%2C480066%2C480065%2C480064%2C480077%2C480076%2C480085%2C480084%2C480082%2C480078%2C480073%2C480075%2C480079%2C480074%2C480083%2C480127%2C480128%2C480057%2C480129%2C480058%2C480081%2C480080%2C480141%2C480132%2C480131%2C480130%2C480140%2C480138%2C480137%2C480136%2C480135%2C480134%2C480133%2C480146%2C480145%2C480154%2C480153%2C480151%2C480147%2C480142%2C480144%2C480148%2C480143%2C480152%2C480139%2C480150%2C480149%2C480106%2C480126%2C480055%2C480165%2C480167%2C480100%2C480123%2C480053%2C480096%2C480168%2C480162%2C480159%2C480158%2C480038%2C480102%2C480017%2C480013%2C480122%2C480047%2C480116%2C480032%2C480034%2C480107%2C480040%2C480118%2C480098%2C480051%2C480110%2C480026%2C480111%2C480027%2C480108%2C480103%2C480115%2C480031%2C480035%2C480087%2C480086%2C480036%2C480119%2C480112%2C480010%2C480097%2C480155%2C480124%2C480054%2C480019%2C480099%2C480104%2C480171%2C480164%2C480041%2C480042%2C480121%2C480043%2C480044%2C480014%2C480052%2C480170%2C480037%2C480050%2C480012%2C480105%2C480169%2C480161%2C480174%2C480173&periodDateString=17%2F10%2F2022&Page=1&PageSize=50
Request Method: GET
Status Code: 200 OK
And Finaly I try the give dataSource remote but not work .But I can give that data ın Ajax call.Can you Help me ?
What can I do in this situation?
There is a type option for the dataSource transport configuration that you can set. It will set the type of request the dataSource would make ("POST", "GET", "PUT" or "DELETE").
Thanks aleksandar.The code I use is below
<script>
var dataSource = new kendo.data.DataSource({
transport: {
read: {
/* omitted for brevity */
type: "POST"
}
}
});
</script>

How can I get the results of two SQL-Queries in PHP in one JS function with AJAX?

I am a complete beginner and I hope that you can help me.
In my php file I make two different database queries and I need their results for calculations in a js function, which in turn should be displayed in the browser.
If I try to display the results from both queries, only "undefined" is returned. However, they are displayed to me in the console, where I also have the numbers output via consol.log (data). I am trying this with the help of ajax. If I remove the part from the second DB query in my function, it works. Unfortunately not all together. What am I doing wrong? Is what I plan to do even possible or do I have to take a detour? If yes, which one?
Here is my previous code:
Javascript:
function clickPHPtoJS(){
$.ajax({
url: "index.php",
type: "POST",
success: function(data) {
console.log(data);
clickPHPtoJSResponse(data);
},
error: function (data) {
console.log("Daten nicht erhalten");
}
});
}
function clickPHPtoJSResponse(data) {
// Antwort des Server ggf. verarbeiten
var response = JSON.parse(data);
var einer = response.einer;
var zwoelfer = response.zwoelfer;
var anzahl = response.nr;
document.getElementById("lab1er").innerHTML = einer + " " + zwoelfer + " " + anzahl;
}
PHP:
<?php
require 'inc/db.php';
$erg = $db->query("SELECT id, sender FROM packaging_log WHERE sender='test' AND packaging='1er'")
or die($db->error);
$gesteigereiner = $db->query("SELECT * FROM geliefert WHERE 1")
or die($db->error);
while ($zeile = $gesteigereiner->fetch_object()) {
$einer = $zeile->test1er;
$dreier = $zeile->test3er;
$sechser = $zeile->test6er;
$zwoelfer = $zeile->test12er;
}
$geliefert = array ( "nr" => $erg->num_rows,
"einer" => $einer,
"zwoelfer" => $zwoelfer);
print_r (json_encode($geliefert));
?>
Unfortunately, that's not how it works. But if I completely remove the result from the first DB query in the JS.
Many thanks in advance. I am grateful for any information, clarification and tips.
The problem was the following: "nr" => $erg->num_rows
To get what I wanted I had to save $erg->num_rows as a variable and to put the variable into the array.
So first step: $nr= $erg->num_rows;
Second step: "nr" => $nr

Navigate to another Page after appointment has been saved in kendo scheduler

I have got this scheduler displayed but not binding to tasks. The scheduler in the view. I am using java script method to read/create call to web api
#(Html.Kendo().Scheduler<TaskViewModel> ()
.Name("AppointmentSearchScheduler")
.DataSource(dataSource => dataSource
.Custom()
.Schema(schema => schema
.Model(m => {
m.Id(f => f.TaskID);
m.Field(f => f.OwnerID).DefaultValue(1);
}))
.Transport(new {
read = new Kendo.Mvc.ClientHandlerDescriptor() {
HandlerName = "customRead"
},
create = new Kendo.Mvc.ClientHandlerDescriptor() {
HandlerName = "customCreate"
}
})))
Below is javascript handler method I am not including create handler for brevity.
function customRead(options){
//get the selected Row of the kendo grid
var selectedRow = $("#locationgridKendo").find("tbody tr.k-state-selected");
var scheduler = $("#AppointmentSearchScheduler").data("kendoScheduler")
//get SelectedRow data
var rowData = $('#locationgridKendo').data("kendoGrid").dataItem(selectedRow);
if (rowData !== null) {
//Convert data to JSON
var rowDataJson = rowData.toJSON();
//extract the location ID
var locationId = rowDataJson.LocationID;
var CalenderweekStartDate = new Date().toISOString();
baseUrl = $('base').attr('href');
$.ajax({
url: baseUrl + 'Schedular/api/GetAppPerLocation?locationId=' + locationId + '&date=' + CalenderweekStartDate,
type: 'GET',
cache: false,
contentType: 'application/json',
success: function (result) {
//This method is hitting and i can see the data being returned
console.log('data is received : ' + result.Data);
options.success(result.Data);
},
error: function (xhr, status, error) {
//alert("Error: Search - Index.js - submitAppointment()");
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
}
Here is the web API controller called by making ajax call . The controller works perfectly when i used the basic read/create syntax . The ajax call complete and it does hit back the success method and returns the data but scheduler for some reason is not binded to incoming data. Here is my controller code
[HttpGet]
[Route("api/GetAppPerLocation")]
public DataSourceResult GetAppointmentPerLocation([ModelBinder(typeof(Usps.Scheduling.Web.ModelBinders.DataSourceRequestModelBinder))] DataSourceRequest request, int locationId, DateTime date) {
List < TaskViewModel > locationAvailableAppointmentList = new List < TaskViewModel > ();
locationAvailableAppointmentList = data.Select(appt => new TaskViewModel() {
TaskID = appt.ServiceAppointmentId,
Title = "Appointment Available",
Start = DateTime.SpecifyKind(appt.AppointmentBegin, DateTimeKind.Local),
End = DateTime.SpecifyKind(appt.AppointmentEnd, DateTimeKind.Local),
Description = "",
IsAllDay = false
}).ToList();
return locationAvailableAppointmentList.ToDataSourceResult(request);
}
For some reason the scheduler is not binding to incoming data . the incoming data works perfectly when i use a basic binding approach but not using transport . My goal for using this approach is once i am done with read(scheduler is not binding now) , on create I need to grab the ID of the newly created task returned by my controller and then pass that id to another mvc controller to render a confirmation page. Any other approach to accomplish this goal will be highly recommended.
Please excuse me for any mistake since this is my first question on stackoverflow.
My goal for using this approach is once i am done with read(scheduler is not binding now) , on create I need to grab the ID of the newly created task returned by my controller and then pass that id to another mvc controller to navigate render a confirmation page.
I speculated that read was not returning correct result so i had to fix that .Also my basic goal was redirection to another page after with appointment id and displaying a confirmation screen. This is how accomplished it . I understand this is not the best approach but it has been more than a year no body answered by question. Here is the approach i took .
I added a error to the model state like this in my controller
if (!String.IsNullOrEmpty(task.TaskID.ToString()))//redirect to confirmation page if the appointment was added to the queue
ModelState.AddModelError("AppointmentID", confirmationNumber);
then on client side i configure the error event on grid like this
.Events(
events => events.Error("RedirectToConfirmationPage"))
Here is the Javascript method details
function RedirectToConfirmationPage(e) {
console.log('RedirecToConfirmationPage method......');
console.log(e);
if (e.errors) {
var appointmentID = "";
// Create a message containing all errors.
$.each(e.errors, function (key, value) {
console.log(key);
if ('errors' in value) {
$.each(value.errors, function () {
appointmentID += this + "\n";
});
}
});
console.log('Newly Generated AppointmentID = ' + appointmentID);
// Redirect URL needs to change if we're running on AWS instead of on local developer machines
if (window.location.href.indexOf('/TestProject.Scheduling') > 1) {
window.location.href = '/Scheduler/AppointmentConfirmation?confirmationNumber=' + appointmentID
}
else {
window.location.href = '/Scheduler/AppointmentConfirmation?confirmationNumber=' + appointmentID
}
}
}
Hope it is helpfull to someone down the road.

How to use JSON.parse or eval () to display an array?

I have this code to save values ​​in json string in a session variable, which I call from ajax
I have the following code:
(function ($) {
Drupal.behaviors.MyfunctionTheme = {
attach: function(context, settings) {
$('.add-music').click(function () {
var songNew = JSON.stringify({
title: $(this).attr('data-title'),
artist: $(this).attr('data-artist'),
mp3: $(this).attr('href')
});
var songIE = {json:songNew};
$.ajax({
type: 'POST',
data: songIE,
datatype: 'json',
async: true,
cache: false
})
.done(
//this is the callback function, which will run when your POST request returns
function(postData){
//Make sure to test validity of the postData here before issuing the GET request
var session;
$.ajaxSetup({cache: false})
$.get('/getsession.php', function (getData) {
session = getData;
alert(session);
});
}
);
});
}}
})( jQuery );
I have the following code that works fine, I just printed the following alert:
["{\"title\":\"El Derecho de las Mujeres a La Comunicaci\u00f3n\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/Cun%CC%83aDerechoMujeresaLaComunicacion.mp3\"}","{\"title\":\"Objetivos del encuentro internacional de Derechos Humanos en el Bajo Aguan.\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/objetivos_del_encuentro_dh.mp3\"}"]
and I need to have something like this:
[
{
title:"Cro Magnon Man",
artist:"The Stark Palace",
mp3:"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"
},
{
title:"Hidden",
artist:"Miaow",
mp3:"http://www.jplayer.org/audio/mp3/Miaow-02-Hidden.mp3"
}
]
How I can work this data with jquery?
thank's
Assuming the data is stored in a variable called yourObject you can do:
var result = JSON.parse("["+yourObject[0]+"]");
Here is a working bin
This is what JSON.parse() was designed to do. Eval() is not the approach to use here. To clarify, JSON.parse() takes valid, appropriately escaped JSON strings and converts them into usable objects within Javascript. eval(), on the other hand, is designed to take strings and attempt to EXECUTE them as Javascript functions, objects, variables, etc.
Your sample input is actually an array of strings. You need to parse each element within the array as an object. Using jQuery:
var input = ["{\"title\":\"El Derecho de las Mujeres a La Comunicaci\u00f3n\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/Cun%CC%83aDerechoMujeresaLaComunicacion.mp3\"}","{\"title\":\"Objetivos del encuentro internacional de Derechos Humanos en el Bajo Aguan.\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/objetivos_del_encuentro_dh.mp3\"}"];
var resultArray = new Array();
for(var i = 0; i < input.length; i++){
var parsedElement = $.parseJSON(input[i]);
resultArray.push(parsedElement);
}
var display = JSON.stringify(jsonObject, undefined, 2); // indentation level = 2

Resources