Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return true or false from my MVC to an jQuery Ajax?

I have code that is part of an $.ajax call to MVC. Two functions that I hope will get executed based on a true or false from my controller.

success: function () {
    $('#mark').html('<span style='color: Green;'>&nbsp;&nbsp;Correct</span>');
},
error: function () {
    $('#mark').html('<span style='color: Red;'>&nbsp;&nbsp;Incorrect</span>')
}

But what should I return from the controller so I can call either the success or error? I didn't try Ajax before so can I just return

return(true) or 
return(false)

In which case what would be the datatype I use for the return value in MVC?

like image 419
MikeSwanson Avatar asked Apr 22 '11 15:04

MikeSwanson


2 Answers

I prefer this technique over return Content("true")

return Json(true);

This way, you will get a boolean passed to your callback:

success: function (response) {
  if (response) {
    // success code here
  } else {
    // error code here
  }
}
like image 143
Johnny Oshika Avatar answered Oct 04 '22 02:10

Johnny Oshika


this "success" and "error" has nothing to do with the actual return value, but with the http return code. if your server returns a http 200 code, the request was sucessfull. otherwise if the server returns a 50x or 40x code than the request failed.

in your case you can actually return an empty object.

the fail codes are returned automatically by the server in cases there is an exception in your code, than it would be an error 501 code would be returned from server and the ajax request failed.

check this out http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

in your case you should do something like chaudcommeunnem has posted. but you also can leave your error passage, just in case the server failed the request.

hth

like image 33
nWorx Avatar answered Oct 04 '22 02:10

nWorx