views:

48

answers:

6

Hey there, new to AJAX, JS.. Im trying to add to a Javascript/Ajax search script that I've put together. Previously, it had a single search field, called search_word, I added one called search_date.

$(".search_button").click(function() {
    var search_word = $("#search_box").val();
    var search_date = $("#datepicker").val();
    var dataString = 'search_word='+ search_word;

    if(search_word=='')
    {
    }
    else
    {
        $.ajax({
        type: "GET",
        url: "searchdata.php",
        data: dataString,

In the Ajax, it appears to pass data of dataString, to my processing script. How do I add search date to the dataString so that I can use that var in my searchdata.php?

In searchdata, I can do this $search_word=$_GET['search_word']; and use that var, but so far every time i attempt to alter the dataString, it breaks all the other functionality.

Thanks!

+1  A: 

You need to modify dataString like so:

var dataString = 'search_word='+ search_word + '&search_date=' + search_date;

I also suggest you invert your if condition, to if(search_word) { ... }, put the AJAX in there, and skip the else.

If this doesn't help you, try alerting out the value of dataString after that concatenation, to see what is really happening. perhaps the value of search_date is not what you think it is?

David Hedlund
+2  A: 

Either

var dataString = 'search_word='+search_word+'&search_date='+search_date;

Or you can get rid of that line completely and just do

$.ajax({
        type: "GET",
        url: "searchdata.php",
        data: {search_word: search_word, search_date: search_date}
      });
caligoanimus
The second option i tried but it wouldnt post. The first option worked like a charm, thanks!
Kelso
the second option should say `data: ` in front of the data object...
David Hedlund
dclowd9901
+1  A: 
var str = 'search_word='+ search_word + '&search_date'+search_date;
dataString = encodeURI(str);

$.ajax({
    type: "GET",
    url: "searchdata.php",
    data: dataString});

To avoid unexpected requests to the server, you should call encodeURI on any user-entered parameters that will be passed as part of a URI.

N 1.1
you'd have to use `encodeURI` or, preferably, `encodeURIComponent` on the two parameters individually, and not on the final concatenated string. the current solution will replace the ` that wont work at all)
David Hedlund
@David: thanks. updated.
N 1.1
A: 

You can also directly add it to the url:

 $.ajax({
        type: "GET",
        url: "searchdata.php?search_word=" + search_word;
 });
streetpc
A: 

In your $.ajax call you can use an object for the data parameter.

$.ajax({
        type: "GET",
        url: "searchdata.php",
        data: {search_word: search_word, search_date: search_date}
});
Ryan
A: 

Make the data a json object with your parameters:

data {
  prop1: val1
  , prop2: val2
}
npup