Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am making an HTTP request with the Google Maps API and I have to pass in parameters (adresses/coordinates):

 $.ajax({
        url : 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' + $("#origin").val() + '&destinations=' + $("#destinations").val() +'&mode=driving&key=AIzaSyASanevdiCI4t1h8LMf5FgWHMD52K3QeB0',
        type: 'GET',
        success : function(data){
        //My code
        }
    });

I was wondering if there was any better cleaner way to do this. I know string concatenation is an option, but I want to know if I have any other options. I just feel like I'm doing this wrong.

share|improve this question
up vote 1 down vote accepted

If we examine the official docs, we can conclude that what you have is standard and clean. Mostly. I'll say a few things though:

  • Instead of the success key, you could choose to use .done(), as in:

    $.ajax({
     // parameters
    })
    .done(function( data ) {
     // success
    });
    
  • To evade string concatenation, you could use a custom string formatting function. JavaScript doesn't have a string format method, so you'll have to add one in, like this one. Then you can code like this:

    var mapsURL = 'https://maps.googleapis.com/maps/api/distancematrix/json?origins={0}&destinations={1}&mode=driving&key=AIzaSyASanevdiCI4t1h8LMf5FgWHMD52K3QeB0';
    

    then

    url: mapsURL.format($("#origin").val(), $("#destinations").val());
    
share|improve this answer

You may want to put your query string into the data property of your XHR request in order to clean up your request as well.

$.ajax({
  url: "https://maps.googleapis.com/maps/api/distancematrix/json",
  type: "GET",
  data: {
    origins: $("#origin").val(),
    destination: $("#destinations").val(),
    mode: "driving",
    key: "AIzaSyASanevdiCI4t1h8LMf5FgWHMD52K3QeB0"
  },
  success: function(data) {
    console.log(data);
  }
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.