4

I have a Rest service on /users/{userId}/orders/{orderId} (please note the path parameters) and I want to call it from JQuery.

I could do it simply concatenating the ids like so:

$.get(
    'users/' + 1234 + '/orders/' + 9876,
    function (data) {
        //do something with the response
    }
);

But this doesn't seem like a very correct way of doing it (although it does the job).

Is there a better way of passing these path parameters on the URL of a JQuery AJAX call?

* just to clarify, my concern is more with the concatenation of the string. I wonder if there's a better way to construct the url without concatenating strings. Perhaps string formatting would be better?

4
  • I think you should change your Rest service using path variables Commented Mar 17, 2017 at 10:51
  • Can you please elaborate on what you mean by "change your Rest service using path variables"? Commented Mar 20, 2017 at 10:01
  • I mean you should use arguments in url like yourservice?userid=xxx&orders=yyy Commented Mar 20, 2017 at 10:20
  • 2
    Yeah but that wouldn't be very Restful-ly and sometimes you need to call an existing service and don't have control over the use of path or query params. Commented Mar 20, 2017 at 15:46

2 Answers 2

7

I think Template literals is the neatest way to proceed here:

$.get(
    `users/${userId}/orders/${orderId}`,
    function (data) {
        //do something with the response
    }
);
Sign up to request clarification or add additional context in comments.

Comments

0

You can make a function to make this request :

function makeOrderRequest(userId, orderId, sucessCallback) {
    $.get('users/' + userId + '/orders/' + orderId, successCallback);
}

And then call it when you need :

makeOrderRequest(1234, 8796, function(data){
     //do stuff
});

2 Comments

Thanks, my concern is more to do with the string concatenation. You are still concatenating strings in the url in your example. I wonder if there's a better way to do it which doesn't involve that.
Ok. I think concatenation is good here, but you can use an object like {order:1234,user:8765} then generate the URL with a loop to avoid manual concatenation.

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.