How to get values out of Ajax success data function - asp.net

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");
}
});
});
});

Related

how to configure and enable xml return type from webmethod in asp.net

I think it might be configuration issue but i cannot figure it out why I am able to make a call from ajax if contentType is "Json" but if i change it to xml it does not call that webmethod. Can someone Please help.
Below code is not working.
In JavaScript
$.ajax({
type: "POST",
dataType: "xml",
contentType: "application/xml; charset=utf-8",
url: "Test.aspx/GenerateXML",
success: function (result) {
alert(result)
},
error: function (error, e1, e2) {
alert(error);
}
});
C# in aspx.cs page
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml, UseHttpGet = false, XmlSerializeString = true)]
public static DataTable GenerateXML()
{
TestCalculator testCalculator = new TestCalculator();
DataTable dataTable = new DataTable();
dataTable = testCalculator.GetValue("Test");
return dataTable;
}
Working Code
In JavaScript
$.ajax({
type: "POST",
dataType: "Json",
contentType: "application/Json; charset=utf-8",
url: "Test.aspx/GenerateXML",
success: function (result) {
alert(result)
},
error: function (error, e1, e2) {
alert(error);
}
});
C# Code
[WebMethod]
public static DataTable GenerateXML()
{
TestCalculator testCalculator = new TestCalculator();
DataTable dataTable = new DataTable();
dataTable = testCalculator.GetValue("Test");
return dataTable;
}

formdata in ajax call

When I pass formdata in ajax call after json return it does not return on Success or error block just printing value on browser
// And my Controller side code is
[HttpPost]
public JsonResult Create(InquiryModel model)
{
var inquiry = _inquiryService.GetInquiryById(model.Id);
return Json(inquiry.Id, JsonRequestBehavior.AllowGet);
}
// View side
var formData = new FormData();
jQuery.each(jQuery('#QuotationDocument')[0].files, function (i, file) {
formData.append('file-' + i, file);
});
$.ajax({
url: '#Url.Action("Create", "Inquiry")',
data: formData,
contentType: false,
processData: false,
type: "POST",
success: function (data) {
alert("ssss");
},
error: function (msg) {
alert("error", msg.statusText + ". Press F12 for details");
}
});
when I pass only formData it works fine
Try like this;
$.ajax({
url: '#Url.Action("Create", "Inquiry")',
data: formData,
datatype: "json",
type: "POST",
success: function (data) {
alert("ssss");
},
error: function (msg) {
alert("error", msg.statusText + ". Press F12 for details");
}
});

asp.net web forms [WebMethod]

I have a problem with my [WebMethod] when I return Json data List<Contract> from DB using Entity Framework
function populateData(pageIndex) {
// populate data from database
$.ajax({
url: "/Pages/App/Docs.aspx/PopulateDataByJquery",
data: "{pageNo: " + pageIndex + ", noOfRecord: 7}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: onError
});
}
function OnSuccess(data) {
alert('good');
}
function onError() {
alert('Failed!');
$('#LoadingPanel').css('display', 'none');
}
This my WeMethod.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Contract> PopulateDataByJquery(int pageNo, int noOfRecord)
{
System.Threading.Thread.Sleep(2000);
Entities4 db = new Entities4();
List<Contract> data = new List<Contract>();
int skip = (pageNo - 1) * noOfRecord;
data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList();
return data;
}
I every time getting ajax error, help me please! I don't know how it fix.
You have to make some changes to your ajax call and WebMethod
function populateData(pageIndex) {
// populate data from database
$.ajax({
url: "Docs.aspx/PopulateDataByJquery",
data: "{pageNo: pageIndex, noOfRecord: 7}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: onError
});
}
function OnSuccess(data) {
alert('good');
}
function onError() {
alert('Failed!');
$('#LoadingPanel').css('display', 'none');
}
Change your WebMethod
[WebMethod]
public static string PopulateDataByJquery(int pageNo, int noOfRecord)
{
System.Threading.Thread.Sleep(2000);
Entities4 db = new Entities4();
List<Contract> data = new List<Contract>();
int skip = (pageNo - 1) * noOfRecord;
data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList();
JavaScriptSerializer TheSerializer = new JavaScriptSerializer()
var TheJson = TheSerializer.Serialize(data);
// for this you need to add using System.Web.Script.Serialization;
return TheJson;
}
For more read this

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

Redirect from Webmethod in Asp.Net

Am new to Asp.Net Programming, Have just started a web project.
Am calling a WebMethod from Aspx page using JSON like below:
<script type="text/javascript">
function getLogin() {
var userName = document.getElementById('TextBox1').value;
$.ajax({
type: "POST",
url: "Services/LogService.asmx/authenticateLogin",
data: "{'userName':'" +userName.toString()+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d)
},
error: function (xhr, status, error) {
// alert(textStatus);
DisplayError(xhr);
}
});
}
function DisplayError(xhr) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message); }
</script>
And WebMethod :
[WebMethod]
public string authenticateLogin(string userName)
{
LoginBO loginBO = new LoginBO();
loginBO.userName = userName.ToString().Trim();
string result = "";
try
{
LoginDao loginDao = DAOFactory.GetDaoFactory().getLoginDao();
result = loginDao.selectUser(loginBO);
}
catch (DBConnectionException)
{
//result = "DB Conenction";
throw new Exception("DB Connection is Down");
}
catch (InvalidLoginException)
{
//HttpResponse res = new HttpResponse();
//HttpResponse.ReferenceEquals.Redirect("~/Login.aspx");
throw new InvalidLoginException("Login Is Invalid");
}
catch (Exception)
{
throw new Exception("Uanble to Fetch ");
}
int ctx = Context.Response.StatusCode;
return result;
}
After Successful Authentication, I want to redirect user to another aspx page.
What is the best practice to do ?
Thanks
Samuel
Add a redirect to the success section of your getLogin() function:
success:
function (response) {
alert(response.d);
windows.location.href = "http://url.for.redirect";
}
(Or use some other method for redirecting within jQuery/Javascript).
In your Ajax method
success: function(msg) {
alert(response.d);
window.location = "xyz.aspx";
},
success: function (response) {
alert(response.d)
window.location.href = "some.aspx";.
}
I think it will help you.

Resources