I am newer to both AJAX and MVC and I am trying to make a confirmation interaction.
What I am trying to do is display a box, the user will enter a value and click submit, and then box will AJAX POST (I think that is what I am supposed to use) to the Controller and return a true or false. I cannot seem to figure out how to make this interaction work however.
If I run debug I can see my value getting passed into the Controller, but it ignores my if
statement to check if the string was correct. Beyond that, I am not sure how to return a true/false and deal with it in my AJAX.
Here is my "best guess" so far.
AJAX/JS
<script type="text/javascript">
function preloadFunc() {
var prompting = prompt("Please enter your password", "****");
if (prompting != null && prompting != null) {
$.ajax({
url: '/Admin/magicCheck',
type: 'POST',
data: {
'magic': prompting
},
success: function () {
//let page load
},
error: function () {
preloadFunc(); //re-ask
}
});
}
else {
window.location.replace("google.com"); //Pressing Cancel
}
}
window.onpaint = preloadFunc();
</script>
Controller
[HttpPost]
public ActionResult magicCheck(string magic)
{
bool success = false;
if (magic == "poof")
{
success = true;
}
else
{
success = false;
}
return RedirectToAction("Index");
}
All help greatly appreciated as I am new to this!
Read all the comments below your post as there are many issues here, but as far as comminication AJAX and returning:
Change the controller to return JSON, like this:
[HttpPost]
public ActionResult magicCheck(string magic)
{
bool success = false;
if (magic == "poof")
{
success = true;
}
else
{
success = false;
}
return Json( new { Success = success });
}
Now that the controller is returning JSON you need to change your js to handle it:
$.ajax({
url: '/Admin/magicCheck',
type: 'POST',
data: 'magic=' + prompting, //<-- you didn't need to send JSON for this, you'd have to change your controller if you are going to send a JSON object also... you just need this for now
success: function (resp) {
//let page load
if ( resp.Success ){
// success...
}
else{
//fail
}
},
error: function () {
preloadFunc(); //re-ask
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.