I am trying to program a "simple" .ajax call. When a button is pressed, I want to check to see if the email in one of the fields of my form is a valid email. If so, I want to progress to the method which attempts to send the email.
Here is my .ajax call in JavaScript:
var emailAddress = $("#EmailAddress_Field").val();
$.ajax({
method: "POST",
url: checkEmailUrl,
data: emailAddress,
contentType: "json",
success: function () {
self.sendEmail(); //currently just prints "success"
},
error: function () {
self.showFailure();
}
});
Here is my method in my Controller:
public ActionResult CheckEmail(string emailAddress)
{
try
{
MailAddress address = new MailAddress(emailAddress);
}
catch(System.FormatException e)
{
return Json(false);
}
return Json(true);
}
I've changed everything around, originally my C# method was async and returned a Task<ActionResult> but I seemed to be having race issues so I thought it better to make it synchronous. I have also tried returning in the format Json(new { Success = false }) but this did not seem to work either. I've tried adding the traditional: true flag under the .ajax call, as suggested in another Stack question, but to no avail. The contentType has also gone back and forth from application\json to json.
Currently, whether the email is valid or not, upon button press the error function is performed. Under Chrome's Inspect > Network tab I can see the call to CheckEmail but the status is 500, with the response {"ClientMessage":"Unknown Error has occurred.", "Code":1}, and the call stack's most recent call is in jquery.js send:
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send((options.hasContent && options.data) || null); // There is an error here
The second most recent call is in jquery.js ajax:
try {
state = 1;
transport.send(requestHeaders, done); // Call was here
} catch (e) {
...
Using Debug and stepping over I can tell that my C# function is returning Json(true) correctly when an email is valid, but somehow the Server is not parsing this correctly and it errors.
If anyone knows how to get .ajax to report a success, please let me know.
you have to fix ajax and remove content type json
$.ajax({
method: "POST",
url: checkEmailUrl,
data: {emailAddress:emailAddress},
success: function () {
self.sendEmail(); //currently just prints "success"
},
error: function () {
self.showFailure();
}
});