Ajax replace new arraylist without refresh page - javascript

I am new ajax, how can i replace ${phList} with new arraylist so that ajax can help me update the content without refresh whole page.
The ajax will trigger controller to retrieve data and store in arraylist then pass the arraylist to ajax. Ajax will update the content in jsp. Next step forEach loop will generate the column and checkbox with value if there have record retrieve from database.
Any solution and hope this solution can help others. Thanks!
myJsp.jsp
<select id="selected_year" name="selected_year" class="form-control">
<c:forEach var="line" items="${yearlist}">
<c:choose>
<c:when test="${refreshInd ge 0 and line eq refreshInd}">
<option selected="selected"><c:out value="${line}" />
</option>
</c:when>
<c:otherwise>
<option><c:out value="${line}" /></option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
<div class="row">
<div class="col-md-4">
<form:input path="phList[${PHstatus.index}].holidayDesc" class="form-control col-md-5" value="${ph.holidayDesc}" />
</div>
<div class="col-md-3">
<form:input path="phList[${PHstatus.index}].startDate" class="form-control" value="${ph.startDate}" id="calendar1" placeholder="dd/mm/yyyy" onkeypress="return noAlphabet(event)" />
</div>
<div class="col-md-3">
<form:input path="phList[${PHstatus.index}].endDate" class="form-control" value="${ph.endDate}" id="calendar2" placeholder="dd/mm/yyyy" onkeypress="return noAlphabet(event)" />
</div>
<div class="col-md-2">
<form:checkbox path="phList[${PHstatus.index}].checkboxDel" value="" class="cbposition" />
</div>
</div>
<br>
</c:forEach>
After i change selected_year to trigger the ajax, it work well but :success function(response) cannot work. I want to remove the existing ${phList} and update with new arraylist by replace ${phList} show at above jsp.
myJavascript.js
$(function($) {
$("#selected_year").change(function(){
var selectedText = $(this).find("option:selected").text();
var $form = $(this);
var action = $form.find('.send').val();
var list[];
var array[];
$.ajax("holiday/pubholiday.json?" , {
method: "GET",
accepts: "application/json",
dataType: "json",
data: $form.serialize() + '&selectedText=' + selectedText,
success: function(response) {
$("#phList").remove()
$(JSON.stringify(response))
//how to pass the response which is my new arraylist to replace the ${phList}
},
}).done(function(data) {
console.log(data)
alert("Data Sent" + selectedText)
})
.fail(function(jqXHR, textStatus, errorThrown) {
var errorMessage = "";
if (jqXHR.status == 401) {
errorMessage = "Your session has expired. Please login again.";
}else if(jqXHR.status == 500){
console.log(jqXHR.status);
console.log(jqXHR.responseText);
console.log(thrownError);
}else {
try {
var errorJson = JSON.parse(jqXHR.responseText);
errorMessage = errorJson.error;
} catch (e) {
errorMessage = errorThrown || textStatus;
}
}
});
})
});
This is object model store in the arraylist. Each record will contain object model data.
model.java
public class PubHoliday {
private int year;
private String holidayID;
private String holidayDesc;
private String startDate;
private String endDate;
private boolean checkboxDel;
private String selected_year;
private int refreshInd;
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getHolidayID() {
return holidayID;
}
public void setHolidayID(String holidayID) {
this.holidayID = holidayID;
}
public String getHolidayDesc() {
return holidayDesc;
}
public void setHolidayDesc(String holidayDesc) {
this.holidayDesc = holidayDesc;
}
public String getStartDate() {
return startDate;
}
public String getEndDate() {
return endDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public boolean getCheckboxDel() {
return checkboxDel;
}
public void setCheckboxDel(boolean checkboxDel) {
this.checkboxDel = checkboxDel;
}
public String getSelected_year() {
return selected_year;
}
public void setSelected_year(String selected_year) {
this.selected_year = selected_year;
}
public int getRefreshInd() {
return refreshInd;
}
public void setRefreshInd(int refreshInd) {
this.refreshInd = refreshInd;
}
}

First, you need to wrapper <c:forEach var="ph" items="${phList}" varStatus="PHstatus"> by div with id, example:
<div id="list_holidays">
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
.......
</c:forEach>
</div>
Then in success ajax code
- Empty div#list_holidays
- Get result, each row, create new div, append to div#list_holidays
success: function(response) {
var wrapper = $('#list_holidays');
wrapper.html('');
//->foreach response result
// -> $('div').html(your template).appendTo(wrapper)
}

JSP is server side rendering. meaning, when a request is received server uses the variable ${phList} to render a dynamic HTML page and sends that page to the browser. Ajax is a request made by your javascript sitting in browser. So, the browser has no way of knowing or changing the variable $(phList} directly and affecting the template.
However, what you said can be achieved. In one of following ways
Method 1 (easiest):
Implement holiday/pubholiday.asp which responds with only this instead of json.
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
<div class="row">
<div class="col-md-4">
<form:input path="phList[${PHstatus.index}].holidayDesc" class="form-control col-md-5" value="${ph.holidayDesc}" />
</div>
...
<br>
</c:forEach>
Add a container element to the array items something like this
<div id="container" >
<c:forEach var="ph" items="${phList}" varStatus="PHstatus">
...
</c:forEach>
</div>
Change your ajax request in main page to this. When you get a response from pubholiday.jsp, replace contents of #container to what is received from ajax.
...
$.ajax("holiday/pubholiday.asp?" , {
method: "GET",
accepts: "application/html",
dataType: "json",
data: $form.serialize() + '&selectedText=' + selectedText,
success: function(response) {
// This is where magic happens
$("#container").html(response);
},
}).done(function(data) {
console.log(data)
alert("Data Sent" + selectedText)
})
...
Method 2:
If you need the response to be only json, in success callback read the json, and generate html yourself by concatenating strings and then replace the #container element.
Method 3 (recommended):
User some client side rendering library like polymer or handlebars to render json into html.

Related

How do I get asp-items to populate a select when adding select element to a div?

Using Javascript to add a select dropdown list when a button is clicked, but the select isn't being populated with the data from the viewmodel. Essentially this code creates what I want, but the asp-items are not populating the select aside from the default "Select Column Name" option.
How would I get this asp-items to populate from the viewmodel selectlist, "Model.SelColumnNames"?
<script>
$('.addSort').click(function() {
$('.block:last').before('<div class="block"><select asp-for="SelColumnNameAdditional" asp-items="Model.SelColumnNames" style="width: 30%;"><option value="">Select Column Name</option></select>   <select style="width: 15%;"><option value="1">Ascending</option><option value="2">Descending</option></select>   <span class="remove">Remove Option</span></div>');
});
</script>
Edit:
I can already populate it properly as a dropbox in the HTML section of my viewpage using this:
<select asp-for="SelColumnNameAdditional" asp-items="Model.SelColumnNames" style="width: 30%;">
<option value="">Select Column Name</option>
</select>
I would like the script code to be able to create a div with the same populated dropdown in javascript. When I do that, asp-items doesn't pull from the viewmodel like it does in the HTML code. Why is that?
If you are using Javascript, you need to get data using ajax. This is what I have so far.
Controller/ViewModel
public class JaesonViewModel
{
public string value { get; set; }
public string text { get; set; }
}
public class HomeController : Controller
{
public ActionResult GetViewModel()
{
var list = new List<JaesonViewModel>();
var j = new JaesonViewModel { text = "text1", value = "value1" };
list.Add(j);
var j2 = new JaesonViewModel { text = "text2", value = "value2" };
list.Add(j2);
return Json(new { Items = list.ToList() }, JsonRequestBehavior.AllowGet);
}
public ActionResult Index10() //I am calling index10 to start--the view is index10
{
return View();
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index10</title>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('.addSort').click(function () {
$.ajax({
type: "GET",
url: "/home/GetViewModel",
async: false,
cache: false,
dataType: "json",
contentType: "application/json",
success: function (jsn) {
jQuery.each(jsn.Items, function (index, itemData) {
$('.dropdown').append('<option value=' + itemData.value + '>' + itemData.text + '</option>');
});
},
error: function (jqXHR, exception) {
var status = jqXHR.status; //400
var message = jqXHR.responseText;
var ex = exception; // 'abort' for example
alert(status + " " + message + " " + ex);
}
});
});
});
</script>
</head>
<body>
<input type="button" class="addSort" value="Click Me" />
<select class="dropdown">
</select>
</body>
</html>

I can't pull data from ajax

public enum SocialEnum
{
[Display(Name = "Genel")]
General,
[Display(Name ="Teşekkür Et")]
Thanks
}
public class SocialMedia : Entity<string>
{
public string Message { get; set; }
public string Departmen { get; set; }
public SocialEnum MessageType { get; set; }
public string FullName { get; set; }
}
This is my model
<div class=" right floated" id="SubjectButtons">
<button class="tiny ui inverted blue button General" id="general"><i class="globe icon"></i>Genel</button>
<button class="tiny ui inverted blue button Thanks" id="thanks"><i class="star icon"></i>Teşekkür Et</button>
</div>
this is my cshtml
$(function () {
$('#Share').on('click', function () {
var file = $("#imgupload").get(0).files;
var droplist = $(".ui.fluid.search.dropdown").val();
var message = $(".ui.form").val();
var sbjtbtn = $("#general").val();
var sbjtbtn = $("#thanks").val();
var data = new FormData;
data.append("Photo", file[0]);
data.append("Message", message);
data.append("FullNameList", droplist);
data.append("MessageType", sbjtbtn);
$.ajax({
url: '#Url.Action("Index")',
type: "POST",
data: data,
contentType: false,
processData: false,
success: function (data) {
$(".post-area").html(Counter);
$(".post-area").html(data);
$("#message").html(data.message);
$(".img-responsive").append('<img src="/Image/' + data + '"class=img-responsive thumbnail"/>');
if (sbjtbtn == $("#thanks")) {
$("#person").html(data.droplist);
$(".post-area").html(data);
$("#message").html(data.message);
$(".img-responsive").append('<img src="/Image/' + data + '"class=img-responsive thumbnail"/>');
}
},
error: function (data) {
}
});
});
});
this is my js
public ActionResult Index(SocialMedia data)
{
var model=GetSocialMedia();
MediaList mediaList = new MediaList();
if (mediaList.MessageType == data.MessageType)
{
mediaList.FullName = model.FullName;
mediaList.Departmen = model.Departmen;
mediaList.Message = data.Message;
var file = data.Photo;
if (file != null)
{
string Location = Server.MapPath("/Image/" + file.FileName);
file.SaveAs(Location);
mediaList.Photo = "../Image/" + file.FileName;
}
mediaList.FullNameList = data.FullNameList;
}
return PartialView("~/Views/SocialMedia/MediaList.cshtml", mediaList);
}
This is my controller
When you press the general button, some data should come. but if you press the thanks button, it should pull more data. I have defined it separately in ajax. I gave the variable name the same. message type comes in general.The message type is never be thanks.Where is my mistake?
My index page, model and controller are longer, but I think these are the parts I need to show.Sorry for my English:)
you should know already what is the difference between view and model. In any case in index view place this div
.....
<div id="mediaList">
<partial name="~/Views/SocialMedia/MediaList.cshtml" />
</div>
.....
<div class=" right floated" id="SubjectButtons">
<button class="tiny ui inverted blue button General" id="general"><i class="globe icon"></i>Genel</button>
<button class="tiny ui inverted blue button Thanks" id="thanks"><i class="star icon"></i>Teşekkür Et</button>
</div>
and ajax
$.ajax({
url: '#Url.Action("Index")',
.....
success: function (data) {
$("#mediaList").html(data);
},
error: function (xhr) {
}
});
have you tried using POSTMAN tool? https://www.postman.com/ . This tool is used for testing webservice API. Try this one first if you really get some data from your API URL.

How to pass values from View to Controller method with javascript? in asp .net core

I have some kind of messenger it have panel by side where I can see all my contacts. What I want is when i click on one of them to pass phone number and Id to my Controller to send message and save it in database.
Foreach prints all my contacts:
#foreach (var contact in Model.Contacts)
{
<div class="chatperson" onclick="get_contact_number(#contact.PhoneNumber , #contact.ContactId)">
<div class="namechat">
<div class="pname">
#contact.Name
<a asp-action="ContactDetails" asp-route-id="#contact.ContactId" class=" glyphicon glyphicon-info-sign"></a>
<a asp-action="EditContact" asp-route-id="#contact.ContactId" class=" glyphicon glyphicon-pencil "></a>
</div>
<div class="lastmsg">#contact.PhoneNumber </div>
</div>
</div>
}
In div I used JS method and passed there values:
function get_contact_number(contactNumber, contactId) {
#Model.PhoneNr = contactNumber;
#Model.ContactId = contactId;
}
In final i want to pass these values to my controller function
public IActionResult SendMessage(MessengerViewModel model, string phoneNumber, string message)
{
var CurrentUserId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
if (ModelState.IsValid)
{
var newMessage = new Message();
newMessage.UserId = CurrentUserId;
newMessage.ContactId = model.ContactId;
newMessage.Body = model.MessageBody;
newMessage.Date = DateTime.Now;
newMessage.isDelivered = true;
_messageService.AddMessage(newMessage);
AtSmsSender smsSender = new AtSmsSender();
message = model.MessageBody;
phoneNumber = model.PhoneNr;
smsSender.SendSms(phoneNumber, message);
return RedirectToAction("Index", "Messenger");
}
else
{
return RedirectToAction("Index", "Messenger");
}
}
you can do a ajax call from get_contact_number function. Something like the below code
$.ajax({
type:'GET',
url: '#Url.Action("ActionName", "ControllerName")',
async:true,
success:function(response){
//Do Something With response object returned by your action
}
});

No converter found for return value of type: class com.google.gson.JsonArray

I am developing an application where I have two drop down lists. When I select a value from first drop down, second drop down, an ajax call happens to controller and returned list should populate in second drop down list. I have tried below code.
jsp form:
<form:form modelAttribute="place" action="getWeather">
<table>
<tr>
<td><form:label path="country">Country:</form:label></td>
<td>
<form:select path="country" id = "countryList">
<form:option value="#">--Select--</form:option>
<form:options items="${CountriesList}"/>
</form:select>
</td>
</tr>
<tr>
<td><form:label path="city">City:</form:label></td>
<td>
<form:select path="city" id = "cityList">
</form:select>
</td>
</tr>
</table>
</form:form>
<script type="text/javascript">
document.getElementById("countryList").addEventListener("change", myFunction);
/* $(document).ready(function(){
alert("sample msg");
}); */
function myFunction(){
var id = $(this).val()
/* var Country = { "Country" : id }
alert(Country);
alert(JSON.stringify(Country)); */
$.ajax({
type: "GET",
url: 'GetCities/' + id,
dataType: 'json',
success: function(data){
var slctSubcat=$('#cityList'), option="";
slctSubcat.empty();
for(var i=0; i<data.length; i++){
option = option + "<option value='"+data[i] + "'>"+data[i] + "</option>";
}
slctSubcat.append(option);
}
});
}
</script>
Controller method:
#RequestMapping(value = "/GetCities/{country}", method = RequestMethod.GET)
public #ResponseBody JsonArray getCities(#PathVariable(value="country") String Country){
List<String> cities = getWeatherService.getCities(Country);
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(cities, new TypeToken<List<String>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
return jsonArray;
}
Ajax call is successful and getting data in list. But When pass the list to jsp in the form of JsonArray, it is giving exception like below.
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.google.gson.JsonArray
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:225)
org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:182)
org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:119)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I have tried passing List directly, but same issue. Please help me to find the solution.
Finally able to resolve this issue. Instead of returning JsonArray from controller, I have just returned Json string. It worked.
#RequestMapping(value = "/GetCities/{country}", method = RequestMethod.GET)
public #ResponseBody String getCities(#PathVariable(value="country") String Country){
List<String> cities = getWeatherService.getCities(Country);
Collections.sort(cities);
Gson gson = new Gson();
String json = gson.toJson(cities);
return json;
}

LogIn Page Using JQuery

Before 3 days the code was working fine. But now its not.
please point out my mistake as i am new to JQuery.
I debugged it, and found out that debugger is not entering inside success method of ajax. and not even going to CS file.
Code of Jquery-
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
alert('b');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "admin.aspx/LogIn",
dataType: "json",
data: "{'name':'" + $('#txtfn').val() + "','password':'" +$('#txtln').val() + "'}",
success: function (data) {
alert(data);
var obj = data.d;
alert(obj);
alert(data.d);
if (obj == 'true') {
$('#txtfn').val('');
$('#txtln').val('');
alert("dasdsad");
window.location = "home.aspx";
alert("success");
}
else if (obj == 'false')
{ alert("errorrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"); }
},
error: function (result) {
alert(data);
alert("aaaaaaafgdgfdfgsfgfhffghgfhgfhfghfghfhfghfhfghgfhgfhgfhgfhfghfghgfhgfhgf");
alert(result);
}
});
});
});
</script>
</head>
<body>
<div id="login">
<div id="triangle"></div>
<h1>Log in</h1>
<form id="f1" runat="server">
<input type="text" id="txtfn" placeholder="name" />
<input type="text" id="txtln" placeholder="Password" />
<input type="submit" id="btnSubmit" value="Log in" />
</form>
</div>
</body>
Code-
[WebMethod]
public static string LogIn(string name, string password)
{
string retMessage = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["oltest_conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string Query = "select * from profile where name=#pname and password=#pwd";
using (SqlCommand cmd = new SqlCommand(Query, con))
{
cmd.Parameters.AddWithValue("#pname", name);
cmd.Parameters.AddWithValue("#pwd", password);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
//retMessage = "home.aspx";
retMessage = "true";
}
else
{
retMessage = "false";
}
}
return retMessage;
}
}
You just need to remove
alert('b');``
on your jquery code
try adding a
return false
at the end of the ajax call
Hi change your submit button to button.
<input type="button" id="btnSubmit" value="Log in" />
data: {name: $('#txtfn').val() ,password: $('#txtln').val()},
I updated my answer:
your ajax call is not executed because form is submitted, this code will prevent submission
$("#f1").submit(function (e) {e.preventDefault();})
place it before $('#btnSubmit').click(function () {
better way will be place your code inside
$("#f1").submit(function (e) {
e.preventDefault();
// here place content of $('#btnSubmit').click(function () {( )}
})
Please ensure JSON data /parameters accepted by your web method and it returning proper true/false without any exception/error.
You can do it by debugging in firebug and Visual Studio.

Categories

Resources