Post JSON data from JSP using Javascript, AJAX - javascript

I want to post JSON data from JSP to Spring MVC Controller. For this, I am using Javascript Ajax. Please help me on this. I searched on net but could not get the solution for my problem.
When I execute the code I get bellow error:
Parse Error: Incorrect syntax Error Unexpected End of Inputand some Ids get printed in a console as below:person#35fcfbc0, person#35fcfbc5`
But I want the value of data1, data2 and data3 to be printed in console;
My Json String as below
{“persons”:
[
{“data1”:”1000”, “data2”:”false”,”data3”:”Holiday”},
{“data1”:”1000”, “data2”:”false”,”data3”:”Holiday”}
]
}
I am using below Javascript and Ajax to post Data
<script type="text/javascript">
$(document).ready(function()
{
var sJson
var ssJson
function dataRow(value1,value2,value3)
{
this.data1 = value1;
this.data2 = value2;
this.data3 = value3;
}
$('#help_button2').click(function()
{
// create array to hold your data
var dataArray = new Array();
var Vars
// iterate through rows of table
// * Start from '2' to skip the header row *
$(".case").each(function(i)
{
if (this.checked)
{
var Vars=i+1
//alert("Checkbox at index " + Vars + " is checked.");
var Vars1= $("#myTable tr:nth-child(" + Vars + ") td").eq(18).find('select').val()
//alert(Vars1)
//alert(Vars)
if (Vars1!="nooption")
{
dataArray.push
(
new dataRow
(
$("#myTable tr:nth-child(" + Vars + ") td").eq(1).html(),
$("#myTable tr:nth-child(" + Vars + ") td").eq(18).find('select').val(),
$("#myTable tr:nth-child(" + Vars + ") td").eq(19).find('select').val()
)
);
} //else {alert("Please Select Option for Error_NoError ")
//return false;
//}
}
});
ssJson1 = JSON.stringify({"persons" : dataArray });
alert(ssJson)
alert(ssJson1)
$.ajax({
url:'<%=webUrl%>/data/data',
type: 'POST',
dataType: 'json',
data:ssJson1,
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.data1 + " " + data.data2 + " " + data.data3);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er+ssJson);
}
});
});
});
</script>
My Pojo Class
public class Person implements Serializable{
private int data1;
private String data2;
private String data3;
public int getData1() {
return data1;
}
public void setData1(int data1) {
this.data1 = data1;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
public String getData3() {
return data3;
}
public void setData3(String data3) {
this.data3 = data3;
}
My Controller code:
#RequestMapping(value="/data",method=RequestMethod.POST)
public #ResponseBody void data(#RequestBody PersonList persons) throws
ParseException, IOException
{
List<Person> data1s=persons.getPersons();
System.out.println(data1s);
}

Related

DropDownList with java script

I hope developers can support me, I have minimal experience in the use of java script.
After investigating and several attempts, I was able to load a dropdownlist with data from a LINQ query and pass as a parameter the value of a textbox.
What I could not do is from the query Linq get two fields (Id and value) send them to the dropdownlist and show the value but after being able to use the Id of that field to be able to use it in a create, currently I can only show the value but I need the Id too.
View
#Html.TextBox("CP", "", new { #id = "txtCP", #onchange = "FillOption();", #placeholder = "Codigo Postal" })
#Html.DropDownList("Asentamientos", ViewBag.Drop as List<SelectListItem>)
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}
</script>
Controllers
public ActionResult Index()
{
List<SelectListItem> drop = new List<SelectListItem>
{
};
ViewBag.Drop = drop;
return View();
}
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select p.Asentamiento).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
I think of something like
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
but I do not know how the id and the value would be handled
Thanks
If I understand your question correctly, I think you need to name the fields of the object you are creating with the Linq expression, so that it would look something like this:
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { id = p.IdCodigoPostal, value = p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
Here are a few examples: https://code.msdn.microsoft.com/LINQ-to-DataSets-09787825#SelectAnonymousTypes1
Then you could access those fields from you javascript with data[i].id and data[i].value.
I hope this helps.
I suspect your issue is around pulling the data from the API result. You're setting the a new property in the ViewBag, then returning the ViewBag property. This really shouldn't be required, and you should instead just return your list, list so (Note: and SelectItemList has a property called "Items" which contains all items you've added):
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
This should return just a nice list of ListItems. You could also just change your jQuery to loop through the items property, like so:
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.Items.length; i++) {
$('#Asentamientos').append('<option value=' + data.Items[i].Value + '>' + data.Items[i].Text + '</option > ');
}
}
});
}
</script>
Thanks to all, the code works as follows
Controller
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { Value = p.IdCodigoPostal, Text= p.Asentamiento }).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}

error when updating records in web api.

After selecting the department to update.
a submit button is click.
this error appear
{"readyState":4,"reponseText":"{\"Message\":\"Object reference not set to an instance of an object.\",\"StackTrace\":\" at WebService.yearEndClosing(String strDate, String endDate, String cond, String cal, String entryUser)in WebService.cs:line 390\",\"ExecptionType\":\"System.NullReferenceException\"}","responseJSON":{"Message":"Object reference not set to an instance of an object.","StackTrace":" at WebService.yearEndClosing(String strDate, STring endDate, String cond, String val, String entryUser) in WebService.cs:line 390\",\"ExecptionType\":\"System.NullReferenceException\"},"status":500, "statusText":"Internal Server Error"}
The code for submit button.
//Function for submit button event
$(function () {
$("#btnSubmit").bind("click", function (e) {
if (confirm("Click [OK] to proceed on forfiet the leave of selected department.")) {
var selectedDept = new Array();
var i = 0;
//Get checked checkbox in the list
$(".bodyfont input").each(function () {
if ($(this).is(":checked")) {
selectedDept[i] = $(this).val();
i++;
}
});
var ddlVal = $("[id*='ddlVal']").val();
var endDate = $("[id*='tEnd']").val();
var strDate = $("[id*='tStart']").val();
if (strDate != "" && endDate !="" && i > 0) {
ShowLoading();
$.ajax({
type: "POST",
url: "WebService.asmx/yearEndClosing",
data: "{ 'strDate':'" + strDate + "', 'endDate':'" + endDate +
"', 'cond':'" + ddlVal + "', 'val':'" + JSON.stringify(selectedDept) +
"', 'entryUser':'" + getLoginID() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var json_obj = data.d;//parse JSON
if (json_obj != null) {
if (json_obj.length == 0) {
alert("All selected department/employee in date range are closed!")
}
else {
//deserialize json object to string
var table = "";
$("#tblNotClose tr").remove();
$.each(json_obj, function (index, YrEndClosing) {
table += "<tr><td>" + YrEndClosing.empID + "</td><td>" + YrEndClosing.empName + "</td></tr>";
});
if (table != "") {
header = "<tr><th>Emp ID</th><th>Emp No</th></tr>";
$("#tblNotClose").append(header);
$("#tblNotClose").append(table).removeClass("hidden");
}
$("#modalResult").modal('show');
}
}
else {
alert("Error on closing");
}
ShowDetails();
},
error: function (error) {
alert(JSON.stringify(error));
}
});
e.preventdefault;
}
else {
alert("Due Date is not seleceted to forfiet the leave");
}
}
});
});
And it is this alert(JSON.stringify(error)); which display the error.
Now lets breakdown the issue. base on my understanding
the error is telling that there is something going on with the parameter in
yearEndClosing(String strDate, String endDate, String cond, String cal, String entryUser) which is on line 390
here i the code
[WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<YrEndClosing> yearEndClosing(string strDate, string endDate, string cond, string val, string entryUser)
{
eLeaveModule em = new eLeaveModule();
JavaScriptSerializer json = new JavaScriptSerializer();
List<string> arrayString = json.Deserialize<List<string>>(val);
DateTime dtStr = Convert.ToDateTime(strDate, CultureInfo.GetCultureInfo("en-us").DateTimeFormat);
DateTime dtEnd = Convert.ToDateTime(endDate, CultureInfo.GetCultureInfo("en-us").DateTimeFormat);
List<YrEndClosing> result = em.yearEndClosing(dtStr, dtEnd, cond, arrayString, entryUser);
if (result.Count > 0)
{
string relDate = Regex.Replace(string.Format("{0:s}", DateTime.Now), #"[^0-9a-zA-Z]+", "");
string subPath = #" C:\webOutput\eHRMS\Closing\";
bool exists = System.IO.Directory.Exists(subPath);
if (!exists)
System.IO.Directory.CreateDirectory(subPath);
using (StreamWriter writer = new StreamWriter(subPath + "ClosingList" + relDate + ".txt"))
{
for (int i = 0; i < result.Count; i++)
{ writer.WriteLine(result[i].empID + "-" + result[i].empName); }
}
}
return result;
}
USEFUL INFORMATION
The code work in server 2
The same code not working in server 1 (current issue)
No error when running on local by visual studio for web
May i know what could be the issue.
I am still trying to even locate where the possible issue is at.

Jquery progress bar while uploading record into database in java

I have thousands of record which are stored in a excel sheet and I need to upload those records into database, And currently I am using Spring controller class for upload, And inside my class I use simple BufferedOutputStream and FileReader classes, So my requirement is I need to show a Jquery progress-bar including percentages while uploading my data into database.
Link here.
My sample code.
String rootPath = request.getSession().getServletContext().getRealPath("/");
File dir = new File(rootPath + File.separator + "uploadedfile");
if (!dir.exists()) {
dir.mkdirs();
}
File serverFile = new File(dir.getAbsolutePath() + File.separator + form.getEmpFile().getOriginalFilename());
try {
try (InputStream is = form.getEmpFile().getInputStream();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
int i;
//write file to server
while ((i = is.read()) != -1) {
stream.write(i);
}
stream.flush();
}
}
catch (IOException e) {
model.addAttribute("msg", "failed to process file because : " + e.getMessage());
}
String[] nextLine;
try (FileReader fileReader = new FileReader(serverFile); CSVReader reader = new CSVReader(fileReader, ';', '\'', 1);) {
while ((nextLine = reader.readNext()) != null) {
for (int i = 0; i < nextLine.length; i++) {
nextLine[i] = nextLine[i].trim();
if (!nextLine[i].equals("")) {
String[] data = nextLine[i].split(",");
Maybe this can help:
1- Controller side :
public class ExtractController {
********
// I created a global variable here
int percentage = 0;
Workbook workbook;
#RequestMapping(value ="/uploadExcel", method = RequestMethod.POST)
public #ResponseBody String uploadExcel(Model model, #RequestParam("excelfile") MultipartFile excelfile,
HttpServletResponse response) {
**********
try {
int i = 0;
*********
while (i <= worksheet.getLastRowNum()) {
percentage = Math.round(((i * 100) / worksheet.getLastRowNum()));
Row row = worksheet.getRow(i++);
}
*********
}catch (Exception e) {
e.printStackTrace();
}
return "extract";
}
#RequestMapping(value = "/getpercent", method = RequestMethod.GET)
public #ResponseBody String getPerc(#RequestParam("param") String param) {
************
// you return the value of the global variable when the action is called
return percrentage;
}
}
1- JavaScript side :
$.ajax({
url : 'uploadExcel',
type : 'POST',
data : new FormData(this),
beforeSend : function() {
$('#valid').attr("disabled", true);
// I call my loop function
loop();
},
success : function(data) {
$('#valid').attr("disabled", false);
}
});
function loop() {
$.ajax({
url : 'getpercent',
type : 'GET',
success : function(response) {
count = response;
// this function updates my progress bar with the new value
change(count);
*********
}
});
var time = 2000;
if(count < 100){
setTimeout(loop, time);
}
}
;

Refresh model after post-request in ASP.MVC

I'm developping a webApp with MVC.
I have a view with cirkles displaying a value and a slider,
when you slide the cirkles need to display the new value.
I send the new value with a POST from my AJAX call to the controller,
which does a minor calculation with the value and give it back to the view
so the cirkles can display the updated value.
However my view still keeps using the startvalue.
#model UGT.UI.Web.MVC.Models.BelastingViewModel
<script language="JavaScript">
var config1 = liquidFillGaugeDefaultSettings();
#{
teller = 1;
string naam_var = null;
foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting)
{
naam = "fillgauge" + teller;
naam_var = "gauge" + teller;
#: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1);
teller++;
}
}
function toonCirkels() {
#{
teller = 1;
naam = "fillgauge" + teller;
string naam_var2 = null;
foreach (KeyValuePair<UGT.BL.Domain.BegrotingPackage.Categorie, double> cat in Model.Belasting)
{
naam_var2 = "gauge" + teller;
// #: gauge1.update("#Html.DisplayFor(modelItem => cat.Value)");
// #: var #naam_var = loadLiquidFillGauge("#naam", "#Html.DisplayFor(modelItem => cat.Value)", config1);
// #: #naam_var2.update("#Html.DisplayFor(modelItem => cat.Value)");
teller++;
}
//#:gauge1.update("500");
}
}
public class BelastingsController : Controller
{
private BegrotingsManager begrotingsManager = new BegrotingsManager();
private int gemeenteId = 54;
private double loon = 200;
private BelastingViewModel belastingen = new BelastingViewModel();
// GET: Belastings
public ActionResult Index()
{
var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId);
belastingen.Belasting = belasting;
UpdateModel(belastingen);
return View(belastingen);
}
[HttpPost]
public ActionResult Index(String loon)
{
this.loon = Double.Parse(loon);
var belasting = begrotingsManager.GetBelastingGebruiker(this.loon, gemeenteId);
belastingen.Belasting = belasting;
UpdateModel(belastingen);
return new HttpStatusCodeResult(HttpStatusCode.OK);
// return RedirectToAction("Index");
}
namespace UGT.UI.Web.MVC.Models
{
public class BelastingViewModel
{
public IDictionary<Categorie, double> Belasting { get; set; }
}
}
d3.selectAll('.range').on('change', function () {
this.value = parseInt(this.value);
if (this.value < 0) this.value = 0;
else if (this.value > 5000) this.value = 5000;
var loon = this.value;
var loonString = "€" + loon;
d3.select('.range_value').html(loonString);
sendLoon(loon, loonString);
});
}
function sendLoon(loon, loonString) {
$.ajax({
contentType: "application/json; charset=utf-8",
url: "/Belastings",
type: "POST",
data: JSON.stringify({ "loon": loon }),
success: function () {
// window.location.reload();
toonCirkels();
},
error: function () { }
});
}
The success of your Ajax call calls 'toonCirkels' which only contains razor generated code which is filled on page load. The content of this method never changes as it contains ONLY razor generated code and thus will always have the same logic with the same values.

how to delete data from database using mvc3?

I am new to Json datatype. how to retrive it.. please look at the code below.
This is my Javascript code:
function fnDeleteSelected() {
var count_checked = $("[name = 'myChkBox[]']:checked").length;
var arrayOfID = [];
$(':[name = "myChkBox[]"]:checked').each(function () {
arrayOfID.push($(this).val());
});
var test = JSON.stringify(arrayOfID);
alert(test);
if (count_checked == 0) {
alert("Please Select a Student to delete");
return false;
}
else {
var confirmDel = confirm("Are you sure you want to delete this?");
if (confirmDel == true) {
jQuery.ajax({
url: baseUrl + "DeleteSelected/",
type: 'Post',
dataType: 'Json',
data: { Parameters: test },
success: function (msg) {
jQuery("input:checkbox:checked").parents("tr").remove();
}
});enter code here
}
}
}
here data send to controller is parameters where parameters = ["143","144","145"]
and my controller is: where Parameters is passed as "[\"143\",\"144\",\"145\"]"my question is how to parse the Parameters so that it can be embedded in sql statement
public JsonResult DeleteSelected(string [] Parameters)
{string strConn = "Data Source=localhost;Initial Catalog=Information;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(strConn);
string strSql = "DELETE FROM dbStudent where ID in";
SqlCommand myCommand = new SqlCommand(strSql, conn);
try
{
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Json(Parameters, JsonRequestBehavior.AllowGet);
}
what should be there in strSql..??
You can change your ajax post to be like that: (the contentType is important)
jQuery.ajax({
url: baseUrl + "DeleteSelected/",
type: 'Post',
dataType: 'json',
data: JSON.stringify(arrayOfID),
contentType: 'application/json; charset=utf-8',
success: function (msg) {
jQuery("input:checkbox:checked").parents("tr").remove();
}
});
and your action method to be like that
public JsonResult DeleteSelected(int[] Parameters)
{
string strConn = "Data Source=localhost;Initial Catalog=Information;Integrated Security=SSPI;";
SqlConnection conn = new SqlConnection(strConn);
var strSql = "DELETE FROM dbStudent where ID IN (" + String.Join(",", Parameters) + ")";
SqlCommand myCommand = new SqlCommand(strSql, conn);
try
{
conn.Open();
myCommand.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Json(Parameters, JsonRequestBehavior.AllowGet);
}
You can convert your array to int array
int[] myInts = Parameters.Select(int.Parse).ToArray();
Then
var query = "DELETE FROM dbStudent where ID IN (" +
String.Join(",", myInts ) + ")";

Categories