Issue to Update HTML Table after Data Insert using Ajax - asp.net

I am new to Ajax.I tried to update my HTML table after successfully insert of data in database using Ajax instead of loading the entire form by using window.location.reload().
Insert Method
[WebMethod]
public static void SaveUser(Employee objEmployee) //Employee is the class
{
//My Code for insert
}
This works fine as the data inserts successfully.Ajax insert defined below
Update Method
public static void GetData() //Tried using datatable as return type nothing happened
{
//var dt = new DataTable();
using (var con = new SqlConnection(Constr))
{
const string query = "select * from TblUser";
using (var cmd = new SqlCommand(query, con))
{
using (var sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (TableData)
{
sda.Fill(TableData);
//return TableData;
}
}
}
}
}
On button save my ajax script is like this
<script type="text/javascript">
$(function () {
$("#btnSave").click(function () {
alert("TESST");
var user = {};
user.FName = $("#FirstName").val();
user.LName = $("#Surname").val();
user.MName = $("#MiddleName").val();
// Some others are also there
user.CreatedDateTime = new Date();
user.ModifiedDateTime = new Date();
$.ajax({
type: "POST",
url: "Default.aspx/SaveUser",
data: '{objEmployee: ' + JSON.stringify(user) + '}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
alert("User has been added successfully.");
//Another Ajax to update the grid
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetData",
data: "{}",
dataType: "json",
success: function () {
},
error: function () {
alert("Error while Showing update data");
}
});
},
error: function () {
alert("Error while inserting data");
}
});
return false;
});
});
</script>
I have binded to HTML Table like this
<table id="dataTables-example" role="grid">
<thead>
<tr role="row">
<th>Name</th>
<th>Email Id</th>
<th>Mobile(H)</th>
<th >Mobile(O)</th>
<th>Joining Date</th>
<th>Birth Date</th>
</tr>
</thead>
<tbody>
<% for (var data = 0; data < TableData.Rows.Count; data++)
{ %>
<tr class="gradeA odd" role="row">
<td class="sorting_1"><%=TableData.Rows[data]["FName"]%></td>
<td><%=TableData.Rows[data]["EMail"]%></td>
<td><%=TableData.Rows[data]["Telephone"]%></td>
<td><%=TableData.Rows[data]["Mobile"]%></td>
<td><%=TableData.Rows[data]["DOJ"]%></td>
<td><%=TableData.Rows[data]["DOB"]%></td>
</tr>
<% } %>
</tbody>
</table>
My Issues
My update method is called after insert but I am not able to see the updated data.
After page refresh as the webmethod is static multiple data shows.

Loop trough the received data and set them to your table :
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetData",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#dataTables-example tbody").append("<tr><td>" + data.d[i].FName+ "
</td><td>" + data.d[i].EMail+ "</td><td>" + data.d[i].Telephone+ "
</td></tr>");
}
},
error: function () {
alert("Error while Showing update data");
}
});

Related

How to get values out of Ajax success data function

My Ajax data function has data but I can't figure out how to get that data out and insert it into a textbox with the ID of FirstName. I know the data is there because I can debug and see "d" contains all of the data from my query but how do I extract it from the success function?
$(document).ready(function () {
$("#btnGetData").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetFormData", //Default.aspx is page and GetFormData is the WebMethod
data: {},
dataType: "json",
success: function (data) {
data: { ("#FirstName").val(d.FirstName) }
},
error: function () {
alert("Error while Showing update data");
}
});
});
});
WebMethod:
public static List<MembersClass> GetFormData()
{
List<MembersClass> infoObjs = new List<MembersClass>();
try
{
// Initialization.
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("dbo.spGetMemberbyMemberID", con);
cmd.Parameters.AddWithValue("#MemberID", "123");
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
// Read file.
while (rdr.Read())
{
MembersClass infoObj = new MembersClass();
infoObj.FirstName = rdr["first_name"].ToString();
infoObj.LastName = rdr["last_name"].ToString();
// Adding.
infoObjs.Add(infoObj);
}
}
}
catch (Exception ex)
{
Console.Write(ex);
}
// info.
return infoObjs;
}
I'm not sure what your response object looks like, but try this.
success: function (data) {
$('#FirstName').val(data.d.FirstName);
}
I found the solution. This is now getting the values from my webmethod and placing them in my forms.
$(document).ready(function () {
$("#btnGetData").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetFormData", //Default.aspx is page and GetFormData is the WebMethod
data: {},
dataType: "json",
success: function (data) {
var formdata = $(data.d);
$.each(formdata, function (index, value) {
$("#FirstName").val(value.FirstName);
$("#LastName").val(value.LastName);
});
},
error: function () {
alert("Error while Showing update data");
}
});
});
});

asp.net mvc load query from controller

I am trying to read my query from controller and I already have the Ajax call to get it through my button. but my problem is there is no changes happening on my index view, the table hasn't change and can't figure out why.
Here is my View:
#{
ViewBag.Title = "LoadInfo";
}
#model IEnumerable<MyApp.Models.LoadInfo>
<html>
<body>
<input style="text-align:left; width:250px" id="txtSearch" type="text" />
<button type="button" id="search" onclick="search()" class="btn btn-primary">Search</button>
<div class="tableFixHead" ; style="margin-top: 10px;">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.ID</td>
<td>#item.Name</td>
<td>#item.Address</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>
<script>
function search() {
var search = document.getElementById("txtSearch").value
$.ajax({
url: '/Home/LoadInfo',
type: 'GET',
data: {
'name': search
},
success: function (data) {
alert("success")
},
error: function (jqXhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
Controller:
public ActionResult LoadInfo(string name)
{
List<readDetails> userDetails = new List<readDetails>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT ID, Name, Address FROM EmpDetails WHERE Name like '%" + name + "%' LIMIT 500";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
userDetails.Add(new readDetails
{
op = sdr["ID"].ToString(),
op_desc = sdr["Name"].ToString(),
doc_id = sdr["Address"].ToString(),
});
}
}
con.Close();
}
}
return View(userDetails);
}
I also using this controller to my starting page load not sure if this is cause of the problem, do I need to create a separate controller and view for initial loading and for my search functionality.
The result alerts me to "success" but its weird because my table is not changing or refreshing just like if you do a simple query with filter from query browser.
You need to add html() function for table's <tbody> element to override existing results with the new one:
$.ajax({
url: '/Home/LoadInfo',
type: 'GET',
data: {
'name': search
},
success: function (data) {
alert("success");
$('.table tbody').html(data); // override previous results
},
error: function (jqXhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
If the response contains entire <table> element, you should omit tbody selector:
$('.table').html(data);
Also you might try to return PartialView(), e.g. return PartialView(userDetails); instead of entire view page if the search results are provided in same search page.
Update:
Since the data returns entire HTML page, the current controller action should be modified to return JSON response like this example:
public ActionResult LoadInfo(string name)
{
List<readDetails> userDetails = new List<readDetails>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT ID, Name, Address FROM EmpDetails WHERE Name like '%" + name + "%' LIMIT 500";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
userDetails.Add(new readDetails
{
op = sdr["ID"].ToString(),
op_desc = sdr["Name"].ToString(),
doc_id = sdr["Address"].ToString(),
});
}
}
con.Close();
}
}
return Json(userDetails, JsonRequestBehavior.AllowGet);
}
Then, replace existing <tbody> contents with data from response:
$.ajax({
url: '/Home/LoadInfo',
type: 'GET',
data: {
'name': search
},
dataType: 'json',
success: function (data) {
alert("success");
var tblbody = $('.table').find('tbody');
tblbody.empty(); // remove existing rows
var row = '';
$.each(data, function(i, item) {
row += $('<tr>').append($('<td>').text(item.ID), $('<td>').text(item.Name), $('<td>').text(item.Address));
tblbody.append(row); // add new rows
});
},
error: function (jqXhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
At this point the search results should appear on the same table instead of returning entire HTML content.

calling webmethod using jquery

I am having two asp textboxes, TextBoxPicPostCode and TextBoxPicAddress.
The goal of this task is that when i enter a post code in TextBoxPicPostCode and the focus gets lost from this TextBox it should automatically populate TextBoxPicAddress using the method in code behind.
The method getadd() in .cs code works fine and uses google api but i am not getting an idea how to use jquery ajax with it.
Code-Behind
public void getadd()
{
string address = "";
//_Address.InnerText = _PostCode.Text;
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://maps.google.com/maps/api/geocode/xml?address=" + TextBoxPicPostCode.Text + "&sensor=false");
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
address = distanceX[0].InnerXml;
TextBoxPicAddress.Text = address;
}
}
JavaScript
<script type="text/javascript">
function submit() {
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx.cs/getadd",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
Markup
<asp:TextBox ID="TextBoxPicPostCode" runat="server"
CssClass="time"
onblur="submit();">
</asp:TextBox>
<asp:TextBox ID="TextBoxPicAddress" runat="server"
CssClass="address">
</asp:TextBox>
Make these changes
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script type="text/javascript">
// change the function name from 'submit' here and at markup
function FetchAddress() {
//passing postalCode as string.
//Make sure that 'postalCode' is the parameter name at the webmethod
var dataValue = "{ 'postalCode' : '" + $('.time').val() + "'}";
//would be worthwhile to read about JSON.stringify, its the standard method
//var dataValue = JSON.stringify({ postalCode: $(".time").val() });
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx/getadd", // .cs is not required
data: dataValue,
contentType: 'application/json', //charset is not required
//dataType: 'json', // not required
success: function (result) {
var data = result.hasOwnProperty("d") ? result.d : result;
//alert("We returned: " + result.d);
// now we are assigning the return value to TextBoxPicAddress
$(".address").val(data);
}
});
}
</script>
Code-behind
//1. webmethod attribute required
[System.Web.Services.WebMethod]
//2. web methods should be static
//ref: http://encosia.com/why-do-aspnet-ajax-page-methods-have-to-be-static/
//3. return type string is needed
// because we need to fetch the return on the ajax callback
//4. we need to pass TextBoxPicPostCode as a parameter
// because we need to fetch the return on the ajax callback
public static string getadd(string postalCode)
{
string address = "No Address found!";
//_Address.InnerText = _PostCode.Text;
XmlDocument xDoc = new XmlDocument();
var remoteXml = "http://maps.google.com/maps/api/geocode/xml?address="
+ postalCode + "&sensor=false";
xDoc.Load(remoteXml);
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
address = distanceX[0].InnerXml;
}
return address;
}
At markup, change the event as onblur="FetchAddress();"
P.S: No time to type all the changes made in detail, so added as comment
.cs is Not Required
and
public void getadd()
Should be Static
so
[System.Web.Services.WebMethod]
public static void getadd()
JScript
<script type="text/javascript">
function submit()
{
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx/getadd",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
EDIT:
You Can't Use Controls Inside Static method. You nee to Refer This:
Using Jquery Ajax Call
Using AutoCompleteExtender
HTML
Javascript
`
function danish() {
var code = $("#<%=TextBoxPicPostCode.ClientID %>").val();
$.ajax({
type: "POST",
url: "GoogleAPI.aspx/getadd",
contentType: 'application/json; charset=utf-8',
data: '{code: "' + code + '"}',
dataType: 'json',
success: function (result) {
$("#<%=TextBoxPicAddress.ClientID %>").autocomplete({ source: result.d });
}
});
return false;
}
</script>`
Codebehind
using System.Web.Services;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
[WebMethod]
public static List<string> getadd(string code)
{
string address = "";
List<string> lst = new List<string>();
XmlDocument xDoc = new XmlDocument();
var jsonSerialiser = new JavaScriptSerializer();
try
{
HttpWebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
xDoc.Load(#"http://maps.google.com/maps/api/geocode/xml?address=" + code + "&sensor=false");
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
for (int i = 0; i < distanceX.Count; i++)
{
lst.Add(distanceX[i].InnerXml);
address = address + distanceX[i].InnerXml;
}
}
}
catch (Exception ex)
{
throw ex;
}
return lst;
}

Fetch data from asp.net using backbone

$.ajax({
type: "POST",
url: "Home.aspx/loadSB",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
for (i = 0; i < msg.d.length; i++) {
$('#sidebar ul').append('<li class="inactive"><a>' + msg.d[i].Title + ' </a></li>');
}
}
});
I go through this
https://github.com/kjbekkelund/writings/blob/master/published/understanding-backbone.md
and
https://gist.github.com/ryandotsmith/1655019
tutorial and create a backbone as below, but is not working well as the model did not fetch data from asp.net, which part goes wrong? I still new to backbone
Menu = Backbone.Model.extend({
parse: function (data) { return data; }
});
MenuCol = Backbone.Collection.extend({
model: Menu,
url: "Home.aspx/loadSB",
parse: function (response) { return response.rows; }
});
MenuView = Backbone.View.extend({
initialize: function () {
this.collection.on('add', this.appendMenu, this);
},
appendMenu: function (msg) {
for (i = 0; i < msg.d.length; i++) {
this.$('ul').append('<li class="inactive"><a>' + msg.d[i].Title + ' </a></li>');
}
}
});
var mc = new MenuCol();
//mc.fetch();
//Update1:
new MenuView({ el: $('#sidebar'), collection: mc });
Update 1:
I had play around with fetch, but still not working well,
Menu = Backbone.Model.extend({});
MenuCol = Backbone.Collection.extend({
model: Menu,
url: "Home.aspx/loadSB",
});
var test = new MenuCol();
test.fetch();
It did not return the data that I want, instead of, it display the interface that my screen have
If i using the jquery.ajax without backbone, it return the json data to me, which part goes wrong? Any guide will be great
Update 2:
Ok, I had change the "fetch", and now I able to see the json data passing into backbone
var test = new MenuCol();
test.fetch({ type: 'POST', contentType: "application/json; charset=UTF-8" });
Ok, finally I had solved the problem,
define(['jquery', 'underscore', 'backbone'], function () {
Menu = Backbone.Model.extend({});
MenuCol = Backbone.Collection.extend({
model: Menu,
url: "Home.aspx/loadSB",
});
MenuView = Backbone.View.extend({
initialize: function () {
this.collection.on('add', _.bind(this.AppendMenu, this));
},
AppendMenu: function (msg) {
var feed = JSON.parse(JSON.stringify(msg));
for (var i = 0; i < feed.d.length; i++) {
this.$('ul').append('<li class="inactive"><a>' + feed.d[i].Title + ' </a></li>');
}
}
});
var test = new MenuCol();
test.fetch({ type: 'POST', contentType: "application/json; charset=UTF-8" });
new MenuView({ el: $('#sidebar'), collection: test })
});
by changing the fetch type to "POST" and contentType: "application/json; charset=UTF-8", finally i manage to populate web with the data I want

asp Textbox with ajax autocomplete does not working in .net 3.5

i was working ajax auto completeextender witha text box in asp.net and c#.net. i am not able to get list to choose ,i have the appropriate web service method called..can anyone guide me to get the automo complete done.
declaring
this is the tag i am using i aspx
the ajax part
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtUsername" MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" ServiceMethod="GetCountries" >
</asp:AutoCompleteExtender>
</div>
Code behind
[System.Web.Services.WebMethod]
public static List<string> GetCountries(string strUserName, int count)
{
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
scon.Open();
SqlCommand scmd = new SqlCommand("select * from UserInformation where UserName like #Username+'%'", scon);
scmd.Parameters.AddWithValue("#Username", strUserName);
SqlDataAdapter sda = new SqlDataAdapter(scmd);
DataTable dt = new DataTable();
sda.Fill(dt);
List<string> UserNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
UserNames.Add(dt.Rows[i][1].ToString());
}
return UserNames;
}
ASPX code in tag. GetCur : name given in asmx file.
$("#<%=txtSearch.ClientID %>").autocomplete({
source: function(request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebService.asmx/GetCur") %>',
data: "{ 'prefixText': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item,
val: item
}
}))
},
error: function(response) {
alert(response.responseText);
},
failure: function(response) {
alert(response.responseText);
}
});
},
});
});

Resources