Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I construct query strings for ajax url with jquery or javascript?

I'm currently using ajax and jquery to update search results with a form that has different categories for filtering.

My problem is that I want to be able to pass different variables to the url I'm using for my ajax from checkboxes and other form elements from the current page.

I have the url of "http://example.com/search/results/?cat=tech&min=5&max=30" in my ajax call below and I need that url to update to something like "http://example.com/search/results/?cat=service&min=10&max=30" or even remove a param if it's not even selected like "http://example.com/search/results/?min=5"

<form>
    <input type="radio" name="cat" value="" /> None<br />
    <input type="radio" name="cat" value="service" /> Service<br />
    <input type="radio" name="cat" value="tech" /> Tech<br />
    <input type="radio" name="cat" value="other" /> Other<br />

    <input type="radio" name="min" value="5" /> 5<br />
    <input type="radio" name="min" value="10" /> 10<br />
    <input type="radio" name="min" value="15" /> 15<br />

    <input type="radio" name="max" value="5" /> 5<br />
    <input type="radio" name="max" value="10" /> 10<br />
    <input type="radio" name="max" value="15" /> 15<br />
</form>

<div class="result"></div>

<script type="text/javascript">
$(document).ready(function(){
    $('.filter').live('click focus', function(){

        $.ajax({
            url: http://example.com/search/results/?cat=tech&?min=5&max=30,
            context: document.body,
            success: function(data) {
                $('.result').html(data);
            }   
        });

    });
});
</script>

Some how the url in the ajax call above needs to have the params update in the url. Also, not every param will always be included or needed.

It would be nice if I could use something like PHP's http_build_query function that would automatically know what values of the array to replace or something like that but I'm really stuck as to what to do. I'm not sure if I need to create an array and concatantate

Ideally I would be able to have something like "http://example.com/search/results/cat/tech/min/5/30" if that's at all doable.

like image 217
bigmike7801 Avatar asked Jan 23 '26 03:01

bigmike7801


1 Answers

url: 'http://example.com/search/results/?' + $('form').serialize(),

or

url: 'http://example.com/search/results/?' + $('form').serialize().replace(/&=/, '/'),
like image 81
Andrew Cooper Avatar answered Jan 24 '26 16:01

Andrew Cooper