ajax and select element dropdown - html

hello guys please i have an issue with ajax i have this function that fetch data from jsp but when i add a new data to the database and call the function again it duplicates the data unless i refresh the page which i don't want users to do
<script>
search1();
function search1(){
$.ajax({
type:"GET",
url:"drop.jsp",
dataType:'JSON',
data:{"title":'title'},
success:function(data){
console.log(data);
for(var i = 0; i< data.length; i++){
$('#title').append($("<option/>",
{
text: data[i].area,
}));
}
},
error(err){
alert("error")
}
});
}
</script>
it fetch's data as i want but when i call that same function with another function it duplicate the dropdown data the second function is below
<script>
function title2(){
$.ajax({
type:"POST",
url:"drop.jsp",
data:{"title1":$("#title1").val()},
success:function(msg){
var obj = JSON.parse(msg);
search1();
},
error(err){
alertify.error('Error');
}
})
}
</script>
and the jsp code is
String title = request.getParameter("title");
String marital = request.getParameter("marital");
String minis = request.getParameter("minis");
String occu = request.getParameter("occu");
String job = request.getParameter("job");
String bs = request.getParameter("bs");
String class1 = request.getParameter("class1");
String course = request.getParameter("course");
JSONArray list =new JSONArray();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/cop","root","root");
Statement st = con.createStatement();
if(title != null){
String sql = "Select * from title";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
JSONObject obj = new JSONObject();
String area = rs.getString("title");
obj.put("area", area);
list.add(obj);
}
out.println(list.toJSONString());
out.flush();
}
and the output is in the image
the output

Related

trying to upload Image in mvc web api project using jquery ajax only

I am trying to upload Image but upon running my application my Image parameter is passing null, and I don't know why it is not picking up the file I attached
but in my browser console when I check my image file object that if it is attached or not, it shows that it does attach
but in my controller its passing null
my ajax code where I am passing the image file object,
$('.empOfficialDetails').click(function (ev) {
ev.preventDefault();
var data = new Object();
data.UserName = $('#username').val();
data.UPassword = $('#userpass').val();
data.OfficialEmailAddress = $('#officialemail').val();
data.Departments = $('#departments :selected').text();
data.Designation = $('#designation :selected').text();
data.RoleID = $('#role').val();
data.Role = $('#role :selected').text();
data.ReportToID = $('#reportToID').val();
data.ReportTo = $('#reportTo :selected').text();
data.JoiningDate = $('#joindate').val();
data.IsAdmin = $('#isAdmin :selected').val() ? 1 : 0;
data.IsActive = $('#isActive :selected').val() ? 1 : 0;
data.IsPermanent = $('#isPermanent :selected').val() ? 1 : 0;
data.DateofPermanancy = $('#permanantdate').val();
data.HiredbyReference = $('#hiredbyRef :selected').val() ? 1 : 0;
data.HiredbyReferenceName = $('#refePersonName').val();
data.BasicSalary = $('#basicSalary').val();
data.CurrentPicURL = $('.picture')[0].files; //this is my image file object
//data.EmpID = $('.HiddenID').val();
if (data.UserName && data.UPassword && data.OfficialEmailAddress && data.Departments && data.Designation && data.Role && data.IsAdmin && data.IsPermanent) {
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(data),
enctype: 'multipart/form-data',
beforeSend: function () {
$("#dvRoomsLoader").show();
},
complete: function () {
$("#dvRoomsLoader").hide();
},
success: function (data) {
var ID = parseInt(data);
if (ID > 0) {
//var id = data;
$(".HiddenID").val(data);
//var id = $(".HiddenID").val();
$('#official').css('display', 'block');
$('#official').html("Employees Official details added successfully...!");
$('#official').fadeOut(25000);
$("#dvRoomsLoader").show();
$('.empOfficialDetails').html("Update <i class='fa fa-angle-right rotate-icon'></i>");
}
else {
$('#official').find("alert alert-success").addClass("alert alert-danger").remove("alert alert-success");
}
},
error: function (ex) {
alert("There was an error while submitting employee data");
alert('Error' + ex.responseXML);
alert('Error' + ex.responseText);
alert('Error' + ex.responseJSON);
alert('Error' + ex.readyState);
alert('Error' + ex.statusText);
}
});
}
return false;
});
but in controller on running the code it passes null
public void EmployeeImage(HttpPostedFileBase file)
{
var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" };
var fileName = Path.GetFileName(file.FileName);
var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)
byte[] bytes;
using (BinaryReader br = new BinaryReader(file.InputStream))
{
bytes = br.ReadBytes(file.ContentLength);
}
if (allowedExtensions.Contains(ext)) //check what type of extension
{
string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension
string myfile = name + "_" + ext; //appending the name with id
var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/assets/img/profiles/employeeImages"), myfile); // store the file inside ~/project folder(Img)
file.SaveAs(path);
}
}
public int Emp_OfficialDetails(Employee emp)
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AmanraHRMS"].ConnectionString);
var con = DB.getDatabaseConnection();
SqlCommand com = new SqlCommand("sp_InsEmpOfficialDetails", con);
com.CommandType = CommandType.StoredProcedure;
#region Employee Official Details Insert Code block
com.Parameters.AddWithValue("#UserName", emp.UserName);
com.Parameters.AddWithValue("#pass", emp.UPassword);
com.Parameters.AddWithValue("#OfficialEmailAddress", emp.OfficialEmailAddress);
com.Parameters.AddWithValue("#Department", emp.Departments);
com.Parameters.AddWithValue("#Role", emp.Role);
com.Parameters.AddWithValue("#IsAdmin", Convert.ToBoolean(emp.IsAdmin));
com.Parameters.AddWithValue("#Designation", emp.Designation);
com.Parameters.AddWithValue("#ReportToID", emp.ReportToID);
com.Parameters.AddWithValue("#ReportTo", emp.ReportTo);
com.Parameters.AddWithValue("#JoiningDate", Convert.ToDateTime(emp.JoiningDate));
com.Parameters.AddWithValue("#IsPermanent", Convert.ToBoolean(emp.IsPermanent));
com.Parameters.AddWithValue("#DateofPermanancy", Convert.ToDateTime(emp.DateofPermanancy));
com.Parameters.AddWithValue("#IsActive", Convert.ToBoolean(emp.IsActive));
com.Parameters.AddWithValue("#HiredbyReference", Convert.ToBoolean(emp.HiredbyReference));
com.Parameters.AddWithValue("#HiredbyReferenceName", emp.HiredbyReferenceName);
com.Parameters.AddWithValue("#BasicSalary", emp.BasicSalary);
com.Parameters.AddWithValue("#CurrentPicURL", emp.CurrentPicURL);
#endregion
var file = emp.CurrentPicURL;
EmployeeImage(file);
var ID = com.ExecuteScalar();
com.Clone();
return Convert.ToInt32(ID);
}
and in my model class my Image datatype is as
public HttpPostedFileBase CurrentPicURL { get; set; }
I have no Idea what I am doing wrong If anyone who knows about this, your help is highly appreciated my friend
You can't use JSON.stringify to upload a file via AJAX. You need to use the FormData class.
Sending files using a FormData object | MDN
const data = new FormData();
data.append("UserName", $('#username').val());
data.append("UPassword", $('#userpass').val());
...
const file = $('.picture')[0].files[0];
data.append("CurrentPicURL", file, file.name);
...
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
data: data,
processData: false,
contentType: false,
beforeSend: function () {
...
NB: Unless you need to support Internet Explorer, you might want to use the Fetch API instead of AJAX. This can be much simpler, particularly when combined with async and await.

mvc controller json return

i want to return an image in base64 from my controller to view using json.
public JsonResult changeProfile()
{
var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
TBL_User item = _context.TBL_User.Find(userID);
UserModel model = new UserModel();
model.UserID = userID;
model.BinaryPhoto = item.BinaryPhoto;
return Json(new
{
??????????????'
},
JsonRequestBehavior.AllowGet);
}
what can i put there to return my image and display in the view?
thanks
Update controller
public JsonResult changeProfile()
{
var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
TBL_User item = _context.TBL_User.Find(userID);
UserModel model = new UserModel();
model.UserID = userID;
model.BinaryPhoto = item.BinaryPhoto;
var base64 = Convert.ToBase64String(model.BinaryPhoto);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
return Json(new
{
Image = imgsrc
},
JsonRequestBehavior.AllowGet);
}
Update src for image in ajax success
$.ajax({
url: "/changeProfile",
success: function(data) {
$(".img-circle").attr('src', data.Image);
}
});

Showing a file tree with parent relation with data from a sql query

I'm currently working on my final project for my university, but unfortunately I stopped in this part, because I tried several things like trying to pass a variable with a list inside from servlet to a jsp file to use in a json function from a project https://gist.github.com/smrchy/7040377 and render a tree.
Right now my project I render directly from a sql query which is not ordered and don't show the relationship.
right now
I created a constructor to create a array or list with the values and parameters in java class, when i try to send it through session or parameter doesn't work...
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession sessao = request.getSession(false);
response.setContentType("application/json");
try {
FicheiroDAO x = new FicheiroDAO();
x.imprime();
List<Ficheiro> lista = x.getLista();
JSONObject json;
JSONArray addresse = new JSONArray();
JSONObject listas = new JSONObject();;
try {
for (int i = 0; i < lista.size(); i++) {
json = new JSONObject();
json.put("id", lista.get(i).getId());
json.put("parentid", lista.get(i).getPasta());
json.put("name", lista.get(i).getNome());
addresse.put(i, json);
}
} catch (JSONException jse) {
}
String s = addresse.toString();
request.setAttribute("listagem", s);
sessao.setAttribute("listagem", s);
sessao.setAttribute("teste", "POST");
request.setAttribute("teste", "POST");
request.getRequestDispatcher("files.jsp").forward(request, response);
My sql engine is Mysql and the image showing the table of the files is on my comment where the id_pasta it's the parent of the file
So I stopped trying that way and right now I'm trying to run the select in the JSP using java JSTL to create the array.
So I need some help from you experts to know the best way and easier to show correctly what I pretend.
Many thanks and regards!
EDITED FOR MORE INFO:
The way I want to show is like this
one
two
four
three
five
six
So in that way I can display in a easy way what I want...
Edited:
Failed try to save the information from result set query, any ideas?
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://192.168.1.98:3306/repual", "admin", "123");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select id_fich, nome_fich, tipo_fich, id_pasta from repual.ficheiro join repual.permissoes where (id_fich=id_ficheiro) and (id_utilizador='26' or dep like ('%'+'1'+'%')) and id_pasta!=2 order by nome_fich");
Gson gson = new Gson();
Map<String, String> objeto = new HashMap<String, String>();
ArrayList data = new ArrayList();
while (rs.next())
{
Map<String, String> lv = new HashMap<String, String>();
lv.put("id", rs.getString("id_fich"));
lv.put("parentid", rs.getString("id_pasta"));
lv.put("name", rs.getString("nome_fich"));
data.add(lv);
}
//create 'dataMap' map object to make a complete FC datasource.
Map<String, String> dataMap = new LinkedHashMap<String, String>();
/*
gson.toJson() the data to retrieve the string containing the
JSON representation of the data in the array.
*/
JsonObject object = new JsonObject();
String json = gson.toJson(data);
con.close();
New update:
I changed the way to do, and I'm now trying this new way but unfortunately I can't get the array from the "scriptlet" into javascript to use in the methods already created.
Here is the code, can someone help me how Can I use the Json array in json code (javascript)?
I created the variable status to receive the array but no luck even testing the string sd to receive the value, so my idea was use the the array "arr" created from resultset to replace the array "sqlquery" manually created in javascript and use the functions to output the elements..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<%#page import="org.json.JSONException"%>
<%#page import="org.json.JSONArray"%>
<%#page import="org.json.JSONObject"%>
<%#page import="java.sql.*" %>
<%#page import="java.util.*" %>
<%#page import="com.google.gson.*" %>
<%# taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%# taglib uri = "http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
HttpSession sessao = request.getSession(false);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String myVar = "sadsa";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/repual", "root", "admin");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select id_fich, nome_fich, tipo_fich, id_pasta from repual.ficheiro join repual.permissoes where (id_fich=id_ficheiro) and (id_utilizador='26' or dep like ('%'+'1'+'%')) and id_pasta!=2 order by nome_fich");
Gson gson = new Gson();
JSONArray arr = new JSONArray();
while (rs.next())
{
JSONObject obj = new JSONObject();
obj.put("id", rs.getString("id_fich"));
obj.put("parentid", rs.getString("id_pasta"));
obj.put("name", rs.getString("nome_fich"));
arr.put(obj);
}
con.close();
st.close();
out.println(arr.toString());
String sd = "asdsad";
%>
<h1>SQL Query to Tree</h1>
<h3>The SQL query</h3>
select id_fich, nome_fich, tipo_fich, id_pasta from ficheiro join permissoes where (id_fich = id_ficheiro) and (id_utilizador = '26' or dep like ('%' + '1' + '%')) and id_pasta != 2 order by nome_fich
<pre id="sqlquery"></pre>
<h3>The sorted query</h3>
<pre id="sortedquery"></pre>
<h3>The Tree</h3>
<pre id="tree"></pre>
<h3>HTML List</h3>
<div id="htmllist"></div>
<button type="button" onclick="downloadficheiro();">sadsaad</button>
<button type="button" onclick="downloadficheir();">post</button>
<!-- jQuery 3 -->
<script src="bower_components/jquery/dist/jquery.min.js"></script>
</body>
</html>
<script type="text/javascript">
var _queryTreeSort = function (options) {
var cfi, e, i, id, o, pid, rfi, ri, thisid, _i, _j, _len, _len1, _ref, _ref1;
id = options.id || "id";
pid = options.parentid || "parentid";
ri = [];
rfi = {};
cfi = {};
o = [];
_ref = options.q;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
e = _ref[i];
rfi[e[id]] = i;
if (cfi[e[pid]] == null) {
cfi[e[pid]] = [];
}
cfi[e[pid]].push(options.q[i][id]);
}
_ref1 = options.q;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
e = _ref1[_j];
if (rfi[e[pid]] == null) {
ri.push(e[id]);
}
}
while (ri.length) {
thisid = ri.splice(0, 1);
o.push(options.q[rfi[thisid]]);
if (cfi[thisid] != null) {
ri = cfi[thisid].concat(ri);
}
}
return o;
};
var _makeTree = function (options) {
var children, e, id, o, pid, temp, _i, _len, _ref;
id = options.id || "id";
pid = options.parentid || "parentid";
children = options.children || "children";
temp = {};
o = [];
_ref = options.q;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
e = _ref[_i];
e[children] = [];
temp[e[id]] = e;
if (temp[e[pid]] != null) {
temp[e[pid]][children].push(e);
} else {
o.push(e);
}
}
return o;
};
var _renderTree = function (tree) {
var e, html, _i, _len;
html = "<ul>";
for (_i = 0, _len = tree.length; _i < _len; _i++) {
e = tree[_i];
html += "<li>" + e.name;
if (e.children != null) {
html += _renderTree(e.children);
}
html += "</li>";
}
html += "</ul>";
return html;
};
sqlquery = ([
{"id": "456", "parentid": "123", "name": "Dogs"},
{"id": 214, "parentid": 456, "name": "Labradors"},
{"id": 123, "parentid": 0, "name": "Mammals"},
{"id": 810, "parentid": 456, "name": "Pugs"},
{"id": 919, "parentid": 456, "name": "Terriers"}
]);
var status = document.getElementsByName("arr");
$('#sqlquery').html(JSON.stringify(sqlquery, true, 2));
sortedquery = _queryTreeSort({q: sqlquery})
$('#sortedquery').html(JSON.stringify(sortedquery, true, 2));
tree = _makeTree({q: sortedquery})
$('#tree').html(JSON.stringify(tree, true, 2));
htmllist = _renderTree(tree)
$('#htmllist').html(htmllist);
function downloadficheir() { // Eliminar uma pasta ou ficheiro
var f = document.form;
f.method = "post";
f.action = 'listaficheiro ';
f.submit();
}
function downloadficheiro() { // Eliminar uma pasta ou ficheiro
var f = document.form;
f.method = "get";
f.action = 'abreficheiro';
f.submit();
}
foo();
function foo()
{
var value = $('#sd').val();
alert(value);
}
</script>

how to pagination JSONResult in MVC with ajax url data loading?

I have a problem in pagination with a json result data in MVC.
Below code is my ajax data loading:
jQuery.ajax({
url: "/Products/Search",
type: "POST",
dataType: "json",
success: function (data) {
displayData(data);
},
error: function (errdata, errdata1, errdata2) { $('#ProductList').html("Error in connect to server" + errdata.responseText); }
and my controller JsonResult is below:
public JsonResult List()
{
tbl = db.tblProducts;
return Json(tbl, JsonRequestBehavior.AllowGet);
}
I can recive data from above ajax data loading successfully, but I can't pagination it.
Please help me.
Thank you.
There is no code for Pagination,Do you want to do client side pagination or server side
Thinking your devloping an ASP.Net MVC application
Server side pagnation : You can load the specific number of records alone.
Using Skip and Take functionlitys
public JsonResult GetOrders(int pagesize, int pagenum)
{
var query = Request.QueryString;
var dbResult = db.Database.SqlQuery<Order>(this.BuildQuery(query));
var orders = from order in dbResult
select new Order
{
ShippedDate = order.ShippedDate,
ShipName = order.ShipName,
ShipAddress = order.ShipAddress,
ShipCity = order.ShipCity,
ShipCountry = order.ShipCountry
};
var total = dbResult.Count();
orders = orders.Skip(pagesize * pagenum).Take(pagesize);
var result = new
{
TotalRows = total,
Rows = orders
};
return Json(result, JsonRequestBehavior.AllowGet);
}
Client side pagination : Load the entire records to your view from there implement pagination
Sample code : http://jsfiddle.net/rniemeyer/5xr2x/
Database db = new Database();
public int PageSize = 5;
public int VisiblePageCount = 5;
public JsonResult Search(int page = 1)
{
var model = new ModelName();
var tbl = db.tblProducts;
var renderedScheduleItems =(tbl.Skip((page - 1) * PageSize)
.Take(PageSize)
.ToList());
model.Products = renderedScheduleItems;
model.PagingDetail = new PagingDetail()
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = items.Count,
VisiblePageCount = VisiblePageCount
};
return Json(model, JsonRequestBehavior.AllowGet);
}

Parsing JSON.stringify'd object array post data

After building an object array and posting it to a jsp page I'm having trouble figuring out how to parse the data.
var arr = [];
for(var i=1; i <= $('#tableData tr').length; i++){
var el = $("#tableData tr:nth-child("+i+")");
var obj = {
id: el.find("td:nth-child(3)").text(),
doc: el.find("td:nth-child(5)").text(),
desc: el.find("td:nth-child(4)").text(),
};
arr.push(obj);
}
$.ajax('controllers/savePrintOutDetail.jsp', {
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(arr),
success: function(response){
},
error: function(){
alert('error');
}
})
I am aware I can retrieve the post data using getReader() but from there I don't know how to parse the array.
I was able to parse the data using org.json
<%# page import="org.json.JSONObject"%>
<%# page import="org.json.JSONArray"%>
<%
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
JSONArray array = new JSONArray(jb.toString());
for(int i=0;i<array.length();i++){
JSONObject jsonObj = new JSONObject(array.get(i).toString());
jsonObj.get("id") // etc
}
%>