Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add select onchange with AJAX

I'm a newbie to Javascript so I couldn't find an answer to my problem. I want to add an extra select when a previous select is changed. I know my code should look something likes this but it isn't working:

$(function(){
$('#artist').change(function(){
    $.ajax({
        url: "artist_field.php",
        dataType:"html",
        type: "post",
        success: function(data){
           $('#artist').append(data);
        }
    });
});
});

HTML

<td id="artist">
<select name="artist_1" id="artist">
<option value=""></option>
</select>
</td>

My problem is that I don't know how to get the values in artist_field.php that I'm trying to send (because I'm trying to exclude the previous selected option in the new select). I hope someone can help me! Thanks in advance.

like image 436
Steven Avatar asked Nov 05 '25 21:11

Steven


2 Answers

$(document).ready(function() {
    $('#select_2').hide();
    $('#artist').change(function(){
        $('#select_2').show();
    });
});

HTML

<td id="artist">
    <select name="artist_1" id="artist">
        <option value=""></option>
    </select>
</td>
<td>
    <select name="select_2" id="select_2">
        <option value=""></option>
    </select>
</td>

It will only show the second select if you chose something on the first one

like image 90
gbestard Avatar answered Nov 07 '25 11:11

gbestard


Update: I just noticed that you have the ID artist in the code twice. You might change the TD to <td id="artist_td"> or something for my example to work

To send the currently selected option back to the server in the post, you can do something like:

$('#artist').change(function(){
    $.ajax({
        url: "artist_field.php",
        data: { "value": $("#artist").val() },
        dataType:"html",
        type: "post",
        success: function(data){
           $('#artist').append(data);
        }
    });
});

Then in the PHP document, you can get the value with $_POST["value"];, and use that value to limit the return options.

update

If you are going to fire the change event off multiple times, it's going to append the new data every time. If this is not the behavior that you want, add a div or something to put the new data into like:

<td id="artist_td">
<select name="artist_1" id="artist">
<option value=""></option>
</select>
<div id="newdata"></div>
</td>

Then edit the success function

success: function(data){
   $('#newdata').empty().append(data);
}
like image 27
jwatts1980 Avatar answered Nov 07 '25 11:11

jwatts1980



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!