stefmikhail
stefmikhail

Reputation: 7125

Ajax PHP Created Form Not Submitting

I have a set of three combo boxes (drop downs) that are populated by PHP with values from a database. I've tested these combo boxes by changing the echoed Submit button to type='submit', and loading the php page itself. They work without a hitch in this fashion.

However, when I load the Ajax page, the submit button refuses to trigger the Ajax function. I have tested the page by creating a set of static combo boxes with html, and in this case the Ajax fires without a hitch. Yet using the PHP created combo boxes do not trigger the Ajax.

I'm hoping someone can shed some light on what the problem is concerning my code.

The HTML & jQuery:

<div id="gallery_container">
    <ul class="new_arrivals_gallery"></ul>
    <div class="pagination"></div>
</div>
<script type="text/javascript" src="js/libs/jquery-1.6.1.min.js"></script> 
<script>

$(document).ready(function() {

    function loadData(imgFamily, imgClass, imgGender){
        $.ajax
        ({
            type: "GET",
            url: "filter_test.php",
            data: {imgFamily:imgFamily, imgClass:imgClass, imgGender:imgGender},
            success: function(data) {
                $("#gallery_container").html(data);
            },
        });
    }
    loadData(1);  // For first time page load default results

    //Bind keypress event to Ajax call
    $('.filter').keypress(function(e) {
        if(e.keyCode == 13) {
            var imgFamily = $('#imgFamily').attr('value');
            var imgClass = $('#imgClass').attr('value');
            var imgGender = $('#imgGender').attr('value');
            //Fetch the images
            loadData(imgFamily, imgClass, imgGender);
        }
    });

    //Bind the click event to Ajax call on submit
    $("#submit").click(function(){
        var imgFamily = $('#imgFamily').attr('value');
        var imgClass = $('#imgClass').attr('value');
        var imgGender = $('#imgGender').attr('value');
        //Fetch the images
        loadData(imgFamily, imgClass, imgGender);
    })
});

The PHP (Although I don't believe the problem lies here):

I'm showing only one combo box to save space, and since they're all the same

// Queries for combo boxes
$imgFamily_query = "SELECT DISTINCT imgFamily FROM images WHERE $clause";
$imgClass_query = "SELECT DISTINCT imgClass FROM images WHERE $clause";
$imgGender_query = "SELECT DISTINCT imgGender FROM images WHERE $clause";


// Create the form and combo boxes
echo "<form name='refine' action=''>
        <fieldset><legend>Refine Results</legend>";

    // imgFamily combo box
    if($imgFamily_result = mysql_query($imgFamily_query))  {
      if($imgFamily_success = mysql_num_rows($imgFamily_result) > 0) {
        // Start combo-box
        echo "<label for='imgFamily' id='imgFamily_label'>Choose a family</label>\n
            <select class='filter' id='imgFamily' name='imgFamily'>\n
            <option value='1'></option>\n";
        // For each item in the results...
        while ($imgFamily_row = mysql_fetch_array($imgFamily_result))
          // Add a new option to the combo-box
          echo "<option value='$imgFamily_row[imgFamily]'>$imgFamily_row[imgFamily]</option>\n";
        // End the combo-box
        echo "</select>\n";
      } else { echo "No results found."; }
    } else { echo "Failed to connect to database."; }


    // Add a submit button to the form
    echo "</fieldset>
        <fieldset><input type='button' name='submit' value='submit' id='submit'></fieldset>
    </form>";

Thanks very much for any help.

Upvotes: 2

Views: 655

Answers (2)

Majid Fouladpour
Majid Fouladpour

Reputation: 30242

This is what is happening (basically a re-statement of what @GolezTrol is saying):

  1. Your page finishes loading
  2. loadData(1) is executed, but because it is an asynchronous call execution continues before form elements are fetched.
  3. jquery executed $('.filter').keypress(function(e) but there are no elements with that class yet, so no binding takes place.
  4. $("#submit").click(function(){ has the same fate, we have no element with submit id yet.
  5. response to ajax call arrives and success function adds the form elements to gallery_container, but there no bindings.

What you need to do is to call event binding functions when the respective elements have been added to the dom; so you should move them to after $("#gallery_container").html(data);:

$(document).ready(function() {

    function loadData(imgFamily, imgClass, imgGender){
        $.ajax
        ({
            type: "GET",
            url: "filter_test.php",
            data: {imgFamily:imgFamily, imgClass:imgClass, imgGender:imgGender},
            success: function(data) {
                $("#gallery_container").html(data);
                //Bind keypress event to Ajax call
                $('.filter').keypress(function(e) {
                    if(e.keyCode == 13) {
                        var imgFamily = $('#imgFamily').attr('value');
                        var imgClass = $('#imgClass').attr('value');
                        var imgGender = $('#imgGender').attr('value');
                        //Fetch the images
                        loadData(imgFamily, imgClass, imgGender);
                    }
                });

                //Bind the click event to Ajax call on submit
                $("#submit").click(function(){
                    var imgFamily = $('#imgFamily').attr('value');
                    var imgClass = $('#imgClass').attr('value');
                    var imgGender = $('#imgGender').attr('value');
                    //Fetch the images
                    loadData(imgFamily, imgClass, imgGender);
                });
            }
        });
    }
    loadData(1);  // For first time page load default results
});

Upvotes: 2

GolezTrol
GolezTrol

Reputation: 116100

You insert the form and thereby overwrite the elements to which the submit-event is bound. You should re-execute the code that binds the events after you have inserted the new form.

A cleaner way would be to return a JSON object or XML containing just the modified information, and update your current form instead of inserting a whole new one, but that will be more work.

function loadData(imgFamily, imgClass, imgGender){
    $.ajax
    ({
        type: "GET",
        url: "filter_test.php",
        data: {imgFamily:imgFamily, imgClass:imgClass, imgGender:imgGender},
        success: function(data) {
            $("#gallery_container").html(data);

            bindEvents(); // <---- Call it here
        },
    });
}

// Separate function
function bindEvents()
{
    //Bind keypress event to Ajax call
    $('.filter').keypress(function(e) {
        if(e.keyCode == 13) {
            var imgFamily = $('#imgFamily').attr('value');
            var imgClass = $('#imgClass').attr('value');
            var imgGender = $('#imgGender').attr('value');
            //Fetch the images
            loadData(imgFamily, imgClass, imgGender);
        }
    });

    //Bind the click event to Ajax call on submit
    $("#submit").click(function(){
        var imgFamily = $('#imgFamily').attr('value');
        var imgClass = $('#imgClass').attr('value');
        var imgGender = $('#imgGender').attr('value');
        //Fetch the images
        loadData(imgFamily, imgClass, imgGender);
    })
}

$(document).ready(function() {

    loadData(1);  // For first time page load default results

    bindEvents(); // <---- And here (where your code originally was).
});

Upvotes: 1

Related Questions