AJAX call a function with a parameter - javascript

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

Related

AJAX Response Text Is Always Empty

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

display data from database in angularjs and json

I am trying to display data from database in angularjs using webservice
But geting Error[object Object] while retriving data
My web method is:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function GetData() As String
Dim strCon As SqlConnection = New SqlConnection("Data Source=PC12\SQL2;Initial Catalog=TestData;User ID=abc;Password=xxxx; timeout=0;")
Dim dt As DataTable = New DataTable
Dim da As SqlDataAdapter
Dim cmd As SqlCommand = New SqlCommand("select * from user", strCon)
strCon.Open()
da = New SqlDataAdapter(cmd)
da.Fill(dt)
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object)
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)()
For Each col As DataColumn In dt.Columns
row.Add(col.ColumnName, dr(col))
Next
rows.Add(row)
Next
Return serializer.Serialize(rows)
End Function
My javascript to call webservice:-
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'WebService1.asmx/GetData',
data: '{}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
alert("Result: " + data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown + XMLHttpRequest + textStatus);
}
});
});
Got the solution
I haven't added attribute in my web service.
Only Web services with a attribute on the class definition can be called from script.
After adding got the data.

Why can't I use my JSON data?

I am trying to read some JSON data from an AJAX function. Here is the AJAX I am using:
$.ajax({
type: 'POST',
cache: false,
url: 'Default.aspx/GetCoords',
data: "{}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
var text = JSON.stringify(data);
$("#jsonData").html(text);
alert(text);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I also have use JSON.parse in place of stringify, and objects return undefined or not at all. This comes from a C# function which looks like this:
[WebMethod]
[ScriptMethod]
public static string GetCoords()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
System.Diagnostics.Debug.WriteLine(serializer.Serialize(rows));
return serializer.Serialize(rows);
}
}
}
It is returning JSON data: Here is what it looks like on the Debugger Console and when I call the function in a paragraph tag:
[{"DrawID":925,"xCoord":466,"yCoord":201},{"DrawID":924,"xCoord":385,"yCoord":318},{"DrawID":923,"xCoord":768,"yCoord":159},{"DrawID":922,"xCoord":543,"yCoord":214},{"DrawID":921,"xCoord":329,"yCoord":172}]
However, when I send it to the paragraph tag in JQuery or call it in an HTML paragraph, here is what it looks like:
{"d":"[{\"DrawID\":925,\"xCoord\":466,\"yCoord\":201},{\"DrawID\":924,\"xCoord\":385,\"yCoord\":318},{\"DrawID\":923,\"xCoord\":768,\"yCoord\":159},{\"DrawID\":922,\"xCoord\":543,\"yCoord\":214},{\"DrawID\":921,\"xCoord\":329,\"yCoord\":172}]"}
I have two questions:
(1) Why am I not able to use this data to insert the xCoords and yCoords into a canvas? I have tried many formats: (data.d[0].xCoord, d[0].xCoord, text.d[0].xCoord, text[0].xCoord, and so on).
(2) Is the second format above going to be a problem in trying to extract that data for painting on the canvas (it's the backslashes that I am wondering about)?
Thanks.
In your success function, you do not stringify or json.Parse the 'data' variable, but rather the data.d variable. 'd' is the member of the json return that you need to parse.
So, change, var text = JSON.stringify(data); to var text = JSON.stringify(data.d); and you should be golden.
You need to use parseJSON, as such:
myThing = {"d":"[{\"DrawID\":925,\"xCoord\":466,\"yCoord\":201},{\"DrawID\":924,\"xCoord\":385,\"yCoord\":318},{\"DrawID\":923,\"xCoord\":768,\"yCoord\":159},{\"DrawID\":922,\"xCoord\":543,\"yCoord\":214},{\"DrawID\":921,\"xCoord\":329,\"yCoord\":172}]"};
myJSON = $.parseJSON(myThing.d);
alert (myJSON[0].DrawID); //etc
I had to return rows in my C# code as #lujcon said:
[WebMethod]
[ScriptMethod]
public static List<Dictionary<string, object>> GetCoords()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
System.Diagnostics.Debug.WriteLine(serializer.Serialize(rows));
return rows;
}
}
}
Then I had to change my var text = JSON.stringify(data); to var text = JSON.stringify(data.d); as #JustinRusso said. Works now. Thanks, everyone.
[WebMethod]
[ScriptMethod]
public static Dictionary<string, object>[] GetCoords()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
System.Diagnostics.Debug.WriteLine(serializer.Serialize(rows));
return rows.ToArray();
}
}
}
Java script:
$.ajax({
type: 'POST',
cache: false,
url: 'Default.aspx/GetCoords',
data: "{}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$.each(data, function(index, value) {
var x = value.xCoord;
/// do something with it ;)
});
var text = JSON.stringify(data);
$("#jsonData").html(text);
alert(text);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});

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

MVC 3 .NET Fill fields dynamically

I have a field for a ZIP Code.
I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur).
This Event will execute a select in database and get the address and fill the other fields with this information.
I read that is not a good idea execute a Controller Method from the View.
So, how can I develop this?
My zip code field:
<div class="editor-field">
#Html.Label("ZIP CODE")
#Html.Editor("zipCodeClient")
</div>
Thanks!
If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.
$('#zipCodeClient').blur(function() {
var zipCode = $(this).val();
if(zipCode.length >= 5 && zipCode.length <= 10) {
$.ajax({
type: 'GET',
data: { ZipCode: zipCode },
url: 'something/ZipCodeToAddressService',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var responseObject = jQuery.parseJSON(data);
$('#cityTextBox').val(responseObject.City);
$('#stateTextBox').val(responseObject.State);
}
});
}
else {
// zip code not valid
}
});
In WCF:
[ServiceContract()]
public interface IAddressServices
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ZipCodeToAddressService(string ZipCode);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
public string ZipCodeToAddressService(string ZipCode)
{
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = ZipCode;
sqlConnection.Open();
SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable tbl = new DataTable();
tbl.Load(sDR);
sDR.Close();
var citystateData = from DataRow Row in tbl.AsEnumerable()
select new
{
City = Row.Field<string>("City"),
State = Row.Field<string>("State")
};
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
js.Serialize(cityStateData, sb);
string rtrnCityStateData = sb.ToString();
return rtrnCityStateData;
}
}
}
}

Categories

Resources