0

I've got JQuery with a load() function that works every second. However, when I type user input into a search box, it won't work.

$(document).ready(function() {
function loadData() {
$('body').load('index.php', function() {
  if(window.reloadData != 0)
    window.clearTimeout(window.reloadData);
    window.reloadData = window.setTimeout(loadData, 1500)
}).fadeIn("slow");
}

window.reloadData = 0;
loadData();

});

<form action="search.php" method="get"><input type="text" placeholder="Search for movie"></form>
11
  • You're replacing the full body of the page every 1500ms. Why would you expect the input not to be destroyed and recreated per the HTML you're reloading (e.g., without whatever you typed)? Commented Jul 13, 2017 at 12:47
  • How would I fix it so the input stays? Commented Jul 13, 2017 at 12:49
  • It's going to sound facetious, but: Don't constantly reload the entire page. Reload just a part of it, not including the input. Commented Jul 13, 2017 at 12:51
  • It didn't work. It still clears the input. What should I do? Commented Jul 13, 2017 at 12:54
  • @SteveWoods did you tried to do like i said in my answer ? Commented Jul 13, 2017 at 12:56

1 Answer 1

1

If you really wan't to replace the entire body and save the form state, just remove the form and put it back:

<!--Index.php-->
<!-- Set a identifier for it -->
<form id="searchForm" <!--more attributes...--> ></form>

The Script :

///main.js

(($) => {
   const loadData = () => {
      //"take" the form 
      let $form = $('#searchForm').detach();

      $('body').load('index.php', () => {

          if(window.reloadData != 0)
             window.clearTimeout(window.reloadData);

          window.reloadData = window.setTimeout(loadData, 1500);

          //replace the default form with the saved form
          $('#searchForm').replaceWith($form);

        }).fadeIn("slow");
      }
   $(document).ready(() => {

      window.reloadData = 0;
      loadData();

   });
})(jQuery)

PS: It's recomended to replace just a div where the search results should appear, because you don't want to save the state of every single thing in your page every time :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.