Reputation: 385
So I'm just trying to post data to a page with ajax.. but it doesn't work.. any ideas?
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
username: $('#username').val(),
firstname: $('#firstname').val(),
lastname: $('#lastname').val(),
email: $('#email').val(),
password1: $('#password1').val(),
password2: $('#password2').val(),
}),
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
}
That is my ajax post -
@{
if (IsPost)
{
var password = Request["password1"];
var username = Request["username"];
}
}
That is the page where its being posted to but when I look at the console it says (cancelled) and the error functions pops the alert.
I appreciate your help :) thank you
Upvotes: 1
Views: 472
Reputation: 1372
The best option for you is to serialize your form an submit it. If your form id is "userdata" your Ajax post should be:
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
dataType: "text",
data: $("#userdata").serialize(),
success: function (result) {
alert("success " + result);
},
error: function () {
alert("Failed");
}
};
and your /REST/GetResponse.cshtml file something like:
@{
var password = Request["password1"];
var username = Request["username"];
// and so on ...
try
{
// do something...
Response.Write(username);
}
catch (Exception ex)
{
Response.StatusCode = 500;
Response.Write(ex.Message);
}
}
Instead, if you want to retain your original Ajax post, I think that your /REST/GetResponse.cshtml should be:
@{
string input;
using(var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
var user = Json.Decode(input);
var password = user.password1;
var username = user.username;
// and so on ...
try
{
// do something...
Response.Write(username);
}
catch (Exception ex)
{
Response.StatusCode = 500;
Response.Write(ex.Message);
}
}
Upvotes: 1
Reputation: 15003
ASP.Net Web Pages normally expect POST
requests to be sent as application/x-www-form-urlencoded
rather than JSON. Just set the contentType
to that (or don't set it at all, since that's the default) and get rid of the JSON.stringify()
call. jQuery will automatically do the encoding for you.
Upvotes: 2