1

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 ) 

1 Answer 1

3

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});
 });
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, i cant seem to get that last part working, why is it important to not keep it inline?
Also, ajaxCall('/ajax/carsetup.php', '#car_setups', {car_id: this.value, variable: 1, variableother: 2}); doesnt seem to work
re: 1st query - inline handlers is so 1990s... not sure about second query - the syntax looks fine. what does your debugger say?
i found out why, i copy pasted your code and you capitalized the function name, cheers mate, everything working perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.