There is a code:

<!DOCTYPE html> <script> function Ajax() { var xhr = new XMLHttpRequest(); var formData = new FormData(document.getElementById('send-form')); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { document.getElementById("demo").innerHTML = xhr.responseText; } } xhr.open("POST", "search.php", true); xhr.send(formData); } </script> <form id="send-form" method="POST"> <input type="search" name="search"> <input type="submit" onclick="Ajax()" value="Поиск"> </form> <div id="demo"></div> 

The problem is that the code is working, but it displays the result for a fraction of seconds and disappears. What could be the problem?

    1 answer 1

    It disappears because the form is sent by pressing the button with type="submit" as usual.

     <input type="submit" onclick="Ajax();return false;" value="Поиск"> 

    or

     <input type="button" onclick="Ajax();" value="Поиск"> 
    • Can you explain why this is happening? - Alexey
    • @Alexey, because submitting the form by pressing the button with type = "submit" goes on as usual. - Grundy
    • @ Alexey Do you understand the first line of my answer? - Igor
    • @Igor, not really. - Alexey
    • @Alexey Imagine that you would not have an onclick attribute. When you click on the submit button, the form is sent to the server, and the page is reloaded (if the server returns the same html), or another page is loaded. This is what you observe. To cancel this standard behavior, you need to make a "button" , or return false from the onlclick handler, or call event.preventDefault(); in the handler event.preventDefault(); . - Igor