0

PHP dev needing JS help! I'm pretty new to JS and can't figure this out.

I have a small jQuery plugin gSearch http://gsearch.scottreeddesign.com/index.html That performs a Google Search within your page. It isnt built with POST/GET capabilities, you need to define the 'search term' within the functions parameters. I am trying to modify it.

I have 2 pages:

search.html contains:

<form action="results.html">
  <input type="text" name="q" id="term">
  <input type="button" id="search_button" onclick="this.form.submit();">
</form>

results.html contains:

$("#search-results").gSearch({
    search_text : 'brian griffin',
    count : 4,
    site : 'wikipedia.org',
    pagination : false  
});

and in the body:

<div id="search-results"></div>

Now I need to get the search term from the form and pass it as a variable to the .gSearch function. How would I go about this? I see posts on how to get/return url parameter but I can't seem to find any explaining how to turn it into a variable and pass it to another function? I can do this with my eyes closed with pure PHP but I'm new to JS!

Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
Charles Butler
  • 573
  • 3
  • 15

3 Answers3

0
$('form').on('submit', function(e){
    e.preventDefault(); //stop default form submit
    $('#search-results').gSearch({
        search_text: $('#term').val(), //the term to search
        count: 4, //how many
        site: 'wikipedia.org', //a site to match the search against
        pagination: false //whether or not to use pagination
    }); 
});

We capture the form submit and stop it with preventDefault(). After, we apply gSearch to an element with the id of search-results (which the returned results will be appended to). We define some parameters within our object request. This should be sufficient.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
0

Try this

$('#search_button').on('click', function(e) {
    e.preventDefault();

    var $search = $('#term').val();

    // Assign it to the gSearch
    $("#search-results").gSearch({
        search_text: $search,
        count: 4,
        site: 'wikipedia.org',
        pagination: false
    });


});​
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • I didn't get a chance to test others, this was the first one and it worked perfect. I do get a better understanding on how the variables work by all the posts. Thank you! – Charles Butler Dec 20 '12 at 02:53
0

There's no built-in way to read the key/value pairs in the querystring in JavaScript. To get a value from the querystring, parse location.search:

var searchTerms = "";
if (/\bq=([^&]+)/.test(location.search)) {
    searchTerms = decodeURIComponent(RegExp.$1);
}
$("#search-results").gSearch({
    search_text : searchTerms,
    count : 4,
    site : 'wikipedia.org',
    pagination : false  
});

You can't read POST values at all from JavaScript. Those are available server-side only.

Community
  • 1
  • 1
gilly3
  • 87,962
  • 25
  • 144
  • 176