Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append selected option to FormData

I am trying to append an <option> selected by the user into an ajax call sent to a php page. (I am not very familiar with ajax or jQuery)

I have built a JSFiddle and hopefully it will be more easily understood than how I can explain it. Here's the gist of it:

HTML

<select name="internType" style="width: 100%; display: block; color: #000;" id="internType">
    <option selected value="default">Please Select</option>
    <option value="accounting">Accounting</option>
    <option value="auditing">Auditing</option>
    <option value="finance">Finance</option>
    <option value="humanresources">Human Resources</option>
</select>

jQuery

formData = new FormData( $(this)[0] );
self.sendData(formData);

sendData : function(formData){
    var self = this;
    var internChoice = $('#internType').val()   // This doesn't seem to hold the value
    formData.append('internChoice', internChoice);  // but rather the entire list
    console.log(formData);
    $.ajax({
        url: self.settings.path + '?i=' + self.settings.app ,
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            console.log(data);
            outcome = jQuery.parseJSON( data );
            self.handleOutcome(outcome);
        },
        cache: false,
        contentType: false,
        processData: false
    });
},

When I do var_dump($_POST); I receive the data that is passed from the inputs, but from the dropdown I receive a string that contains all of the values. E.g:

["internSelect"]=>
string(130) "
    Please Select
    Accounting
    Auditing
    Finance
    Human Resources
"

What am I doing wrong and how can I better trouble shoot what I am doing wrong?

Am I losing the selected value? The page never refreshes so I am not sure how that could be the case.

I am using jQuery 1.10.2 if you need to know that.

like image 730
Mark C. Avatar asked Apr 13 '26 21:04

Mark C.


1 Answers

You can try something like this to get the value: instead of: var internChoice = $('#internType').val()

try: var internChoice = $('#internType option:selected').val()

like image 162
whoopah Avatar answered Apr 16 '26 10:04

whoopah