Return True or False in jQuery Success

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>

My 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 the image shows, and I wanted the return to be success of jquery .

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

    
asked by anonymous 07.02.2017 / 01:48

4 answers

4

Try to do the following: in JS, validate the returned object and in C # return the boolean direct 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);
        }            
    }
    
07.02.2017 / 13:18
2

You need to put the [HttpPost] attribute 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);
        }            
    }
    
16.02.2017 / 19:16
1

The way you're trying to use Ajax's return does not work. The ideal is to express this result and work with it from the "outside". Below is a demonstration, " Untested " of how to dock the Ajax function. Make sure the data to be sent is correct and the address of the " 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...');
        }
    });
});
    
16.02.2017 / 23:10
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: defines 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 infer based on the MIME type of the response.

link

    
07.02.2017 / 11:08