volume one
volume one

Reputation: 7571

How to pass a URL parameter in an ajax() call

I have a single page (products) which responds to URL parameters and displays the information accordingly.

Here are some examples:

These are user-friendly URLs. The URL parameters are "buy" and "computers".

I need to pass the parameters from the current page in an ajax() to my server so that it knows what types of information to send back e.g.

$.ajax({
    type: "POST",
    url: "/cfc/getsomeproducts",
    dataType: "html",
    data: {
        //psuedo code below...
        ProductCategory: "buy",
        ProductType: "computers"
    }
})

To clarify, if I were on /products/buy, I would need to send ProductCategory: 'buy'. If on /products/buy/computers, ProductCategory: 'buy', ProductType: 'computers'.

How could I achieve something like this?

Upvotes: 0

Views: 1350

Answers (2)

user2045806
user2045806

Reputation:

var url = document.location.pathname;
var values = url.split("/");

$.ajax({
    type: "POST",
    url: "/cfc/getsomeproducts",
    dataType: "html",
    data: {
        ProductCategory: values[2],
        ProductType: values[3]
    }
})

Upvotes: 2

MiiinimalLogic
MiiinimalLogic

Reputation: 818

If you have a solid convention for URL params you can just parse the URL before your ajax call then send an array as data. On the backend, just parse the array in the order your convention defines. Something like:

var myUrl = 'http://my.url/param1/param2',
delimiter = '/',
start = 3,
params = str.split(delimiter).slice(start),


$.ajax({
type: "POST",
url: "/cfc/getsomeproducts",
dataType: "html",
data: {
    params[]: params
}
})

Upvotes: 1

Related Questions