I want to stay on the same page

2

How can I stay on the same page with ajax?

my ajax is

$('#add-user').click(function() {
    $.ajax({
      type: "GET",
      url: "/evaluacion/usuariosSeleccionados",
      data: { 
              fact: JSON.stringify(localStorage.getItem("evaluacion")),
              seleccionados: JSON.stringify(yourArray)
            },
       contentType: "application/json; charset=utf-8",
       dataType: "text",
      success: function(data) {
        document.open("text/html", "replace");                          
        document.write(data);
        document.close();
        window.location.href="/evaluacion/agregarUsuarios"// esto hago para que se quede en la misma pagina

      },
      error: function(err) {
        var msg = 'Status: ' + err.status + ': ' + err.responseText;

      }
    }); 

and my link is

a(href="" id='add-user' class='btn btn-primary') agregar usuarios
  

window.location.href="/ evaluation / addUsers" // this I do for   stay on the same page

it's okay to use window.location.href ???

    
asked by hubman 27.12.2017 в 04:11
source

1 answer

2

I think there are two things that may fail you. By clicking on the <a /> tag you are calling a function and you are missing a event.preventDefault(); that prevents the href of the tag from propagating. And on the other hand I see that you are rewriting the document:

document.open("text/html", "replace");                          
document.write(data);
document.close();

If you need to print the result of ajax I recommend you do something like this:

var result = document.getElementById('result');
result.innerHTML = data;

In your code:

$('#add-user').click(function(event) {
  event.preventDefault();
  $.ajax({
    type: "GET",
    url: "/evaluacion/usuariosSeleccionados",
    data: { 
      fact: JSON.stringify(localStorage.getItem("evaluacion")),
      seleccionados: JSON.stringify(yourArray)
    },
    contentType: "application/json; charset=utf-8",
    dataType: "text",
    success: function(data) {
      $('#result').html(data);
    },
    error: function(err) {
      var msg = 'Status: ' + err.status + ': ' + err.responseText;
    }
  });
});
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

<a href="" id="add-user" class="btn btn-primary">
  Agregar usuarios
</a>

<div id="result"></div>
    
answered by 27.12.2017 / 04:33
source