John
John

Reputation: 426

Using AJAX for multiple selects and no submit button

Alright, so right now I have a page that has two select buttons. Once both of them are set, I want the page to automatically update. Then, whenever a new option is selected each time, the page will keep automatically updating. Here's my HTML:

<form action="" method="POST" id = "multiple">
    <select name="op" id="op"> 
        <?php
            require('C:\www\php\connect.php'); 
            require('C:\www\php\stuff1.php'); // populates first select bar
        ?>   
    </select>

    <br>

    <select name="op2" id="op2"> 
        <?
            php require('C:\www\php\stuff2.php'); //populates second select bar
        ?> 
    </select>
</form>

Here was my jQuery BEFORE. Right now with this, it will automatically submit the page once two items are selected:

$(document).ready(function () {
    $('#op,#op2').on('change', function () {
        if ($('#op').val() && $('#op2').val()) {
            $("#multiple").submit();
        }
    });
});

Here's my (not working) AJAX response that I want to try to implement to do what I mentioned at the start:

$(document).ready(function (e) {
    $('#op,#op2').on('change', function () {
        $("#multiple").submit();
        var url = "C:\www\php\stuff2.php"; 
        alert("show me signs of life"); // show response
        $.ajax({
               type: "POST",
               url: url,
               data: $("#multiple").serialize(),
               success: function(data)
               {
                   alert(data); // show me something
               }
             });

        e.preventDefault();
    }
});

Where exactly am I going wrong here? I'm pretty sure that my URL situation is a little bit messed up seeing as how I use multiple php files to populate the boxes, but I feel like that doesn't matter. If it helps, the file where the magic happens is in stuff2.php, so that was the only one I've included.

Upvotes: 0

Views: 96

Answers (1)

Alo
Alo

Reputation: 3844

The code:

$("#multiple").submit()

will perform an HTTP POST request to the current URL. You don't need it if you are making AJAX calls.

Simply having:

$.ajax({
     type: "POST",
     url: url,
     data: $("#multiple").serialize(),
     success: function(data)
     {
          alert(data); // show me something
     }
});

should work just fine.

Upvotes: 2

Related Questions