Return True or False in jQuery’s Success

Asked

Viewed 1,392 times

0

< script type = "text/javascript" >

  $(document).ready(function() {

    $('#btnEnviarDados').click(function() {

      var strFomr = $("form").serialize();

      $.ajax({
        url: $("form").submit(),
        type: "POST",
        data: strFomr,
        contentType: 'application/json; charset=utf-8',
        cache: false,
        success: function(ret) {
          if (ret == true) {
            alert('funcionaou');
            location.href = "@Url.Action("
            Contact ")"
          } else
            alert("noa funcionou a rquisicao");
        }
      });
    });
  }) < /script>

Man Controller:

 public JsonResult CadastroUsuario(Usuario _usuario )
    {
        if (ModelState.IsValid)
        {
            return Json(new{ret = true });
        }
        else
        {
            return Json(new { ret = true });
        }            
    }

the problem is that in View returns only the value true or false as shown in the image, and I wanted the return to success of jquery.

Retorno do jQuery

Does anyone have any idea how I return the value true or false in the success jQuery to display a alert of the return?

  • Possible duplicity: http://answall.com/questions/29382/fun%C3%A7%C3%A3o-ajax-return-value

  • 1

    I think the right thing would be something like: success: function(data) {&#xA; if (data.ret == true) {

4 answers

4

Try it this way: in JS, directly validate the returned object and in C# return the boolean without creating an object to store this value. As in the example I left below and see if it works:

<script type = "text/javascript">
  $(document).ready(function() {

    $('#btnEnviarDados').click(function() {

      var strFomr = $("form").serialize();

      $.ajax({
        
        type: "POST",
        url: $("form").submit(),
        data: strFomr,
        dataType: "json",
        cache: false,
        success: function(data) {
          if (data) {
            alert('Valor de retorno é verdadeiro!');
          } else
            alert("Valor de retorno é falso!");
        }
      });
    });
  }) 
< /script>

    public JsonResult CadastroUsuario(Usuario _usuario )
    {
        if (ModelState.IsValid)
        {
            return Json(true);
        }
        else
        {
            return Json(false);
        }            
    }
  • 1

    Faria minor: public JsonResult CadastroUsuario(Usuario _usuario ) { return ModelState.IsValid; }.

2

You need to put the attribute [HttpPost] on top of your method.

[HttpPost]
public JsonResult CadastroUsuario(Usuario _usuario )
    {
        if (ModelState.IsValid)
        {
            return Json(new{ret = true }, JsonRequestBehavior.DenyGet);
        }
        else
        {
            return Json(new { ret = true }, JsonRequestBehavior.DenyGet);
        }            
    }

1

The way you’re trying to use Ajax’s comeback doesn’t work. The ideal is to externalize this result and work with it from the "outside". Below is a demonstration, "untested" how to dock the Ajax function. Make sure that the data to be sent is correct and the address of "webservice".

var ajaxParams  = {
    type:   'POST',
    data:   $('form').serialize (),
    url:    $('form').submit (),
    contentType:    'json',
    cache:  false
};

var httpRequest =   function (params, fn) {
    $.ajax ({
        type:   params.type,
        data:   params.data,
        contentType:    params.contentType,
        cache:  params.cache,
        url:    params.url
        success:    function (jsonData) {
            fn (jsonData);
        }
    });
};


$('#btnEnviarDados').bind ('click', function (event) {
    event.preventDefault ();

    httpRequest (ajaxParams, function (jsonObject) {
        if (jsonObject) {
            console.log ('funcionou...')
        }
        else {
            console.log ('Há algo errado aqui...');
        }
    });
});

0

 $.ajax({
        url: $("form").submit(),
        type: "POST",
        data: strFomr,
        //Retire isso. contentType diz o formato enviando para o servidor
        //contentType: 'application/json; charset=utf-8',
        //Use dataType que diz o formato esperado de resposta
        dataType: 'JSON',
        cache: false,
        //success: function(ret) {
        success: function(resposta) {
          //if (ret == true) {
          if (resposta.ret == true) {
            alert('funcionaou');
            location.href = "@Url.Action("
            Contact ")"
          } else
            alert("noa funcionou a rquisicao");
        }
      });

contenttype: defines the type of data being sent to the server. The default is application/x-www-form-urlencoded; charset=UTF-8, which is suitable for most cases.

dataType: sets the response format you are expecting to receive from the server. It can be text, xml, html, script, json, jsonp. If no value is entered, jQuery will try to deduct based on the MIME type of the answer.

http://api.jquery.com/jquery.ajax/

  • 1

    It would be interesting to translate the yellow picture, because not everyone who visits the site can understand English.

  • @diegofm, sorry. I edited and included the translation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.