I don't know what happened but one of my Ajax query stops working. I have 2 Views, in first one user choose colors of buttons
function choose()
{
var a = document.getElementById("button1").style.backgroundColor.toString();
var b = document.getElementById("button2").style.backgroundColor.toString();
var c = document.getElementById("button3").style.backgroundColor.toString();
var d = document.getElementById("button4").style.backgroundColor.toString();
if (a && b && c && d != "") {
$.ajax({
url: '@Url.Action("SetCode", "Home")',
type: 'POST',
data: { a, b, c, d },
}).done(function(res) {
window.location.href = res.newUrl;
}).fail(function(xhr, a, error) {
console.log(error);
});
then in controller the colors are saved in singleton class
Kod o1 = Kod.makeObject();
[HttpPost]
public JsonResult SetCode(string a, string b, string c, string d)
{
o1.FirstColor = a;
o1.SecondColor = b;
o1.ThirdColor = c;
o1.FourthColor = d;
return Json(new { newUrl = Url.Action("Game", "Home") });
};
after that there is a redirection to method in controller "Game" which return View. In this View next user selects the colors and checks if they are correct
public IActionResult Game()
{
return View();
}
function checkcode() {
var a = document.getElementById("button1").style.backgroundColor.toString();
var b = document.getElementById("button2").style.backgroundColor.toString();
var c = document.getElementById("button3").style.backgroundColor.toString();
var d = document.getElementById("button4").style.backgroundColor.toString();
if (a && b && c && d != "") {
$.ajax({
url: '@Url.Action("Check", "Home")',
dataType: "text",
type: 'POST',
data: {a , b, c, d },
success: function (data) {
if (data == true) {
alert("OK")
} else { alert("Error") }
}
});
In controller method I always receive nulls in viarables e,f,g,h. What's wrong?
[HttpPost]
public bool Check(string e, string f, string g, string h)
{
if (o1.FirstColor == e && o1.SecondColor == f && o1.ThirdColor == g && o1.FourthColor == h)
{
return true;
}
else { return false; }
}
CodePudding user response:
You need to change data: {a , b, c, d },
to data: { e:a, f:b, g:c, h:d },
.
If you use data: {a , b, c, d }
,request will pass parameters which name is a,b,c,d
,so you need to change their name to e,f,g,h
.
When using data: {a , b, c, d }
,the request data will be:
When using data: { e:a, f:b, g:c, h:d },
,the request data will be:
Update:
You need to change data == true
to data == "true"
,When you pass true to ajax,the data will be "true"
.