Why doesn't my ajax call reach my .NET WebMethod? - javascript

I can't for the life of me understand why this code isn't working. I need a second set of eyes to review it - TIA:
This function returns success, but the C# method is not called.
JavaScript
$(function() {
($("#survey").on("submit", function() {
var data = serializeForm();
$.ajax({
type: "POST",
url: "Default.aspx/SaveSurveyInfo",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert('ok');
},
error: function(data) {
alert('failed');
}
}); //ajax
return false;
}));
function serializeForm() {
var data = new Object;
$("#survey input[type='checkbox']").each(
function(index) {
data[$(this).get(0).id] = $(this).get(0).checked ? 1 : 0;
});
data.otherEnviron = $("#survey input[type='text']").val();
var strData = JSON.stringify(data);
return strData;
}
});
Revised:
$(function () {
($("#survey").on("submit", function() {
var data = serializeForm();
alert(data);
$.ajax({
type: "POST",
url: "Default.aspx/SaveSurveyInfo",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('ok-'+ data);
},
error: function (xml, textStatus, errorThrown) {
alert(xml.status + "||" + xml.responseText);
}
}); //ajax
return false;
}));
Note:
strData="{\"ms\":1,\"google\":0,\"PHP\":0,\"otherEnviron\":\".NET\"}"
C# WebMethod
[WebMethod]
private void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
using (SqlConnection scon = new SqlConnection(connectionString))
{
scon.Open();
SqlCommand scmd = scon.CreateCommand();
scmd.CommandType = System.Data.CommandType.StoredProcedure;
scmd.CommandText = "SurveyResults";
scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
scmd.Parameters.AddWithValue("GoogleTranslator", google);
scmd.Parameters.AddWithValue("PHPOkay", PHP);
scmd.Parameters.AddWithValue("other", otherEnviron);
scmd.ExecuteNonQuery();
}
}
Revised C#
[WebMethod]
public static void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
try
{
using (SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["C287577_NorthwindConnectionString"].ConnectionString))
{
scon.Open();
SqlCommand scmd = scon.CreateCommand();
scmd.CommandType = System.Data.CommandType.StoredProcedure;
scmd.CommandText = "SurveyResults";
scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
scmd.Parameters.AddWithValue("GoogleTranslator", google);
scmd.Parameters.AddWithValue("PHPOkay", PHP);
scmd.Parameters.AddWithValue("other", otherEnviron);
scmd.ExecuteNonQuery();
scmd.Dispose();
}
} catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
This is still not working. No error msg is shown, only ok.

because WebMethod must be public and static
Similar question: ASP.NET jQuery error: Unknown Web Method
If you need more security around your ajax call, try moving it to a web service.

public static void SaveSurveyInfo
The method should be static and public in aspx pages to be hit.
In asmx it can be just public.

Related

Ajax POST returns undefined error from a ashx page

I keep receiving the undefined error. Here is the ajax method.
function testing() {
var data = JSON.stringify(
{
"TestID1": "12345",
"TestID2": "12345",
"TestID3": "12345",
});
$.ajax({
type: "POST",
url: "Test.ashx",
data: data,
//async: false,
//cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.ID);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
});
}
Here is the controller/handler.
public void ProcessRequest(HttpContext context)
{
string jsonString = String.Empty;
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(HttpContext.Current.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
JavaScriptSerializer jSerialize = new JavaScriptSerializer();
var receipt = jSerialize.Deserialize<Receipt>(jsonString);
if (receipt != null)
{
InsertData(receipt.TestID1, receipt.TestID1, receipt.TestID1);
var wrapper = new { ID = receipt.TestID1};
context.Response.Write(JsonConvert.SerializeObject(wrapper));
//context.Response.Write("{ \"data\": [1,2,3] }");
//context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
Right now I am getting undefined error, but I was getting the "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data" until recently. The data that is being posted is working since the InsertData() function inserts the correct data. I also tried setting the async function in the ajax method to false, but no luck. Also, tried sending specific responses (like the one commented out) and so far none have succeeded.

How to display data from server in textarea

I have below code in C# which adds data in Dictionary
public static Dictionary<int, string> ReadFile()
{
Dictionary<int, string> datalist = new Dictionary<int,string>();
var lines = File.ReadAllLines(#"C:\\temp\\Sample.txt");
int i = 1;
foreach (var line in lines)
{
datalist.Add(i, line);
i++;
}
return datalist;
}
Now, I want to display Dictionary data separated by key line by line in textarea. Below is my UI code
<button type="button" id ="GetFlatFile">Click Me!</button>
<div id ="DisplayFlatFile">
</div>
function GetFlatFileAndSetupColumn() {
$("#GetFlatFile").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/ReadFile",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (jsondata) {
mydata = jsondata.d;
$('#DisplayFlatFile').empty();
$('#DisplayFlatFile').append(mydata);
}, error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
});
});
}
How to do it?
First, GetFlatFile is not a <textarea> element, it's <div> element. Assumed that jsondata.d contains dictionary values returned from code-behind method, you can use jQuery.each() to iterate values:
function GetFlatFileAndSetupColumn() {
$("#GetFlatFile").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/ReadFile",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (jsondata) {
mydata = jsondata.d;
$('#DisplayFlatFile').empty();
// iterate keys and values here
$(mydata).each(function (key, value) {
// data display example
$('#DisplayFlatFile').append(key + ' - ' + value);
// line break per iteration
$('#DisplayFlatFile').append('<br />');
});
}, error: function (x, e) {
alert("The call to the server side failed. " + x.responseText);
}
});
});
}
Additionally, your code-behind method should be marked with [WebMethod] attribute :
[WebMethod]
public static Dictionary<int, string> ReadFile()
{
Dictionary<int, string> datalist = new Dictionary<int, string>();
var lines = File.ReadAllLines(#"C:\\temp\\Sample.txt");
int i = 1;
foreach (var line in lines)
{
datalist.Add(i, line);
i++;
}
return datalist;
}
Related issue:
How to get data from C# WebMethod as Dictionary<> and display response using jquery ajax?

My jquery ajax call is not working when I call web services which retrieves data from database

I am new working with jquery ajax calls in fact my first time and, I am running into a issue here my web service is working but for some reason when I try to call it from jquery ajax the data is not retrieve.
Please I've been working the whole day on this and I need to finish it tonight.
My web method is this :
public Didyoumean SayHello(string search)
{
Didyoumean Didyoumean = new Didyoumean();
string cs = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand ("USP_DidYouMean",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("#search",search);
cmd.Parameters.Add(parameter);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Didyoumean.SearchInput = reader["detail"].ToString();
}
reader.Close();
con.Close();
}
return Didyoumean;
}
my Didyoumean class is this:
public class Didyoumean
{
public string SearchInput { get; set; }
}
my ajax call is this (the error is most likely to be here)
function bla() {
var SearchInput = document.getElementById("#locationSearchInput").value;
var DataObject = { search: SearchInput };
$.ajax({
type: "POST",
url: "/kiosk/EmailCoupon.asmx/SayHello",
data: JSON.stringify({dataObject}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.tags_select a').html(data.d);
},
error: function () {
$('.tags_select a').html("<p>no suggestion</p>")
}
});
}
and finally my html
<input id="Button1" type="button" value="button" onclick="bla()"/>
<div class="tags_select">
Basically what I am trying to do is depending on the data in my database the application give suggestions for spelling errors.
note: do not pay attention to the name of the functions and methods this is just a test.
Your service might be like this
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public Didyoumean SayHello(string search)
{
Didyoumean didyoumean = new Didyoumean();
didyoumean.searchInput = "result of " + search;
return didyoumean;
}
}
and your javascript is
function test() {
var SearchInput = "test";
$.ajax({
type: "POST",
url: "/WebService1.asmx/SayHello",
data: JSON.stringify({search:SearchInput}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var didYouMean = data.d;
alert(didYouMean.searchInput);
},
error: function (e) {
console.log(e);
}
});
}

Pass json/javascript data/objects to c# function using ajax

I'm using FullCalendar (http://arshaw.com/fullcalendar/) and I need help with passing data using json to a c# function in the code behind page of my ASP.net page.
I am using json to load data like so in my FullCalendar web application:
Code behind:
[WebMethod]
public static List<Event> GetEvents()
{
List<Event> events = new List<Event>();
events.Add(new Event()
{
EventID = 1,
EventName = "EventName 1",
StartDate = DateTime.Now.ToString("MM-dd-yyyy"),
EndDate = DateTime.Now.AddDays(2).ToString("MM-dd-yyyy"),
EventColor = "red"
});
events.Add(new Event()
{
EventID = 2,
EventName = "EventName 2",
StartDate = DateTime.Now.AddDays(4).ToString("MM-dd-yyyy"),
EndDate = DateTime.Now.AddDays(5).ToString("MM-dd-yyyy"),
EventColor = "green"
});
return events;
}
asp.x page:
events: function(start, end, callback)
{
$.ajax(
{
type: 'POST',
contentType: 'application/json',
data: "{}",
dataType: 'json',
url: "Calendar.aspx/GetEvents",
cache: false,
success: function (response) {
var events = $.map(response.d, function (item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.end = new Date(item.EndDate);
event.title = item.EventName;
event.color = item.EventColor;
return event;
})
callback(events);
},
error: function (err) {
alert('Error');
}
});
},
This is working fine. Now I want to save data by calling a function and passing it data. Here is what I have done so far:
Code behind:
[WebMethod]
public static bool SaveEvents(List<Event> events)
{
//iterate through the events and save to database
return true;
}
asp.x page
function save() {
var eventsFromCalendar = $('#calendar').fullCalendar('clientEvents');
var events = $.map(eventsFromCalendar, function (item, i) {
var event = new Object();
event.id = item.id;
event.start = item.start;
event.end = item.end;
event.title = item.title;
event.color = item.color;
return event;
});
$.ajax(
{
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(events), **<-- I have to pass data here but how???**
dataType: 'json',
url: "Calendar.aspx/SaveEvents",
cache: false,
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});
return false;
}
The above ajax post is where I need help with. The variable events contais all the FullCalendar event info.
How do I pass the data 'events' to the function 'SaveEvents'?
I can change the SaveEvents signature if need be.
EDIT
If I change my c# function to use an array like s0:
[WebMethod]
public static bool SaveEvents(Event[] newEvents)
{
return true;
}
And pass the following data through:
data: JSON.stringify({ newEvents: events }),
Then the function 'SaveEvents' gets called with an array of size 4 but all the data values are null, why is this?
Thanks
Obvious from your code that you have a c# class as
public class Events
{
public int EventID {get; set;}
public string EventName {get;set;}
public StartDate {get; set;}
public string end {get; set;}
public string color {get; set;}
}
So take json array. A sample here
// Array which would be provided to c# method as data
var newEvents=[
{
EventID : 1,
EventName : "EventName 1",
StartDate : "2015-01-01",
EndDate : "2015-01-03",
EventColor : "red"
},
{
EventID : 2,
EventName : "EventName 2",
StartDate : "2015-01-02",
EndDate : "2015-01-04",
EventColor : "green"
}
];
Now the ajax request which passes JSON objects to posted URL
$.ajax
({
type: 'POST',
contentType: 'json',
data: {newEvents:newEvents},// Pass data as it is. Do not stringyfy
dataType: 'json',
url: "Calendar.aspx/SaveEvents"
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});
Update :
To make sure that there is nothing else wrong please test your Save Events as. If it goes fine above should work as well, As it is working for me :)
[WebMethod]
public static bool SaveEvents(string EventName)
{
//iterate through the events and save to database
return true;
}
$.ajax
({
type: 'POST',
contentType: 'json',
data: {EventName:'myevet 1'},
url: "Calendar.aspx/SaveEvents",
cache: false,
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});

Ajax jquery sending Null value to Mvc4 controller

I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>

Categories