?
Solved

Ajax form submitting onchange of any form field

Posted on 2011-02-23
8
Medium Priority
?
504 Views
Last Modified: 2012-05-11
I have a form with multiple fields that when submitted, the results are retrieved via ajax on the same page. This works perfectly. However, to retrieve the results you have to press a button, submitting the form.

I would like it so that if any of the fields are changed, the results are updated without having to press the button, kind of like a search filter. There are currently several text fields, a couple of dropdowns and there will be a few checkboxes.

The form is currently processed using the attached code.

Thanks


$(function() {

  $("form#search").submit(function(){
	  
	var range = $("#range").val();
	var subcat = $("#subcat").val();
	var colour = $("#colour").val();
	var size1 = $("#size").val();
	
	var dataString = 'range='+ range + '&subcat=' + subcat + '&colour=' + colour + '&size=' + size1;
		
     $.ajax({
		type: "POST",
		url: "/search_results.php",
		data: dataString,
		success: function(data){
			$("#results").empty().html('<img src="/images/ajax-loader.gif" class="loader" />');
			setTimeout(function() {
				$("#results").html(data);
			}, 1500);
        }
     });
     return false;
  });

});

Open in new window

0
Comment
Question by:djfenom
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
8 Comments
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 34960859
Probably could do something like this:
$('input, select').change(function()
{
    var range = $("#range").val();
	var subcat = $("#subcat").val();
	var colour = $("#colour").val();
	var size1 = $("#size").val();
	
	var dataString = 'range='+ range + '&subcat=' + subcat + '&colour=' + colour + '&size=' + size1;
		
     $.ajax({
		type: "POST",
		url: "/search_results.php",
		data: dataString,
		success: function(data){
			$("#results").empty().html('<img src="/images/ajax-loader.gif" class="loader" />');
			setTimeout(function() {
				$("#results").html(data);
			}, 1500);
        }
     });
});

Open in new window

0
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 34960931
Sorry, in case it's not obvious, you'd want to wrap the above script inside of a $(document).ready() function like this:
 
$(document).ready(function ()
{
    $('input, select').change(function ()
    {
        var range = $("#range").val();
        var subcat = $("#subcat").val();
        var colour = $("#colour").val();
        var size1 = $("#size").val();

        var dataString = 'range=' + range + '&subcat=' + subcat + '&colour=' + colour + '&size=' + size1;

        $.ajax({
            type: "POST",
            url: "/search_results.php",
            data: dataString,
            success: function (data)
            {
                $("#results").empty().html('<img src="/images/ajax-loader.gif" class="loader" />');
                setTimeout(function ()
                {
                    $("#results").html(data);
                }, 1500);
            }
        });
    });            
});

Open in new window

0
 

Author Comment

by:djfenom
ID: 34961047
Ok, that's working, but I have a couple of autosuggest fields which when submitted by the button passed whatever was selected from the autosuggest dropdown. Now that no button is pressed if you start typing say Gr and then select Green, the value that is passed is just the Gr bit which is giving false results?

Code for this is attached.
<script>
function lookup(inputString) {
		if(inputString.length == 0) {
			// Hide the suggestion box.
			$('#suggestions').hide();
		} else {
			$.post("/list_colours.php", {queryString: ""+inputString+""}, function(data){
				if(data.length >0) {
					$('#suggestions').show();
					$('#autoSuggestionsList').html(data);
				}
			});
		}
	} // lookup
	
	function fill(thisValue) {
		$('#colour').val(thisValue);
		setTimeout("$('#suggestions').hide();", 200);
	}
</script>

<input type="text" id="colour" name="colour" onblur="fill();" onkeyup="lookup(this.value);" value="Type a colour..." title="Type a colour..." size="30" class="loseit1" autocomplete="off" />
            <div class="suggestionsBox" id="suggestions" style="display:none;"> <img src="/images/upArrow.png" class="uparrow" alt="upArrow" />
              <div class="suggestionList" id="autoSuggestionsList"> &nbsp; </div>

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 34961507
Hmm, my thinking is that when the 'change' event is fired, before you do that ajax request which fills $('#results'), you need to do another ajax request to validate if $('#colour') holds a correct colour value.  Pretty much like a pre-query.  Just something simple to see if the colour exists in your color list on the server, and then return a true/false back to the client.

Probably have to tweak it a bit, but something like this:
 
$(document).ready(function ()
{
    $('input, select').change(function ()
    {
        var colour = $("#colour").val();
        var validcolour = false;

        $.ajax({
            type: "GET",
            url: '/list_colours.php',
            data: 'colourcheck=' + colour,
            success: function (data)
            {
                //server should return simple boolean value here
                validcolour = data;
            }
        });

        if (validcolour)
        {
            var range = $("#range").val();
            var subcat = $("#subcat").val();
            var size1 = $("#size").val();

            var dataString = 'range=' + range + '&subcat=' + subcat + '&colour=' + colour + '&size=' + size1;

            $.ajax({
                type: "POST",
                url: "/search_results.php",
                data: dataString,
                success: function (data)
                {
                    $("#results").empty().html('<img src="/images/ajax-loader.gif" class="loader" />');
                    setTimeout(function ()
                    {
                        $("#results").html(data);
                    }, 1500);
                }
            });
        }                
    });
});

Open in new window

0
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 34961592
Also, may have to separate the functionality out a bit to get the query to run after your auto suggest code runs.
See below:
 
$(document).ready(function ()
{
    $('input, select').change(function ()
    {
        var colour = $("#colour").val();
        var validcolour = false;

        $.ajax({
            type: "GET",
            url: '/list_colours.php',
            data: 'colourcheck=' + colour,
            success: function (data)
            {
                //server should return simple boolean value here
                validcolour = data;
            }
        });

        if (validcolour)
        {
            GetResults(colour);
        }
    });
});

function fill(thisValue)
{
    $('#colour').val(thisValue);
    setTimeout("$('#suggestions').hide();", 200);
    GetResults(thisValue);
}

function GetResults(colour)
{
    var range = $("#range").val();
    var subcat = $("#subcat").val();
    var size1 = $("#size").val();

    var dataString = 'range=' + range + '&subcat=' + subcat + '&colour=' + colour + '&size=' + size1;

    $.ajax({
        type: "POST",
        url: "/search_results.php",
        data: dataString,
        success: function (data)
        {
            $("#results").empty().html('<img src="/images/ajax-loader.gif" class="loader" />');
            setTimeout(function ()
            {
                $("#results").html(data);
            }, 1500);
        }
    });
}

Open in new window

0
 

Author Comment

by:djfenom
ID: 34961761
Thanks P1ST0LPETE, I have a couple of issues though:

Firstly, there is 2 autocomplete boxes and secondly, the user won't necessarily use the autosuggest in the way it is meant to be used. For example, they may type in a colour and not select from the list, like you can in Google, if this is the case then the colour will be passed as undefined and not display the results.
0
 
LVL 10

Accepted Solution

by:
P1ST0LPETE earned 2000 total points
ID: 34963116
Ok, scratch the idea of the pre-query.

Check this idea.  Give your ajax request like a 1 second delay before it fires off.  This should give the fill() function the time it needs to populate the auto complete box BEFORE the GetResults() function accesses the value of the auto complete box .  However, you only want to apply this delay when the user is currently working in one of the auto complete fields.  See below:
 
$(document).ready(function ()
{
    $('select, input').change(function ()
    {
        if (this.id == 'Colour' || this.id == 'YourOtherAutoCompleteId')
        {
            setTimeout("GetResults()", 1000);
        }
        else GetResults();
    });
});

function GetResults()
{
    var range = $("#range").val();
    var subcat = $("#subcat").val();
    var colour = $("#colour").val();
    var size1 = $("#size").val();

    var dataString = 'range=' + range + '&subcat=' + subcat + '&colour=' + colour + '&size=' + size1;

    $.ajax({
        type: "POST",
        url: "/search_results.php",
        data: dataString,
        success: function (data)
        {
            $("#results").empty().html('<img src="/images/ajax-loader.gif" class="loader" />');
            setTimeout(function ()
            {
                $("#results").html(data);
            }, 1500);
        }
    });
}

Open in new window

You may want to test a bit to see if you can shorten the delay.  I was able to manually test this theory with just a 2 second delay, and I would image code can operate much faster than my fingers can type :-).  1000 milliseconds is just playing it safe.

0
 

Author Comment

by:djfenom
ID: 34995425
That works great, many thanks!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question