Gugis
Gugis

Reputation: 21

Submit Ajax form on select change

I need to submit form on selection change. There's form I have.

<form id="form" name="form" method="post" action="modules/submit.php">
<select name='category' id='category' size='12' onChange='this.form.submit();'>
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<select name='subcategory' id='subcategory' size='12'>
</select>
</form>

JS:

$(document).ready(function(){
    $('#form').submit(function() {
        select();
        e.preventDefault();
    });

});


function select()
{
    error(0);

    $.ajax({
        type: "POST",
        url: "modules/submit.php",
        data: $('#form').serialize(),
        dataType: "json",
        success: function(msg){
            if(parseInt(msg.status)==1)
            {
                window.location=msg.txt;
            }
            else if(parseInt(msg.status)==0)
            {
                result(1,msg.txt);
            }
        }
    });

}

function result(act,txt)
{
    if(txt) $('#subcategory').html(txt);
}

submit.php:

if(isset($_POST['category'])){
die(msg(0,"<option value='0'>Trololo</option>"));
}
function msg($status,$txt)
{
    return '{"status":'.$status.',"txt":"'.$txt.'"}';
}

When i change selection form is being submitted and redirects to submit.php file. I need to get results for subcategory selection.

Upvotes: 2

Views: 14488

Answers (2)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175098

Try this:

$('#category').change(function() {

    $('#form').submit();

});

Also, your code will fail to prevent the default action for the form submission, because you didn't pass the event argument to the function.

$('#form').submit(function(e) { //Note the e!!
    e.preventDefault();
    select();
});

Upvotes: 4

karim79
karim79

Reputation: 342795

Your form will always submit because you're not passing e as argument to the submit handler:

$('#form').submit(function(e) {
    e.preventDefault();
    select();
});

Also, I would change the msg function to this:

function msg($status,$txt)
{
    return array('status' => $status, 'text' => $text);
}

and the call:

if(isset($_POST['category'])){
    die(json_encode(msg(0,"<option value='0'>Trololo</option>")));
}

Upvotes: 0

Related Questions