Joan Silverstone
Joan Silverstone

Reputation: 385

Sending multiple values to jquery ajax from a function

I want to use the following function for all the ajax calls in my site:

function ajaxcall(my_url, my_div, my_data)
        {
        $(my_div).append('<div style="text-align:center; position:absolute; top:0; left:0; width:100%;"><img src="/images/loading.gif" /></div>');
        $.ajax({ url: my_url,
        data: {data: my_data},
        type: 'get',
        success: function(output) 
            {
            $(my_div).html(output);
            }
        });
        }

It gets whatever URL I want and updates the DIV I want, so far so good. The problem is I also need to send 1 or more values and want to predict the names of those values.

<select class="formtext" name="car_id" id="car_id" onChange="ajaxcall('/ajax/carsetup.php', '#car_setups', $(this).val() )">
<option value="1">1</option>
<option value="2">2</option>
</select>

<div id="car_setups">select car</div>

So what this does is send my select value to the function, it works, however I don't know how to call that value anything, right now its called data but I want to name it whatever I wish, in this case car_id, dynamically, even worse I might want to send more values in that function's third slot. How would I get around this?

Right now print_r($_GET); gives me:

Array ( [data] => 2622 ) 

Upvotes: 1

Views: 1334

Answers (1)

Alnitak
Alnitak

Reputation: 340055

Just do:

data: my_data,

instead of:

data: {data: my_data},

and you can then pass whatever values you look to your AJAX script, e.g.

<select class="formtext" name="car_id" id="car_id"
 onChange="ajaxcall('/ajax/carsetup.php', '#car_setups', {car_id: $(this).val()} )">

That said, you should consider attaching that AJAX call from within your JS itself, rather than inline in the HTML:

 $('#car_id').change(function() {
    ajaxCall('/ajax/carsetup.php', '#car_setups', {car_id: this.value});
 });

Upvotes: 3

Related Questions