OtoNoOto OtoNoOto - 5 months ago 25
jQuery Question

jQuery AJAX URL Ampersand (&) Formatting

Using the following script I am capturing date value from jQuery datepicker and passing that on to a jQuery AJAX call. Everything is working, but running into an issue with ampersands in the AJAX URL.

This is my code:

<script type="text/javascript">
$(document).ready(function(){

$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function (date) {

//capture date values from datepicker
var date = date;
var year = date.substr(0,4);
var month = date.substr(5,2);
var day = date.substr(8,2);
var url = "http://www.example.com?view=week" + "&year=" + year + "&month=" + month + "&date=" + day;


//ajax events load
$.ajax({url: url ,success:function(result){
$("#ajaxEvents").html(result);
}});

//close datepicker
$('#datepicker').toggle();
$(this).toggleClass('close');

return false;
}

})

});
</script>


When I inspect the AJAX request using fiddler you can see the URL format is as follows:

http://www.example.com?view=week&amp;year=2014&amp;month=01&amp;date=23


Note that all the '&' characters were converted in the URL. In order for the query to work correctly I need the format to be:

http://www.example.com?view=week&year=2014&month=01&date=23


Any ideas how I can prevent the format from changing in the AJAX request?

Thanks in advance!

Answer

Add a data element to your jQuery ajax function

  data: { year: "2014", month: "Jan", date: "15" }

jquery will add it to the URL for you.

 //ajax events load
 $.ajax({url: url, data: { year: '"'+year+'"', month: '"'+month+'"', date: '"'+day+'"'} ,success:function(result){
 $("#ajaxEvents").html(result);
 }});
Comments