Loading data into html table using ajax and SQL stored procedure - c#

I have a stored procedure that selects all the fields in the table based on the date. I then created a method shown below to return the results as JSON.
[HttpGet]
public JsonResult GetResult()
{
MonthNameConverter converter = new MonthNameConverter();
string fullDate = converter.startOfMonth().ToShortDateString();
string[] split = fullDate.Split('/');
string date = "";
if(Convert.ToInt32(split[0]) < 10)
{
date = split[2] + "-0" + split[0];
}
else
{
date = split[2] + "-" + split[0];
}
var results = travelSOCC.GetLansingMileage(date).ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
However when I go to append the data to an HTML table I'm getting an unidentified result.
$(function LoadData() {
$("#LansingTable tbody tr").remove();
$.ajax({
type: 'GET',
url: '#Url.Action("GetResult")',
dataType: 'json',
data: JSON,
success: function (data) {
$.each(data, function (item) {
var rows = "<tr><td>" + item.TravelDate + "</td><td>" + item.TripType + "</td></tr>";
$("#LansingTable tbody").append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.resonseText);
alert("Message: " + r.Message);
}
})
});
Any help is greatly appreciated.

Please modify $.each(data, function(item) { as below:
$.each(data, function(idx, item) {
Please refer documentation here for more information.

Related

How to get data from FormData Javascript send in C#

My code int Client:
var formData = new FormData();
formData.append("ID", "1");
formData.append("Name", "Gà Haha");
console.log(formData.get("ID"));
$.ajax({
type: "POST",
url: "http://localhost:13497/myapi/student",
contentType: "json",//Request header
data:formData,
dataType: "json",//Responce header
processData: false,
success: function (data) {
$.each(data, function (key, value)
{
var jsonData = JSON.stringify(value);
var objData = $.parseJSON(jsonData);
var id = objData.ID;
var fname = objData.Name;
var lname = objData.Price;
$('<tr><td>' + id + '</td><td>' + fname + '</td><td>' + lname + '</td></tr>').appendTo('#students');
});
},
error: function (errormsg) {
alert(errormsg.responseText);
}
});
My code in server:
[HttpPost]
public IEnumerable<Products> GetStudents()
{
string temp=HttpContext.Current.Request.Params["ID"];
return temp;
}
But temp return null. I'm using How can retrieve string formData js in c# but return empty and here How to read FormData into Web api but it not working.
Finally: I want to get data from FormData Client send
Please try in server side
Use form
HttpContext.Current.Request.Form["ID"] instead of Request.Params["ID"]

keep geography coords from ajax

good evening,
j tries to retrieve the data from the user but the problem iç that i can not handle the coords because of "," longitude and latitude, i do not know how to treat these give, i tried with parsefloat but without result, thank you
code controller action :
public ActionResult GetNeaarByLocations(string CurrentLat, string CurrentLng)
{
using (GeolocationTestEntities context = new GeolocationTestEntities ())
{
var CurrentLocation = DbGeography.FromText("POINT(" + CurrentLat + " " + CurrentLng + ")");
//var CurrentLocation = DbGeography.FromText("POINT(36,806494799999996 10,181531600000001)");
var places = (from u in context.schoolinfo orderby u.Location.Distance(CurrentLocation)
select u).Take(4).Select(x=>new schoollinfo(){ Name = x.name ,Lat = x.Location.Latitude, Lng = x.Location.Longitude,Distance = x.Location.Distance(CurrentLocation)});
var nearschools = places.ToList();
return Json(nearschools , JsonRequestBehavior.AllowGet);
}
}
and this is code Ajax :
jQuery.ajax({
cache: false,
type: "POST",
url: "#Url.Action("GetNeaarByLocations")",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: JSON.stringify({ CurrentLng:currentLatLng.longitude, CurrentLat: currentLatLng.latitude }),
success: function (data) {
if (data != undefined) {
$.each(data, function (i, item) {
addMarker(item["lat"], item["lng"], "Click to get directions");
})
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
thanks all.
we need to convert lng & lant to double
var currentLatLng = position.coords;
var Lat = currentLatLng.latitude;
var Lng = currentLatLng.longitude;
var LatDouble = parseFloat(Lat);
var LngDouble = parseFloat(Lng);
for Ajax is to delete att stringify
data: JSON({ CurrentLng:LngDouble , CurrentLat: LatDouble }),

"Internal server error" returning SelectList through ajax

Trying to retrieve data from database in .NET MVC, and populate a dropdown list with it.
The controller code:
public JsonResult GetCity(string name)
{
var cities = from c in context.Cities
orderby c.Name
select c;
var chosenCities = cities.Where(c=>c.Name== name);
return Json(new SelectList(chosenCities, "CityID", "Name"));
}
The jquery ajax script:
$(function () {
var countrySelect = $("#country-dropdown");
var citySelect = $("#city-dropdown");
countrySelect.change(function () {
citySelect.prop("disabled", false);
citySelect.empty();
$.ajax({
method: "GET",
url: "#Url.Action("GetCity")",
data: { name: countrySelect.val() },
dataType: ("json"),
success: function(cities){
$.each(cities, function(i, val){
citySelect.append("<option value=\"" + val.CityID +
"\">" + val.Name + "</option>");
});
},
error: function(ex, status, err){
alert("Couldn't retrieve data: " + ex + " "
+ status + " " + err);
}
});
});
});
Results in "Internal server error.".
Thanks to Stephen Muecke, I've solved the problem. There was also a mistake in the query.
What I was trying to do is a cascading select list, using two lists; the second list would get populated based on the value from the first list.
So the EF query should have been cities.Where(c=>c.Country.Name==name) as shown below. But more importantly, the reason I was getting the Internal server error is because I was using 'GET' instead of 'POST' to fetch my data. This requires adding JsonRequestBehaviour.AllowGet in the Json(...) arguments list:
public JsonResult GetCity(string name)
{
var cities = from c in context.Cities
orderby c.Name
select c;
var chosenCities = cities.Where(c => c.Country.Name == name).Select(c => new{ Value = c.CityID, Text = c.Name });
return Json(chosenCities, JsonRequestBehaviour.AllowGet);
}
Also there were some modifications in the JS code. When iterating over the returned data, the CityID and Name properties of the City class are bound to the Value and Text property of the object provided as the argument in the success function respectively.
This is the modified code:
$(function () {
var countrySelect = $("#country-dropdown");
var citySelect = $("#city-dropdown");
countrySelect.change(function () {
citySelect.prop("disabled", false);
citySelect.empty();
$.ajax({
method: "GET",
url: "#Url.Action("GetCity")",
data: { name: countrySelect.val() },
dataType: ("json"),
success: function(cities){
$.each(cities, function(i, val){
citySelect.append("<option value=\"" + val.Value +
"\">" + val.Text + "</option>");
});
},
error: function(ex){
alert("Couldn't retrieve data: " + ex);
}
});
});
});
Thank you to all who helped with this issue.

Populate items in dropdownlist

I have one function in my code behind
[System.Web.Services.WebMethod]
public static pcpName[] getPcpNames(string pcpCounty, string claimType)
{
List<pcpName> pcpNames = new List<pcpName>();
string query = "SELECT DISTINCT [PCP_ID], [PCP_NAME]+':'+[PCP_ID] AS [PCP_NAME] FROM [dbo].[FreedomTrinity] WHERE [PCP_COUNTY] = '" + pcpCounty + "' AND [CLAIM_TYPE] = '" + claimType + "'";
SqlDataReader reader = Database.SQLRead(query);
while (reader.Read())
{
pcpName names = new pcpName();
names.PCP_ID = reader.GetString(0);
names.PCP_NAME = reader.GetString(1);
pcpNames.Add(names);
}
return pcpNames.ToArray();
}
Now I want to populate items in a drop down list using this out put using jQuery.
So I write the code like this in my js file.
$(document).ready(function () {
$("#drpPcpCounty").change(function () {
//Remove items from drpPcpName
$("#drpPcpName option").remove();
$.ajax({
type: "POST",
url: "FreedomContestation.aspx/getPcpNames",
data: '{pcpCounty: "' + $("#drpPcpCounty").val() + '", claimType: "' + $("input:radio[name='rbtnlstClaimType']:checked").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
for (i in data) {
var d = data[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
}))
},
failure: function (response) {
alert(response.d);
}
});
});
});
But nothing is happening in dropdown list. Code behind code is returning the array with values. What to do after success: ??
EDIT 1
I track the code till response($.map(data.d, function (item) { . But I don't know what's happening inside it. No alert() working inside response($.map(data.d, function (item) {
Try this:
success: function (data) {
for (var i = 0;i < data.d.length;i++) {
var d = data.d[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
},

how to fetch return values between jquery functions and post ajax jquery request to webservice

I have the following code where the function codeaddress geocodes the text feild value and returns geocoded value , geocoded value is stored in variable example ,how will i return the variable v2 to the function call and post to asmx webservice.
<script type="text/javascript">
$(document).ready(function() {
$('#SubmitForm').submit(function() {
var geocoder;
var map;
function codeAddress(state) {
var address = document.getElementById("state").value;
geocoder.geocode( { 'address': state}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var v2=results[0].geometry.location;
alert(example);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
return v2;
});
var businessname = ($("#businessname").val());
var keyword = ($("#keyword").val());
var description = ($("#textarea").val());
var zipcode = ($("#zipcode").val());
var streetno = ($("#streetno").val());
var streetname = ($("#streetname").val());
var state = $('#state :selected').text();
var telephone = ($("#telephone").val());
var email = ($("#email").val());
var username = ($("#username").val());
var password = ($("#pass").val());
var repassword = ($("#pass1").val());
//data: "{'businessname':" + businessname + "'keyword':" + keyword + "}",
alert(state);
var v2=codeAddress(state);
alert(example);
var jsonobject = "{\"businessname\":\"" + businessname + "\",\"keyword\":\"" + keyword + "\",\"description\":\"" + description + "\",\"zipcode\":\"" + zipcode + "\",\"streetno\":\"" + streetno + "\",\"streetname\":\"" + streetname + "\",\"state\":\"" + state + "\",\"telephone\":\"" + telephone + "\",\"email\":\"" + email + "\",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"repassword\":\"" + repassword + "\"}";
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
});
function ajaxCallFailed(error) {
alert("error");
}
function ajaxCallSucceed(response) {
if (response.d == true) {
alert(" sucessfully saved to database");
}
else {
alert("not saved to database");
}
}
});
</script>
You call the codeAddress method with a callback. Inside codeAddress when you get value of v2, call the callback function passing it v2.
codeAddress(state,
function(v2) {
var jsonobject = "{\"businessname\":\"" + businessname/*.. use v2 in buiding jsonobject..*/;
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
}
);
function codeAddress(state, callback) {
var address = document.getElementById("state").value;
geocoder.geocode(...);
// ...
var v2=results[0].geometry.location;
callback(v2);
}

Categories

Resources