I'm attempting to use jQuery's $.ajax() function to post form variables to an MVC route. Problem is, when the code hits my MVC action, all of the parameters are null, even though data is being passed to them:
jQuery:
$(function () {
$('#signupform').submit(function (e) {
e.preventDefault();
if ($(this).valid()) {
var postData = '{name : "' + $("#Name").val() + '", email : "' + $("#Email").val() + '", message : "' + $("#Message").val() + '" }';
$.ajax({
url: "/api/contact-form-post",
data: postData,
type: "get"
})
.complete(function (data) {
$("#formContainer").html($("#formThankYou").html());
});
}
});
});
calling alert(postData) outputs the following:
{name : "Scott Smith", email : "[email protected]", message : "test message" }
MVC Action:
public JsonResult ContactFormPost(string email, string name = "" , string message = "")
{
AddEmailToMailingList(email);
if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(message))
{
InsertContactMessage(email, name, message);
}
return Json(true);
}
Using FireBug to examine the request reveals that this is the URL that's being called. Obviously the url parameters are not in the correct format, but I can't figure out why.
http://localhost:10637/api/contact-form-post?{name%20:%20%22Scott%20Smith%22,%20email%20:%20%[email protected]%22,%20message%20:%20%22Test%20message%22%20}
Am I making any obvious mistakes here that would cause the parameters of my ContactFormPost method to always be null?
jQuery $.post() Method The $.post() method requests data from the server using an HTTP POST request. Syntax: $.post(URL,data,callback); The required URL parameter specifies the URL you wish to request.
ajax({ url: 'superman', type: 'POST', data: { field1: "hello", field2 : "hello2"} , contentType: 'application/json; charset=utf-8', success: function (response) { alert(response. status); }, error: function () { alert("error"); } }); jquery. ajax.
Try this: $. ajax({ type:'GET', url:'your url', data:{ var1: value1, var2: value2}, success:function(response) { } });
The jqXHR Object. The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method.
Unquote postData
, pass $.ajax a real JS object.
var postData = {
name: $("#Name").val(),
email: $("#Email").val(),
message: $("#Message").val()
};
Trinidad is correct about unquoting the object. You only need to do that with ASP.NET AJAX services, which expect the data to come in as a JSON string.
Another issue is that your return statement needs to explicitly allow the GET verb since you're trying to use it:
return Json(true, JsonRequestBehavior.AllowGet);
Trinidad is right, but if you must post JSON, then use the POST method, not GET.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With