How do you submit more than one variable via Ajax?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

How do you submit more than one variable via Ajax?

Post by simonmlewis »

Code: Select all

<script>
function precheck(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        };
        xmlhttp.open("GET","ajax-search.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>

<?php echo "<div class='home-search'>
<div class='home-search-inner'>
<form method='GET' action='/index.php'>
<input type='hidden' name='page' value='search'>
<div class='home-search-icon'><i class='fa fa-search' aria-hidden='true'></i></div>
<div class='home-search-input'> <input type='text' name='search' placeholder='Search the site'";
if (isset($search)) { echo " value='";
?><?= htmlspecialchars($search); ?><?php
echo "'";}
echo " onChange=\"precheck(this.value)\"></div>
<div class='home-search-cat'><select name='category'>
<option value='all'>All Categories</option>";

  $query = "SELECT DISTINCT catname FROM products WHERE pause <> 'on' ORDER BY catname";
  $result = $pdo->query($query);
  while ($row = $result->fetch(PDO::FETCH_OBJ)) 
      {
      
      echo "<option value='$row->catname'";
      if (isset($categorysearch)) 
      {
      if ($row->catname == $categorysearch) { echo " selected='selected'";}
      }
      echo ">$row->catname</option>";
      }

echo "</select></div>
<div class='home-search-submit'><input type='submit' value='search'></div>
</form>
<div style='clear: both'></div>
</div></div>
<div id='txtHint'><b>Person info will be listed here...</b></div>";
Then it gets posted to the PHP file to run the query.

But how do I make it pass the dropdown menu <select> option in the Ajax query as well?
Ideally, if they typed in something, and it came up with the answers, and then they switched the dropdown <Select> to a different category, the options would change.

Trouble is, there is one or two main keywords here that means hundreds of products can be found.
Tho I can limit it I suppose.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How do you submit more than one variable via Ajax?

Post by Celauran »

The first thing you'll need to do, clearly, is make sure ajax-search.php accepts more parameters than just q. Once that's done, you can attach a listener to your select list as well and pass both select and search values to your AJAX call. Probably easier, and definitely cleaner, to do using jQuery.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: How do you submit more than one variable via Ajax?

Post by simonmlewis »

How would u do it using jQuery tho? I'm very much a notice with Ajax. We stopped it for a while, but with this new site we want to try it again.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: How do you submit more than one variable via Ajax?

Post by simonmlewis »

Plan B would be to have two scripts, that point to the same *.php results code.

The results code could have a session for the two entries that are passed over. The Text and Select onChange scripts could run separate queries, and just update the PHP file.

Or is that bad practice?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How do you submit more than one variable via Ajax?

Post by Celauran »

Could be something like this

Code: Select all

<?php

$query = "SELECT DISTINCT catname FROM products WHERE pause <> 'on' ORDER BY catname";
$result = $pdo->query($query);
$categories = $result->fetchAll(PDO::FETCH_OBJ);

?>

<div class="home-search">
    <div class="home-search-inner">
        <form method="GET" action="/index.php">
            <input type="hidden" name="page" value="search">
            <div class="home-search-icon"><i class="fa fa-search" aria-hidden="true"></i></div>
            <div class="home-search-input">
                <input type="text" name="search" placeholder="Search the site" value="<?= isset($search) ? htmlspecialchars($search) : ''; ?>">
            </div>
            <div class="home-search-cat">
                <select name="category">
                    <option value="all">All Categories</option>
                    <?php foreach ($categories as $category): ?>
                        <?php $selected = (isset($categorysearch) && $categorysearch == $category->catname) ? 'selected="selected"' : ''; ?>
                        <option value="<?= $category->catname; ?>" <?= $selected; ?>><?= $category->catname; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="home-search-submit">
                <input type="submit" value="search">
            </div>
        </form>
        <div style="clear: both"></div>
    </div>
</div>
<div id="txtHint"><b>Person info will be listed here...</b></div>";

<script>
// This really belongs in a separate JS file, not embedded alongside PHP or HTML
$(document).ready(function() {
    $('.home-search-input input').on('keyup', function(event) {
        var search_string = $(this).val();

        // Don't fire on very short strings
        if (search_string.length > 2) {
            var category = $('.home-search-cat select').val();
            $.ajax({
                url: '/ajax-search.php?q=' + search_string + '&category=' + category,
                method: 'GET'
            }).done(function(response) {
                // Do something with the response here
            });
        }
    });
});
</script>
Note I've tried to separate concerns a little bit. Also note I haven't tested this, so it's unlikely to be perfect. It should, however, give you the general idea and a good jumping off point.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: How do you submit more than one variable via Ajax?

Post by simonmlewis »

search_string... should all entries that say that, be "search", as that is the name of the search field? Like it is for "category"?
I ask that, as so far it's not producing anything.
Also, what is the "Do something with the response here" for?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How do you submit more than one variable via Ajax?

Post by Celauran »

simonmlewis wrote:Also, what is the "Do something with the response here" for?
Your AJAX call will return something. Right now I believe it's a string, so you can just update the DOM.

Code: Select all

$(document).ready(function() {
    $('.home-search-input input').on('keyup', function(event) {
        var search_string = $(this).val();

        // Don't fire on very short strings
        if (search_string.length > 2) {
            var category = $('.home-search-cat select').val();
            $.ajax({
                url: '/ajax-search.php?q=' + search_string + '&category=' + category,
                method: 'GET'
            }).done(function(response) {
                $('#txtHint').html(response);
            });
        }
    });
});
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How do you submit more than one variable via Ajax?

Post by Celauran »

simonmlewis wrote:search_string... should all entries that say that, be "search", as that is the name of the search field? Like it is for "category"?
Not quite sure what you're asking here. search_string is just a local variable that holds the contents of the search field. Defined here:

Code: Select all

    $('.home-search-input input').on('keyup', function(event) {
        var search_string = $(this).val();
You can call it whatever you like.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: How do you submit more than one variable via Ajax?

Post by simonmlewis »

search_String. gotcha.
"Your AJAX call will return something. Right now I believe it's a string, so you can just update the DOM.".
Sorry...?? This is what I mean by "novice". I did have some AJAX queries that worked, but I think they were old. It seems that I need to send the results to "txtHint", and that is echoed in that DIV. But I don't know how.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How do you submit more than one variable via Ajax?

Post by Celauran »

I edited my post above with an example. Let me know if that still doesn't clear it up.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: How do you submit more than one variable via Ajax?

Post by simonmlewis »

That is passing something over, but on the "results" php file, I am getting "undefined all" showing where "results $search $category" is.

Code: Select all

<?php
session_start();
$todaydate = date('Y-m-d');
$newdate = strtotime("$todaydate");

if(isset($_GET['search']))
{
    $search = $_GET['search'];
    $search = str_replace("-", " ", $search);
    $_SESSION['search']=$search;
} elseif (isset($_SESSION['search'])) {
    $search=$_SESSION['search'];
}

if(isset($_GET['category']))
{
    $category = $_GET['category'];
    $category = str_replace("-", " ", $category);
    $_SESSION['category']=$category;
} elseif (isset($_SESSION['category'])) {
    $category=$_SESSION['category'];
}

include "dbconn.php";

echo "<div class='ajax_toggle'><div class='ajax_toggleresults'>results $search $category</div><div class='ajax_togglebtn'><a href=\"javascript:toggleDiv('srcHint');\">Close</a></div><div style='clear: both' /></div></div>";....................
Looking at the code, I think I can see why.

Code: Select all

url: '/ajax-search.php?q=' + search_string + '&category=' + category,
This is compiling it into the $q$ variable.
So how in my PHP results page do I split this up to query against 'search' and 'category'?
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: How do you submit more than one variable via Ajax?

Post by simonmlewis »

Ok my bad, I see it. Just changed q to search.
But it's still not changing the value of $category in the results PHP file. Not sure why, as it is sending new data to it.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How do you submit more than one variable via Ajax?

Post by Celauran »

I used q= based on your code above

Code: Select all

xmlhttp.open("GET","ajax-search.php?q="+str,true);
If your PHP is expecting $_GET['search'], you can easily change q to search.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: How do you submit more than one variable via Ajax?

Post by simonmlewis »

Yep I did that. No worries there. But it's not passing over category. The session it's stored for that isn't being changed.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How do you submit more than one variable via Ajax?

Post by Celauran »

simonmlewis wrote:But it's still not changing the value of $category in the results PHP file. Not sure why, as it is sending new data to it.
Can you elaborate? Have you checked what's being sent? What is being displayed as a result? Also note I only attached a listener to the search box, not to the select list, so the AJAX currently only fires on keyup in search box.
Post Reply