Search code examples
jqueryrazorengine

Unable to show the $.ajax results in labels


I have created an MVC ASP.Net View using Razor and the view has a search that works just fine if I reload the view (send the search parameters to a specific controller and then reload the view to show the due results).

However now I need to use jQuery to send the search parameters to the controller and receive/show the results in specific labels of my view. I have coded this in the search click event

$.ajax({
  type: "POST",
  url: '@Url.Action(actionName: "PrecalificacionLibreGestion", controllerName: "Home")',
  datatype: "json",
  contentType: "application/json",
  data: JSON.stringify({
    NUMERO: numero,
    NIT: nit
  }),
  beforeSend: function() {
    $("#loader").show();
  },
  success: function(data) {
    $("#loader").hide();
    if (data.respuesta == "OK") {
      $("#lblPrecalificacion").empty();
      $("#lblAccion").empty();
      $("#lblPrograma").empty();
      $("#lblPrecalificacion").val("CODIGO PROGRAMA: " + data.codigo_programa);
      $("#lblAccion").val("ACCIÓN FORMATIVA: " + data.accion_formativa);
      $("#lblPrograma").val("PROGRAMA: " + data.precalificacion);
    }

    if (data.respuesta == "OKNO") {
      alert("no se encontró");
    }
  }
});

It sends the two parameters to the controller and also the controller returns the correct information according to the search parameters, but I can't manage to show the info in the label elements.

What I get is an empty web page with the results in JSON format as shown below:

enter image description here

Could you tell me what I am doing wrong please.

this is the search button

<button class="btn btn-default" type="submit" id="btn-buscar"><span class="glyphicon glyphicon-search"></span></button>

Solution

  • As you're running the code under the click of the submit button the issue is that the form submission is causing a page redirect before your AJAX logic runs. To fix this you need to call preventDefault() on the event which is raised.

    However a better idea again would be to hook to the submit event of the parent form element instead of the click of the button. Try this:

    $('#yourForm').on('submit', function(e) {
      e.preventDefault();
    
      $.ajax({
        // your AJAX logic here...
      });
    });