How to create a single search box for Google and Wikipedia?

Asked

Viewed 176 times

0

I created a search box with two Buttons, one for Google Search and one for Wikipedia Search. The Google button works very well but I can’t do the same for Wikipedia. Follow the code...

<!DOCTYPE html>
<html>
<head>
<title>Search Box Example 1</title>
<meta name="ROBOTS" content="NOINDEX, NOFOLLOW" />
<!-- CSS styles for standard search box -->
<style type="text/css">
	#tfheader{
		background-color:#c3dfef;
	}
	#tfnewsearch{
		float:left;
		padding:20px;
	}
	.tftextinput{
		margin: 0;
		padding: 5px 65px;
		font-family: Arial, Helvetica, sans-serif;
		font-size:14px;
		border:1px solid #0076a3;
		border-top-left-radius: 5px 5px;
		border-bottom-left-radius: 5px 5px;
		border-top-right-radius: 5px 5px;
		border-bottom-right-radius: 5px 5px;
	}
	.tfbutton {
		margin: 0;
		padding: 5px 15px;
		font-family: Arial, Helvetica, sans-serif;
		font-size:14px;
		outline: none;
		cursor: pointer;
		text-align: center;
		text-decoration: none;
		color: #ffffff;
		border: solid 1px #0076a3; border-right:0px;
		background: #0095cd;
		background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5));
		background: -moz-linear-gradient(top,  #00adee,  #0078a5);
		border-top-left-radius: 5px 5px;
		border-bottom-left-radius: 5px 5px;
		border-top-right-radius: 5px 5px;
		border-bottom-right-radius: 5px 5px;
	}
	.tfbutton:hover {
		text-decoration: none;
		background: #007ead;
		background: -webkit-gradient(linear, left top, left bottom, from(#0095cc), to(#00678e));
		background: -moz-linear-gradient(top,  #0095cc,  #00678e);
	}
	/* Fixes submit button height problem in Firefox */
	.tfbutton::-moz-focus-inner {
	  border: 0;
	}
	.tfclear{
		clear:both;
	}
</style>
</head>
<body>
	<!-- HTML for SEARCH BAR -->
	<div id="tfheader">
		<form id="tfnewsearch" method="get" action="https://www.google.com/search" target="_blank" >
		    
		 <input type="text" class="tftextinput" name="q" id="google-search" size="21" maxlength="120"><br><br>
		 <input type="submit" value="Pesquisa Gooogle" class="tfbutton">
		        
		 <button type="submit" class="tfbutton" name="q" id="wikipedia-search" formaction="http://pt.wikipedia.org/wiki/Special:Pesquisar/">Pesquisa Wikipedia</button>
		</form>
	<div class="tfclear"></div>
	</div>
</body>
</html>

  • The name of input research should be search, instead of q, to work with the Wikipedia

2 answers

3

OPTION 01

in his input change the name for search

being like this: name="search"

OPTION 02 (AS PHP)

So you can use php for this. with a simple form! I used bootstrap, but then just add to your code.

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <!-- Meta tags Obrigatórias -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0-12/css/all.css" integrity="sha256-qQHUQX+gGGYfpC7Zdni08sr+h0ymXr0avmIASucY4FM=" crossorigin="anonymous" />

    <title>Formulario!</title>
  </head>
  <body>


    <div class="container">
      <div class="row">
        <div class="col-12 text-center">
          <form action="resultado_caixadebusca.php" target="_blank" method="post">
            <div class="form-group">
              <label>Sua pesquisa abaixo</label>
              <input type="text" name="termo_pesquisa" class="form-control" placeholder="Oque deseja ?">
            </div>
            <button type="submit" name="tipo_pesquisa" value="1" class="btn btn-primary"><i class="fab fa-google"></i> Pesquisa Gooogle</button>
            <button type="submit" name="tipo_pesquisa" value="2" class="btn btn-primary"><i class="fab fa-wikipedia-w"></i> Pesquisa Wikipedia</button>
          </form>
        </div>
      </div>
    </div>

    <!-- JavaScript (Opcional) -->
    <!-- jQuery primeiro, depois Popper.js, depois Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
  </body>
</html>

And in the result_caixadesearch.php Voce adds the:

if ($_POST['tipo_pesquisa'] === '1') {
  $linkpesquisa = "https://www.google.com/search?q=".$_POST['termo_pesquisa']."";
  header('Location: '.$linkpesquisa.'');
}
if ($_POST['tipo_pesquisa'] === '2') {
  $linkpesquisa = "https://pt.wikipedia.org/w/index.php?sort=relevance&search=".$_POST['termo_pesquisa']."";
  header('Location: '.$linkpesquisa.'');
}

So he’ll get the $_POST sent by the form add the URL and redirect.

  • You can also use $_GET metado, just change.

  • Thanks Matheus Vitor, but I can’t get it to work... here’s the thing: "Warning: Cannot Modify header information - headers already sent by (output Started at /home2/wid/corampopulo.pt/resultado_caixadesearch.php:6) in /home2/wid/corampopulo.pt/resultado_caixadesearch.php on line 10"

  • And anything on your server that’s not allowing $_POST, try switching to $_GET anyway.

  • I left it just like this: http://prntscr.com/ospuir

  • Like php I can’t see.. only with the file I can see, you have team view ?

  • Change everything $_POST to $_GET

  • Switch to GET in PHP and HTML

  • I switched to "get" in html and php page and goes to a new page but shows nothing, not even show the search address on google website or wikipedia.

Show 3 more comments

1


You don’t have to use language back-end to that end. With Javascript it is possible to do what you wish.

This can be done by treating the "click" event of the buttons. This way we can create an element, type anchor <a>, temporary and activate it automatically.

Example:

/**
 * Captuar o elemento responsável por 
 * capturar o valor digitado pelo usuário
 */
const inputSearch = document.querySelector('input[name="q"]')

/**
 * Aplica um evento, do tipo "click", nos botões de pesquisa.
 * Para evitar incompatibilidades, você pode substituir o `forEach`
 * por um `for` "simples"
 */
document.querySelectorAll('#google-search, #wikipedia-search')
  .forEach(btn => btn.addEventListener('click', search))

/**
 * Função responsável por identificar o botão pressionado,
 * e enviar o usuário para o site correto.
 *
 * @param {EventTarget} event
 * @return void
 */
function search(event) {
  event.preventDefault()

  const anchor = document.createElement('a')
  anchor.target = "_blank"
  anchor.href = `${event.target.getAttribute('formaction')}${encodeURI(inputSearch.value)}`
  anchor.click()
}
#tfheader {
  background-color: #c3dfef;
}

#tfnewsearch {
  float: left;
  padding: 20px;
}

.tftextinput {
  margin: 0;
  padding: 5px 65px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
  border: 1px solid #0076a3;
  border-top-left-radius: 5px 5px;
  border-bottom-left-radius: 5px 5px;
  border-top-right-radius: 5px 5px;
  border-bottom-right-radius: 5px 5px;
}

.tfbutton {
  margin: 0;
  padding: 5px 15px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
  outline: none;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  color: #ffffff;
  border: solid 1px #0076a3;
  border-right: 0px;
  background: #0095cd;
  background: -webkit-gradient(linear, left top, left bottom, from(#00adee), to(#0078a5));
  background: -moz-linear-gradient(top, #00adee, #0078a5);
  border-top-left-radius: 5px 5px;
  border-bottom-left-radius: 5px 5px;
  border-top-right-radius: 5px 5px;
  border-bottom-right-radius: 5px 5px;
}

.tfbutton:hover {
  text-decoration: none;
  background: #007ead;
  background: -webkit-gradient(linear, left top, left bottom, from(#0095cc), to(#00678e));
  background: -moz-linear-gradient(top, #0095cc, #00678e);
}


/* Fixes submit button height problem in Firefox */

.tfbutton::-moz-focus-inner {
  border: 0;
}

.tfclear {
  clear: both;
}
<!-- HTML for SEARCH BAR -->
<div id="tfheader">
  <form id="tfnewsearch">

    <input type="text" class="tftextinput" name="q" size="21" maxlength="120"><br><br>

    <button type="button" class="tfbutton" id="google-search" formaction="https://www.google.com/search?q=">
      Pesquisa Google
    </button>

    <button type="button" class="tfbutton" id="wikipedia-search" formaction="http://pt.wikipedia.org/wiki/Special:Pesquisar?search=">
      Pesquisa Wikipedia
    </button>
  </form>
  <div class="tfclear"></div>
</div>

<small>Aqui, no StackOverflow, não vai funcionar devido à restrição.</small>

  • Thanks Valdeir Psr you’re fantastic... it really works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.