0

I have this form that executes blogSearch() on submit:

<form onsubmit="return blogSearch();">
  <input class="mb0" type="text" id="blogsearchinput" placeholder="Search..." />
</form>

Here is my javascript:

function blogSearch() {
  var test = document.getElementById("blogsearchinput").value
  window.location.href = "../list.php";
  return false;
}

I want to run some more javascript in the function blogSearch() after the page loads, but obviously I can't do that after return false. The page will only load if I return false because I read that that will override the default input submit.

Is there are a way to load a URL from an input submit without needing return false? Or some way I can continue running a function after loading?

Rick
  • 4,030
  • 9
  • 24
  • 35
Ryan
  • 121
  • 3

1 Answers1

0

You can't display search results on the same page using window.location, that takes you to another page. In this case, you probably want to use a XHR request to get the data and then display it on the same page.

I've modified the HTML a little:

<form id="search-form">
  <label>Search blog: <input class="mb0" type="search" id="search-query"></label><input type="submit" value="Search">
</form>
<ul id="search-results"></ul>

Then in list.php you would do something like this:

<?php
// get the q parameter that we will be setting in our XHR request
$query = isset($_GET['q']) ? $_GET['q'] : '';

// I'm assuming you are returning a list of links, so I'm creating an
// array of associative arrays that contain url and link name info.
// In your actual application you would probably be pulling this data from a
// database instead, using the $query variable to filter the results that the DB
// returns. I would recommend using prepared statements to avoid SQL injection
// attacks. My PHP is really rusty right now so I'm not going to attempt to
// filter this array and just return the whole thing.
$results = array(
  array('name' => 'Foo', 'url' => '/foo'),
  array('name' => 'Bar', 'url' => '/bar'),
  array('name' => 'Baz', 'url' => '/baz'),
);

// encode our array as JSON so we can easily decode it in JavaScript
echo (json_encode($results));
?>

Then, here is the JS you would use to make the request and display the results.

// cache elements we will be using in variables
const searchForm = document.getElementById("search-form");
const searchQuery = document.getElementById("search-query");
const searchResults = document.getElementById("search-results");

// this function will do the XHR request and display the results
function blogSearch(event) {

  // stops the default action, in this case submitting the form to the server
  event.preventDefault();

  // get the query and build a url to request
  let query = searchQuery.value;
  let url = `../list.php?q=${query}`;

  let displayError = () => {
    searchResults.innerHTML = '<li>There was an error retrieving your search results</li>';
  };

  let request = new XMLHttpRequest();
  request.open('GET', url, true);

  request.onload = () => {
    if (this.status >= 200 && this.status < 400) {
      // parse the JSON data that was returned
      let data = JSON.parse(this.response);

      // build up a list of li element containing links
      let html = ''
      data.forEach(item => {
        html += `<li><a href="${item.url}">${item.name}</a></li>`;
      });
      // display the search results in our unordered list
      searchResults.innerHTML = html;

    } else {
      displayError();
    }
  };

  request.onerror = () => {
    displayError();
  };

  request.send();
}

// attach the event to the search form
searchForm.addEventListener('submit', blogSearch, false);

A few notes on things I changed:

Further reading

Useless Code
  • 12,123
  • 5
  • 35
  • 40