I am developing an app in asp.net in which I have jquery code in my asp page
var strdata = {
problemID: $("#problemID").val(),
commentText: $("#_1").val(),
empID: $("#empID").val(),
agree: 0,
disagree: 0
};
$.ajax({
type: "POST",
url: "<%= Url.Action("PostComment", "Discussion") %>",
data: strdata,
dataType: "JSON",
success: function (msg) {
if ( msg == 1)
alert("Success" + msg );
}
});
and my controller has code
public bool PostComment(string problemID, string commentText, string empID, string agree, string disagree)
{
return _discussionRepository.postComment(Convert.ToInt32(problemID), commentText, Convert.ToInt32(empID), Convert.ToInt32(agree),Convert.ToInt32( disagree));
}
and model has code
public bool postComment(int problemID, string commentText, int empID, int agree, int disagree)
{
bool result = false;
Comment c = new Comment();
c.ProblemID = problemID;
c.CommentText = commentText;
c.EmpID = empID;
c.Agree = agree;
c.DisAgree = disagree;
_objectModel.Comments.InsertOnSubmit(c);
try
{
_objectModel.SubmitChanges();
result = true;
}
catch (Exception ex)
{
}
return result;
}
Data is saving in database through ajax and jquery but the success message is not showing
If the alert is not running with or without the condition that means the datatype being returned is not the datatype the $.ajax function is expecting.
2 ways to get to the bottom of it:
First open up chrome or firebug and check out the network traffic. If you are getting the result back (the request is being made and the content looks accurate) then your data type is definitely the cause. Try changing the datatype in the request.
Next you could try adding functions other than just success. There is also error, status codes (404,500 etc), beforeSend, etc check the docs.
There are other ways as well :). Fiddler might help too.
To get the result of your AJAX request use the following code in your success handler:
success: function (msg) {
if ( msg.d === true) {
alert("Success" + msg.d );
}
}
You have to access the result via the "d" property.
To get the error message use the following error handler:
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
i think the result returned in 'msg' isnt the number 1. maybe msg == true ?
Related
I have an ASP.NET application sending data through AJAX to a handler withing my application. This works as it should when debugging locally, but as soon as I deploy the solution to the server, the handler only receives an empty string. I tried fiddling around with contentType and dataType, but without luck.
Here is my code so far.
aspx of the sending page, while "myData" is a simple string:
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: myData,
// tried all those content/dataTypes without any luck
//contentType: "text/plain",
//dataType: "text",
//contentType: "application/json; charset=utf-8",
//dataType: "json",
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
.ashx.cs of the receiving handler:
public void ProcessRequest(HttpContext context) {
//string data = new StreamReader(context.Request.InputStream).ReadToEnd();
var data = String.Empty;
context.Request.InputStream.Position = 0;
using(var inputStream = new StreamReader(context.Request.InputStream)) {
data = inputStream.ReadToEnd();
}
if (data != "") {
// doing something with my data here.
// this is never reached while on the server, but works fine locally!
} else {
context.Response.Write("Please supply data to the risk group service!");
}
}
public bool IsReusable {
get {
return false;
}
}
}
The data variable in the .ashx.cs file is filled when debugging locally, but always "" on the server. I have no clue why.
var para={};
para.myData="abcd"
$.ajax({
type: "POST",
url: "handlers/changeRiskGroup.ashx",
data: para,
error: function (xhr, status, error) {
console.log(xhr.responseText);
},
success: function (msg) {
console.log(msg);
}
});
from server side
string myData=contect.Request.Form["myData"].toString();
Easy, just took me ~20 hours to figure out. Found the answer here: Web service returns "301 error moved permanently" in production environment
In short, I created a blank page within my project to ensure no plugins etc were interfering with the jQuery execution. Further, I created a very simple mask to submit certain data to the handler URL. Within this mask I varied different ways to POST data, when I tried implementing the POST as a [WebMethod] I finally got a clue, as the response was "301 moved permanently" from the WebMethod. Therefore I could start investigating and found out that my server was lowercasing the urls, obviously jQuery/HTTP does not like that.
I hope this post helps others struggling with similar problems.
I have an AJAX JS functions which calls a C# MVC HttpPost Controller. This will return an object but for the purposes of debugging I am just trying to return a string.
JS AJAX code:
function UpdateBlogFilters(month, year) {
var url = "/HttpPost/GetBlogPostsPerMonth";
if (month != null && month != "" && year != null && year != "") {
alert(month + " " + year);
$.ajax({
url: url,
data: { monthValue: month, yearValue: year },
cache: false,
type: "POST",
success: function (data) {
console.log("Data " + data);
var markup = "";
},
error: function (response) {
console.log(response.responseText);
console.log("Error: " + response);
}
});
console.log("1");
}
console.log("2");
}
Controller Code:
[HttpPost]
public ActionResult GetBlogPostsPerMonth(int monthValue, int yearValue)
{
.... the non-debug code
return Json("test");
}
This is returning an error, but the responseText and any error information is blank? I have verified that the controller is being called and it is reaching the return statement in the C# without error.
Any help?
Change your C# code to read something like this:
[HttpPost]
public ActionResult GetBlogPostsPerMonth(int monthValue, int yearValue)
{
.... the non-debug code
return Json(new { result = "test" });
}
Ultimately, you want to pass an object into Json(). You can pass an instance of a class, or an anonymous type, or dynamic.
This was the solution. The AJAX call in itself worked fine. All code posted here was correct as per Bhavik.
The issue was that this AJAX request was called onclick of a hyperlink and this hyperlink although having no href set, was refreshing the page and somehow cancelling off the AJAX request. Removing the href to leave
<a onclick="UpdateBlogFilters(5,2014)">
resulted in the object being returned from AJAX successfully.
Why do you have "/HttpPost/" in url? Is that name of a controller that is different from the one you are using to render the view? Can you try without /HttpPost/
var url = "GetBlogPostsPerMonth";
I'm having a lot of trouble making jQuery's autocomplete widget work for me. I am using a list of key/value pairs from a server.
I have the following requirements:
If the user set the id of the value, like he knowes the code of the city
and instad of typing the name of a city he put the code of the city-- I want that the autocomplete will put the name of the city, and it dosn't!!
I edit My Code, now it works!
I add this lines
if (data.d.length == 1 && request.term.match(/\d+/g))
SetValue(textbox, hidden, data.d[0]);
else
and the function function SetValue(textbox, hidden, value){
textbox.focus().val(value.Text);
hidden.val(value.Semel);}
Another thing is if one is using the same page for creation and editting - on reloading the page while editting, you have to recreate all the spans etc for the values, and I want to send from the server just the code of the autocomplete, not the text value, and I want when i will set the value into the textBox, the autoComplete will start to work and will bring the value from the server
But with this I get still stuck:
I Dont know how to trigger the “autocomplete” event with send the value (the request value)
Here is My C# code:
[WebMethod(EnableSession = true)]
[ScriptMethod]
public List<IEntityBase> FetchList(string Text, string Code, string Dspl, int NumRecordes, string TableName)
{
Text = Server.UrlDecode(Text);
List<Tavla> tvListById = null;
int ignored = 0;
if (int.TryParse(Text, out ignored))
tvListById = TvList.GetTvListById(TableName, ignored, Code, Dspl);if (tvListById != null && tvListById.Count != 0)
return tvListById.Cast<IEntityBase>().ToList();
var fetchShem = TvList.GetData(TableName, Code, Dspl)
.Where(m => m.Shem.ToLower().Contains(Text.ToLower()))
.Take(NumRecordes);
return fetchShem.Cast<IEntityBase>().ToList();
}
and here is my Jquery Code:
enter code here
textbox.autocomplete({
source: function (request, response) {
$.ajax({
url: "AutoComplete.asmx/" + funcName,
data: "{ 'Text': '" + escape(request.term) + "','Code':'" + code + "','Dspl':'" + dspl + "','NumRecordes':'" + numrecordes + "','TableName':'" + tablename + "'}",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
if (data.d.length == 1 && request.term.match(/\d+/g))
SetValue(textbox, hidden, data.d[0]);
else
response($.map(data.d, function (item) {
return {
label: item.Text,
value: item.Semel
}
}));
}
},
error: function (msg) { alert(msg); }
});
},
minLength: minLength,
select: function (event, ui) {
var selectedObj = ui.item;
if (selectedObj) {
textbox.val(selectedObj.label);
hidden.val(selectedObj.value);
} return false; },
});function SetValue(textbox, hidden, value) {
textbox.focus().val(value.Text);
hidden.val(value.Semel);
}
For your first question, it all depends the logic you have tried , just in case if you have an id for any country then this shouldnt be any difficult.
Second query is all about performance of the page, this also shouldnt be any tougher if you try updating the elements based on the search pattern using ajax, where in you have to update just the realted elements,while keeping rest of your Page intact .
refer http://jquery.com/ for better understanding of the same
I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.
On my .cs file I have the following Webmethod
[WebMethod]
public static string IsJobEditable(int jobid)
{
try
{
string isEditable = "false";
JobsBLL jbl = new JobsBLL();
int jobStatusId = jbl.GetJobStatusId(jobid);
if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
{
isEditable = "true";
}
return isEditable;
}
catch (Exception ex)
{
throw ex;
}
}
This function in this case will ALWAYS return TRUE as a string.
On Aspx page I have the following
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (result) {
alert(result);
// This is written out in the alert {"d":"true"}
// I want this in a variable as a string
// so I can do a check on it before I do some other actions
// The format is not a String so i cannot split on it to
// retrieve the "true" part.
},
error: function (err, result) { alert(err); }
});
});
As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.
So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).
Use result.d to get your string.
See this site for an explanation of the .d issue when calling .ajax from ASP.NET: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
try alert(result.d);
You can easily retrieve the "true" part like this:
alert(result.d);
The reason the object is wrapped in the "d" json object is security. You can read about it for example here.
According to two articles I found, I think you want to specify "DataType" as json not as text (since you're expecting a content-type of json to be returned). That may be your issue, though i don't have a sample project in front of me to test on. Your result is also probably result.d as outlined in those same articles.
This solved it:
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
//I finally got the data string i wanted
var resultAsString = result.d;
},
error: function (err, result) { alert(err); }
});
});
So 2 things were done to solve this. I had to change the dataType to "json" and I used the result.d to retrieve my data.
What threw me off was the lack of intellisens on the result object. But the .d (data) property however solved it.
Thanks you to all who contributed to this answer.
I want to post data to a web service with ajax. there is my ajax code:
function Looping() {
var Grid = document.getElementById("<%= gvHastalar.ClientID %>");
var Row;
var Cell;
if (Grid.rows.length > 2) {
for (i = 1; i < Grid.rows.length - 1; i++) {
Row = Grid.rows[i];
Cell = Row.cells[3];
alert(Cell.innerHTML);
var html = $.ajax(
{
type: "POST",
url: "http://localhost:7753/HastaTahlilUyariServisi.asmx/f_HastaninAktarilacakAlislabTestleri",
data: "{_sTcKimlikNo:" + Cell.innerHTML + ",_iKlinikKodu:18001,_bAy:12,_iYil:2009}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: alert('success'),
error: alert('error')
}
).responseText;
Row.style.backgroundColor = "#D3EFD1";
}
}
}
And my webservice function's code is here:
[WebMethod]
[SoapHeader("_ticket", Direction = SoapHeaderDirection.In)]//SoapHeaderDirection.Out
public DataSet f_HastaninAlisLabTahlilleri(string _sTcKimlikNo, int _iKlinikKodu, byte _bAy, int _iYil)
{
try
{
string QSelect =
#"SELECT * FROM [V_EUCLID_SONUC]
WHERE MONTH(KAYITTARIHI) = " + _bAy + #"
AND YEAR(KAYITTARIHI) = " + _iYil +
AND TCKIMLIKNO = '" + _sTcKimlikNo + #"'";
return dbA.ExecuteDataSet(CommandType.Text, QSelect);
}
catch (Exception ex)
{
throw (ex);
}
}
There is a break point on function which is in the web service but debug never go that break point. I pasted webservice's url from browser but may be url is wrong. And when i run project, i have 3 alert.
First Cell's text its normal.Second alert is success and the last alert is error. I want to send parameters to f_HastaninAlisLabTahlilleri and user return dataset. How can i do this?
Thanks in advance
Here are a few remarks about your code:
success and error are callback functions, they should be defined like this:
success: function(data) { alert('success'); },
error: function(XMLHttpRequest, textStatus, errorThrown) { alert('error'); }
ASMX web services use SOAP by default unless you decorate them with ScriptServiceAttribute in which case JSON could be used to invoke a method. It is not clear from your code if the web service is decorated with this attribute.
When you pass parameters, you need to encode them, use JSON. stringify instead of concatenating strings:
data: JSON.stringify({_sTcKimlikNo: Cell.innerHTML,
_iKlinikKodu: 18001,
_bAy: 12,_iYil: 2009});
Use FireBug to inspect network AJAX requests and server responses and post them on StackOverflow to facilitate debugging.
You cannot put a break-point in the web-service code i.e. even the IDE would not let u debug the web-service code.... it is an old legacy the VS.Net IDE has since its inception... lets see if it is resolved in VS 2010.
The url that you have specified in the JQuery script is not equal to the name of the function in c# code. Isn't it the point. *f_HastaninAktarilacakAlislabTestleri* in url and *f_HastaninAlisLabTahlilleri* in c# code. Some reasons for such a problem can be wrong url or deference between argument list of client request and argument list of the server side method or action.