I have the following ajax email submit routine on my ASP.NET WebForms web site:
A page provides a user with an input dialog, where he enters data.
A data is packed into a json like this:
var name = $("[id$='clientName']");
var phone = $("[id$='clientPhone']");
var serviceType;
var serviceCost;
$("#SubmitOrder").click(function () {
var currName = name.val();
var currPhone = phone.val();
var json = "{'ClientName':'" + escape(name.val()) + "','ClientPhone':'" + escape(phone.val()) + "','ServiceType':'" + serviceType + "','ServiceCost':'" + serviceCost + "'}";
var ajaxPage = "/sendmail.aspx?Send=1";
var options = {
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
success: function (response) {
$("#ResMsg").html(response);
},
error: function (msg) { alert("failed: " + msg); }
};
$.ajax(options);
});
and is sent to a sendmail.aspx for procession. sendmail.aspx is just a webforms page that, when debugged, works just fine. It receives and parses the JSON correctly, then initiates an async mail sending routine.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
SendMail();
}
private void SendEmail()
{
//Bunch of parsing and mail sender init
mailSender.MessageSent += new MessageSentEventHandler(OnMessageSent);
//Here we have subscribed to an async event that occurs when mail sender is done.
// Other unimportant stuff
mailSender.SendMessage(settings["mail.feedback.to.name"], settings["mail.feedback.to.email"], settings["mail.feedback.subject"], body);
}
void OnMessageSent(object sender, MessageSentEventArgs args)
{
if (args.Status == MailSentStatus.Sent)
{
Response.Write("Everything is fine");
}
else
{
Response.Write("Oops. Error!");
}
}
The problem:
On my client page, whenever the response is received from the mail sender I get a
failed: [object Object] message box.
Apparently my error: method gets executed instead of success:. But the mail sender sends messages just fine.
What is the correct way to respond to a jquery .ajax() call from an ASP.NET? What am I doing wrong in my case?
You told
$.ajaxto expectdataType: "json", so it’s trying (and failing) to parse the returned HTML as JSON.