I am passing an array from servlet through ajax call. But when I am trying to get the same in servlet side, I am getting null pointer exception. I tried using one of the examples given in SO. Since I'm a newbie, any help would be appreciated!
$.ajax({
url : 'insertserv1',
type: 'POST',
dataType: 'json',
data: {tablearray:tablearray} ,
contentType: 'application/json',
mimeType: 'application/json',
success : function(data) {
alert('Hi');
}
});
// to get data from inspection table
{ var tablearray = [];
$("#tab_logic tr.data").map(function (index, tr) {
$(this).find('td').each(function(){
var $data = $(this).html();
if($(this).find("select").length > 0) {
var $x = $(this).find("select").val();
}else{
var $x = $(this).find("input[type='text']").val();
}
tablearray.push($x);
});
});
}
String[] tablearray = request.getParameterValues("tablearray[]");
for (int i = 0; i < tablearray.length; i++) {
System.out.println(InspTableArray[i]);
}
If I have understood correctly, this is what you would be looking for:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
JSONObject jObj = null;
StringBuilder sb = new StringBuilder();
BufferedReader br = request.getReader();
String str = null;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
try
{
jObj = new JSONObject(sb.toString()); //This is your JSON data.
}
catch (JSONException e)
{
e.printStackTrace();
}
}
Related
Function which is use to take input data from HTML
function saveclickdata()
{
var allData = {
InvNo:document.getElementById('TbInvNo').value,
GrossSale:document.getElementById('TbOrderTotal').value,
discount:document.getElementById('TbDiscount').value,
CusCash:document.getElementById('TbCash').value,
CusBal:document.getElementById('TbBalance').value,
};
$.ajax({
url: "\Controllers\POSController.cs\SaveData",
type: 'POST',
data: allData,
success: function (res) {
alert("success");
},
error: function (err) {
alet("Error");
}
});
Api which is in controller used to post data
[HttpPost]
JsonResult SaveData(POSMater collection)
{
if (collection.InvNo.ToString() == null)
{
var LocalInvNo = (from b in db.TblPOSMasters select b).FirstOrDefault();
int MaxInvNo = Convert.ToInt32(LocalInvNo) + 1;
collection.InvNo = MaxInvNo;
TblPOSMaster master = new TblPOSMaster();
master.InvNo = collection.InvNo;
master.AddBy = 1;
master.AddDate = DateTime.Now;
master.CashStatus = "A";
master.CompId = 1;
//master.CreditAmt = collection.CreditAmt;
//master.CrCardNo = collection.CrCardNo;
master.CusCash = collection.CusCash;
master.CusId = 1;
master.GrossSale = collection.GrossSale;
db.TblPOSMasters.Add(master);
db.SaveChanges();
}
else
{
return Json(collection);
}
return Json(collection);
}
What should i do? My html button working properly but still not able to call api
I think you ought to use forward slashes (/) in your URL
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);
}
}
;
I'm new to the world of ajax requests and asp.net. I'm trying to send an ajax request to aspx page. When I'm debugging the server side it seems to be ok, but the response printing the error message?
I tried to change the Response.ContentType but it didn't solve my problem. Any suggestions?
Here is my javascript code:
function onclick(){
$.ajax({
url: "SandaAJAXRequests.aspx",
type: "post",
data: JSON.stringify({ "first": "getevent","second":"data" }),
dataType: 'json',
success:
function (response)
{
roundNumber = 1;
numberofblackwins = 0;
numberofredwins = 0;
ifBattleIsOver = false;
$("#round").text(roundNumber);
var result = response.split(",");
name1 = result[1];
name2 = result[2];
var r = confirm("Is " + name1 + " the black competitor?");
if (r == true) {
$("#black_competitor_name").text(name1);
$("#red_competitor_name").text(name2);
}
else {
$("#black_competitor_name").text(name2);
$("#red_competitor_name").text(name1);
}
},
error: function (xhr) {
alert("Problem sending data to the server");
}
});
}
Here is my server side:
protected void Page_Load(object sender, EventArgs e)
{
string jsonString = String.Empty;
Request.InputStream.Position = 0;
using (var inputStream = new StreamReader(Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
string data = jsonString.Replace("\\", "");
char[] seperators = { ':', ',', '"' };
string[] a = data.Split(seperators);
string t = a[4];
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
object serJsonDetails = javaScriptSerializer.Deserialize(jsonString, typeof(object));
string requestType = serJsonDetails.ToString();
switch (t)
{
case "getevent":
SandaEvent current = (SandaEvent)Application["CurrentEvent"];
Response.ContentType = "text/plain";
String response = current.id + "," + current.name1 + "," + current.name2;
Response.Write(response);
Response.End();
break;
}}
You are missing contentType in $.ajax({});
Content-type: application/json; charset=utf-8
is necessary when you are a doing a post using $.ajax({})
Content-type: application/json; charset=utf-8 designates the content to be in JSON format, encoded in the UTF-8 character encoding.
This is my action in controller. Which return a List> converting into DataSourceResult.and also Serializing into Json.
[HttpPost]
public ActionResult GetMissingShiftData([DataSourceRequest]DataSourceRequest request)
{
DataTable dtResponse = new DataTable();
var dynamicList = new List<dynamic>();
var myMainList = new List<List<dynamic>>();
List<DataSourceResult> viewResultList = new List<DataSourceResult>();
string RigNumber = string.IsNullOrWhiteSpace( resultData.Filter.SelectedRig.RigNumber) || resultData.Filter.SelectedRig.RigNumber == "ALL" ? "" : resultData.Filter.SelectedRig.RigNumber;
DataSet response = MissingShiftsReportData.GetData(Convert.ToDateTime(resultData.Filter.DateStart), Convert.ToDateTime(resultData.Filter.DateEnd), ConnString, RigNumber);
foreach (DataTable dt in response.Tables)
{
dtResponse = dt;
string[] columnNames = dtResponse.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow dr in dtResponse.Rows)
{
dynamic myObj = new ExpandoObject();
var p = myObj as IDictionary<string, object>;
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i = 0; i < columnNames.Length; i++)
{
string name = dr.Table.Columns[i].ColumnName.Replace(" ", String.Empty);
name = name.Replace(".", String.Empty);
name = name.Replace("(", String.Empty);
name = name.Replace(")", String.Empty);
name = rgx.Replace(name, "");
p[name] = dr[i];
}
dynamicList.Add(p);
}
myMainList.Add(dynamicList);
}
DataSourceResult viewResult = myMainList.ToDataSourceResult(request);
string JsonViewData = JsonConvert.SerializeObject(viewResult.Data);
return new ContentResult { Content = JsonViewData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
}
And this is the async call I am doing with Jqery.while I am trying to bind a data source it shows "data[0].Data" is "undefined". How can I make use of 'data'.
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var list = data[0].Data;
var dataSource = new kendo.data.DataSource({
data: data[0].Data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
You are serializing an array (the Data property) and don't need to use the Data field at the client-side:
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var dataSource = new kendo.data.DataSource({
data: data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
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 ) + ")";