0

I've created a search form for a script in php. Basicaly this form have some checkboxes and a submit button. Each checkbox is a category, if I check one or more checkboxes the result is filtered by thoose categories.

Here is the html code:

<?php
if ($_POST['do_search'] == 'true') {
$results = 'Do the query and store results in the $results var';
}
?>
    <form method="post" action="search.php" id="search">
     <input type="checkbox" name="categories[]" id="categories[]" value="1">Category 1
     <input type="checkbox" name="categories[]" id="categories[]" value="2">Category 2
     <input type="checkbox" name="categories[]" id="categories[]" value="3">Category 3
     <input type="submit" name="submit">
     <input type="hidden" id="do_search" value="true">
    </form>
    <div id="search_results">
<?php echo $results; ?>
</div>

I'm trying to get the result inline with ajax, for most parts of my script I use JQuery. Anyone can help me to figure out how to pass the $_POST data in realtime through ajax, without reload the page?

p.s. I'm sorry for my poor english, I hope I was clear enough :|

Pennywise83
  • 1,784
  • 5
  • 31
  • 44
  • Some optimization advice for when you achieved your goal: Use a cache for the data you have already received so that you don’t request the same data multiple times. – Gumbo Dec 06 '09 at 23:30
  • The jquery grid may help simplyfy things: http://www.trirand.com/blog/?page_id=5 – brian chandley Dec 06 '09 at 23:46
  • I really appreciate your answers guys, unfortunately I don't know ajax so much... I'd like to load the results from the php script, in the example provided by cletus the results are written inside the JS code... I've edited the main code to show you how my simple script works.I really appreciate your answers guys, unfortunately I don't know ajax so much... I'd like to load the results from the php script, in the example provided by cletus the results are written inside the JS code... I've edited the main code to show you how my simple script works. – Pennywise83 Dec 06 '09 at 23:49
  • check out my answer, it will update your results without reloading the page – AmbrosiaDevelopments Dec 06 '09 at 23:55
  • Ambrosia, thank you so much. Your script is nearly perfect, except for the 'category' value that is passed through $_POST. It should be an array (the form input was id="categories[]"). The value passed through $_POST should be multiple, like 'categories[] = array([0] => 'value1', [1] => 'value2')' – Pennywise83 Dec 07 '09 at 00:07
  • okey dokey, check out the new update of my script. It only creates an array place if it is selected. So if checkboxes 2 and 3 are selected the code will be array: 2,3. You can then use this to convert it back to a PHP array. You will need to play in ur PHP script but I'm sure you can do it. – AmbrosiaDevelopments Dec 07 '09 at 01:21

4 Answers4

0

Inside jQuery, when you do an AJAX request, you call:

jQuery.ajax(options)

In your options object, make sure you set the data member. This member serializes a javascript object into post data.

You can then intercept the form submit, and submit it via AJAX by building up the request from the action, and form fields.

Alternatively you can use the simpler

jQuery.post()

function.

http://docs.jquery.com/Ajax

Tim Ebenezer
  • 2,714
  • 17
  • 23
0

start with this:

$('#search').submit(function(){
    var _this = $(this);
    $.post(_this.attr('action'), _this.serialize(), function(result){
        // callback
    });
    return false;
});
hubbl
  • 266
  • 1
  • 3
  • 9
0

Here is a fairly detailed tutorial on AJAX form submission, which should answer your questions although I don't like the way the query parameters are done. It has:

var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;  
$.ajax({  
  type: "POST",  
  url: "bin/process.php",  
  data: dataString,  
  success: function() {  
    $('#contact_form').html("<div id='message'></div>");  
    $('#message').html("<h2>Contact Form Submitted!</h2>")  
    .append("<p>We will be in touch soon.</p>")  
    .hide()  
    .fadeIn(1500, function() {  
      $('#message').append("<img id='checkmark' src='images/check.png' />");  
    });  
  }  
});  

I would instead do this:

$.ajax({  
  type: "POST",  
  url: "bin/process.php",  
  data: {
    name: name,
    email: email,
    phone: phone
  },
  success: function() {  
    $('#contact_form').html("<div id='message'></div>");  
    $('#message').html("<h2>Contact Form Submitted!</h2>")  
    .append("<p>We will be in touch soon.</p>")  
    .hide()  
    .fadeIn(1500, function() {  
      $('#message').append("<img id='checkmark' src='images/check.png' />");  
    });  
  }  
});  

If you want to automatically construct the form variables rather than doing it automatically, take a look at Serialize form to JSON with jQuery.

Community
  • 1
  • 1
cletus
  • 616,129
  • 168
  • 910
  • 942
0

IDs must be unique, forms only worry about names.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function()
    {
        $('#submitButton').click(function()
        {
            var catArray = new Array();
            var j = 0;
            for(var i = 0; i < 3; i++)
            {
                if(document.myForm.categories[i].checked == 1)
                {
                    catArray[j] = document.myForm.categories[i].value;
                    j++;
                }
            }

            // Just put this here so you can see the output
            // alert('array:'+catArray.toString());

            $.ajax(
            {
                type:    "POST",
                url:     "search.php",
                data:    ({ categories : catArray.toString() }),
                success: function(msg)
                {
                    $('#search_results').html(msg);
                }
            });

            return false;
        });
    });
</script>
</head>
<body>
    <form name="myForm" onsubmit="return false">
        Category 1<input type="checkbox" name="categories" id="category1" value="1" />
        Category 2<input type="checkbox" name="categories" id="category2" value="2" />
        Category 3<input type="checkbox" name="categories" id="category3" value="3" />
        <button id="submitButton">Submit</button>
    </form>
    <div id="search_results"></div>
</body>
</html>
AmbrosiaDevelopments
  • 2,576
  • 21
  • 28