AJAX Response Text Is Always Empty - javascript

I'm using asp.net web forms and trying to call a web service method from a java script function using AJAX which returns a JSON array with a car number and a car number ID pairs
the web methods resides in the same code behind file of the java script function page
I checked the json variable more than one time using the debugger and made sure it holds a valid JSON array
however when I checked the cars object in the FillLimoCars java script function I found the response text to be an empty array
I'm not sure why this is happening I hope that anyone of you would be able to help
Java Script
function testButton(carModelID) {
$.ajax({
type: "POST",
url: baseURL + "WebPages/NewPages/ListCarRental.aspx/FillLimoCars",
data: "{CarModelID:'" + carModelID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: FillLimoCar
});
}
function FillLimoCar(cars)
{
var rdd_LimoCars = $find("<%=rdd_LimoCarNumber.ClientID %>");
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
for(var i = 0; i < cars.length; i++)
{
;
}
}
C#
[WebMethod]
public static string FillLimoCars(int CarModelID)
{
try
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<LimoFleet> limos = carsBLL.GetCarModelLimoFleet(CarModelID);
List<object> objLimosList = new List<object>();
foreach(var limo in limos)
{
var limoObj = new
{
CarID = limo.CarID,
CarNumber = limo.CarNumber
};
objLimosList.Add(limoObj);
}
var json = serializer.Serialize(objLimosList);
return json;
//Context.Response.Write(objLimos.ToJson());
}
catch (Exception ex)
{
Tracer.Singleton.Log(ex);
return null;
}
}

You have to use success attribute. Inside success, you have to de serialize JSON object.
$.ajax({
type: "POST",
url: baseURL + "WebPages/NewPages/ListCarRental.aspx/FillLimoCars",
data: "{CarModelID:'" + carModelID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
"success": function (json) {
if (json.d != null) {
FillLimoCars(json.d);
}
});

Related

AJAX Call to Update table goes Null - ASP.NET

I'm trying to update my table using Ajax Call through this code
var customer = {};
customer.CustomerId = row.find(".CustomerId").find("span").html();
customer.Nome = row.find(".Nome").find("span").html();
customer.Tipo = row.find(".Tipo").find("span").html();
customer.NCM = row.find(".NCM").find("span").html();
customer.Contabil = row.find(".Contabil").find("span").html();
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
But when I click to update the value it returns a System.NullReferenceException, I can't see where I'm doing wrong.
Here's my Controller Code
public ActionResult UpdateCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer updatedCustomer = (from c in entities.Customers
where c.CustomerId == customer.CustomerId
select c).FirstOrDefault();
updatedCustomer.Nome = customer.Nome;
updatedCustomer.Tipo = customer.Tipo;
updatedCustomer.NCM = customer.NCM;
updatedCustomer.Contabil = customer.Contabil;
entities.SaveChanges();
}
return new EmptyResult();
}
System.NullReferenceException revealed the value updatedCustomer or customer is null.You need check which is null.
And when you want to update a enity in EF,you need add code like :
context.Entry(existingBlog).State = EntityState.Modified;
Howerver,Why you need Query A Entity befor update?I guess you want to do this:
public ActionResult UpdateCustomer(Customer customer)
{
using (CustomersEntities entities = new CustomersEntities())
{
entities.Entry(customer).State = EntityState.Modified;
entities.SaveChanges();
}
return new EmptyResult();
}
This AJAX callback below actually passed JSON string containing JSON object, which is wrong and causing customer contains null value which throwing NullReferenceException (it is strongly advised to put null check before using EF entity context):
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: '{customer:' + JSON.stringify(customer) + '}', // this is wrong
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Instead of passing JSON string like that, just use data: JSON.stringify(customer) or simply passing entire object directly with data: customer and remove contentType setting:
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: customer,
dataType: "json",
success: function (result) {
// do something
}
});
Regarding second issue which selected data from table query is not updated, it depends on auto-tracking setting from EF. If auto-tracking is disabled, you need to set EntityState.Modified before using SaveChanges():
if (customer != null)
{
using (CustomersEntities entities = new CustomersEntities())
{
Customer updatedCustomer = (from c in entities.Customers
where c.CustomerId == customer.CustomerId
select c).FirstOrDefault();
updatedCustomer.Nome = customer.Nome;
updatedCustomer.Tipo = customer.Tipo;
updatedCustomer.NCM = customer.NCM;
updatedCustomer.Contabil = customer.Contabil;
// if EF auto-tracking is disabled, this line is mandatory
entities.Entry(updatedCustomer).State = System.Data.Entity.EntityState.Modified;
entities.SaveChanges();
}
}
Notes:
1) You can see all methods to update existing data with EF in this reference.
2) This fiddle contains sample to make AJAX request from a table contents.

AJAX call a function with a parameter

The following gives me a internal server error.
var jsonStateData;
$.ajax({
type: "POST",
url: "functions.aspx/StateSalesDataString",
data: '{' + 'AL' + '}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
jsonStateData = $.parseJSON(data.d);
}
}).done(function () {
console.log(jsonStateData);
})
This is the function that it is calling
//Returns stores sales datatable
[WebMethod]
public static string StateSalesDataString(string whichState)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Dashboard_VWConnectionStringTest"].ConnectionString);
conn.Open();
string storeSalesQuery = "SELECT StoreSalesTbl.StoreNumb, Lat, Lng, TodayTotalSales, TodayTotalOrders, TodayTotalWebSales, TodayTotalCallSales, TodayTotalIFSales, TodayTotalStoreSales, TodayTotalWebOrders, TodayTotalCallOrders, TodayTotalIFOrders, TodayTotalStoreOrders " +
"From StoreSalesTbl INNER JOIN StoreAddreTbl " +
"ON StoreSalesTbl.StoreID = StoreAddreTbl.StoreID " +
"Where DatetimeTo IN (SELECT max(DatetimeTo) FROM StoreSalesTbl) " +
"AND StoreAddreTbl.State = #stateName";
SqlCommand storeComm = new SqlCommand(storeSalesQuery, conn);
storeComm.Parameters.AddWithValue("#stateName", whichState);
storeComm.CommandType = CommandType.Text;
// Create a DataAdapter to run the command and fill the DataTable
SqlDataAdapter dataAdpt = new SqlDataAdapter();
dataAdpt.SelectCommand = storeComm;
DataTable storeDataTbl = new DataTable();
dataAdpt.Fill(storeDataTbl);
conn.Close();
//convert the datatable to string
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in storeDataTbl.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in storeDataTbl.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
UPDATE
Thank you guys for answering! I think my problem might also be in my c# function. Am I doing anything wrong with the query statement #stateName part?
Because when I changed the query's last line to just
AND StoreAddreTbl.State = 'AL'"
It worked. But when I pass the string whichState in there, it didn't proceed.
Your JSON is invalid. You have it looking like this:
{'AL'}
It should be looking similar to this:
{ "whichState": "AL" }
The proper way to do this in JavaScript:
var myData = {};
myData.whichState = 'AL';
var jsonStateData;
$.ajax({
type: "POST",
url: "functions.aspx/StateSalesDataString",
data: JSON.stringify(myData),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
jsonStateData = $.parseJSON(data.d);
}
}).done(function () {
console.log(jsonStateData);
})
Notice on the data parameter, I'm using JSON.stringify. The JavaScript JSON.stringify function will automatically create your JSON string for you.
When sending the data, give it the key you expect to assign it to. For example, you should be able to do:
data: { "whichState" : "AL" }

Pass Json Object and String Value at once in Ajax

I want to pass a Json Object and String Value together in ajax call. I have attached my code below.
$('#ddcountryid').change(function () {
var jdata = ko.mapping.toJSON(viewModel);
var Cid = $(this).val();
//alert(intCountry);
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")',
type: 'POST',
data: jdata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
});
});
My Action Method
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I am getting wrapper object with Values, but how can get the CID as well. Can anyone please help me on this??.
you can pass it as query string parameter:
var Cid = $(this).val();
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")' + '?cID=' + Cid,
...
server side:
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
OR add a new property to your Wrapper object as Gavin Fang suggested:
var Cid = $(this).val();
viewModel.Cid = Cid;
var jdata = ko.mapping.toJSON(viewModel);
server side code:
public JsonResult PopulateDropDown(Wrapper wrapper)
{
var cid = wrapper.Cid;
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I think you can add a property to store you 'CID' to your viewModel.
and you can get the CID in the 'success' function in javascript in here, I think.
You can achieve this is two ways:
You can add extra field for existing json 'jdata' by defining field jdata.cid = null; and assigning it as jdata.cid = $(this).val();.
Prepare an object to hold both json data and string value:
var obj = {"json": jdata, "string":$(this).value()};
then pass obj in data parameter

The returned code not stopping on ajax call

this is my ajax call function
$.ajax({
url: "webservices/mywebserveice.vb",
data: "{'myactivity':'" + myactivity + "','myproddate':'" + mynewprddatee + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
success: function (data) {
var obj = jQuery.parseJSON(data.d);
//obj[0]["ColumnName"]
var returnlist = new Array();
my vb. code returns some data and pass I to ajax call using
Return New JavaScriptSerializer().Serialize(rows) .It stops at var obj in ajax call for some data but it is not stopping when i pass some other data in vb file. even if i have identical dataset result.
here is a part of vb code
'Convert Dataset to DataReader
Dim dr As DataTableReader = ds.Tables(0).CreateDataReader()
If dr.HasRows Then
Do While dr.Read()
row = New Dictionary(Of String, Object)
For c As Integer = 0 To dr.FieldCount - 1 '//fieldcount gives the column count.
row.Add(dr.GetName(c), dr.GetValue(c)) '//getname->gets the column name; getvalue->gets the col value.
Next
rows.Add(row)
Loop
End If
Return New JavaScriptSerializer().Serialize(rows)
I also tried asycn = false/ture , same issue ..
Any help appreciate

jQuery Ajax - deserialize object to xml

I want to post data to my service and I have chosen XML instead of JSON because I have database logic that will query the xml.
So this is my code so far:
var saveChanges = function (agencyObservable) {
if (agencyObservable) {
var data = ko.toJS(agencyObservable._latestValue[0]);
var options = {
url: '/breeze/SaveData',
type: 'POST',
dataType: 'xml',
data: data,
contentType: "application/json; charset=utf-8"
}
}
Breeze.webapi
[HttpPost]
public void SaveData(XmlDocument xmldoc)
{
tblAgencyQuery tblAgencyQuery = new tblAgencyQuery();
tblAgencyQuery.QueryID = Guid.NewGuid();
//tblAgencyQuery.QueryText = data.ToString();
//tblAgencyQuery.AgencyID = DeserializedData.agencyID;
tblAgencyQuery.CreatedDate = DateTime.UtcNow;
_ContextProvider.Context.tblAgencyQuery.Add(tblAgencyQuery);
_ContextProvider.Context.Entry(tblAgencyQuery).State = System.Data.EntityState.Added;
_ContextProvider.Context.SaveChanges();
}
agencyObservable is knockout observable and I am converting it to a standard javaScript object. But I don't know what to do from here. I want to somehow change my object to XML but is this easy or possible?

Categories

Resources