How to build query strings for ajax url with jquery or javascript?

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

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

I have the url " http://example.com/search/results/?cat=tech&min=5&max=30 " in my ajax call below and I need this url to upgrade to " http://example.com / search / results /? cat = service & min = 10 & max = 30 "or even remove the parameter if it is not even selected as" 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>

, URL- ajax URL-. , .

, - PHP http_build_query, , - , , . , concatantate

- http://example.com/search/results/cat/tech/min/5/30 ", .

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

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

, , . , :

  • Undo the default action that should refresh the response page
  • Send via ajax and process the response

Like this:

<form id="MyFilterForm" action="/myBaseUrl" method="POST">
    ...
    <input type="submit" value="Filter"/>
</form>

<script type="text/javascript">
$(document).ready(function(){
    $('#MyFilterForm').submit(function(event){
        // cancel the default action
        event.preventDefault();

        var theForm = $(this);
        $.post(theForm.attr('action'), theForm.serialize(), function (data){
            $('.result').html(data);
        });
    });
});
</script>
0
source

You can check which radio inputs were selected and build the URL accordingly, for example:

<input id="radCat" type="radio" name="cat" value="service" /> Service<br />

string url = "http://example.com/search/results/?";

if($("#radCat").attr("checked").val() == "checked") {
    url = url + "cat=" + $("#radCat").attr("value").val();
}
0
source

All Articles