3

I have not been able to find a working example or a good explanation of how I can achieve the following: (I would appreciate if anyone can point me in the right direction.

I have a query string: **"/api/bla?sources=[1,2]&plans=[1,2]&codes=[1,2,3]"**

I will be updating the query string via either javascript or jquery when certain events occur on my page, doesnt matter which.

For example, there is a multi select dropdown on the page which houses [sources] and [plans] and [codes]... These dropdowns have IDs which i am to update my request url with upons selecting items in teh dropdowns.

When a source with ID "3" is selected from the dropdown (or checkbox, doesnt matter what page controls are being used) the query string parameter sources[1,2] will need a "3" appended. Likewise then if the item with an ID of "2" is unselected, it will likewise be removed from the query string leaving the new string as sources[1,3]

I am somewhat new to javascript/jquery and especially more advanced string manipulation. I have been attempting to recreate something to demonstrate this and have gotten to the following which is not fully working.

Basically my initial if statement works as intended, but the moment the else is hit (when another ID needs to be added to an existing model in the query string - like a second ID for [sources] or [codes]) it returns wonky output - seeng as I couldnt get the right formula to update everything correctly.

//TIMEMTABLE QUERY
function updateCalendar(filter_id, filter_element) {
    //Run through the filter checks before making final call to query and update timetable?

    //GET THE MODEL/OBJECT NAME
    var queryName = filter_element.attr('data-owner');


    //GET THE IDs //this is either an array of all selected IDs or a single id which is used in the else statement
    var queryId = filter_element.attr('value');
    var queryIds = $('#'+filter_id).val();


    var modelCheckIndex = requestString.toLowerCase().indexOf(queryName.toLowerCase());
    //build a request string
    if (modelCheckIndex < 0) {
        console.info('ADD MODEL TO QUERY STRING');
        requestString = requestString + "&" + (queryName.toLowerCase() + "[" + queryIds + "]");
        console.log(requestString);
    }
    else{
        console.info('UPDATE MODEL ON QUERY STRING');
        var position = requestString.toLowerCase().indexOf(queryName.toLowerCase());
        //requestString = requestString.substr(modelCheckIndex -1, requestString.length -1) + "," + queryId + "]";
        requestString = requestString.slice(modelCheckIndex.indexOf("]"), modelCheckIndex) + "," + queryId;
        console.log(requestString);

    }

//MAKE THE API CALL USING CREATED QUERY STRING

}

If anyone has any examples or fiddles lying around I would also appreciate it. Fiddle I am trying to get to work

6
  • Can include html at Question , create stacksnippets , jsfiddle jsfiddle.net to demonstrate ? Commented Dec 25, 2015 at 16:17
  • Can you post the 'wonky output' ;) Commented Dec 25, 2015 at 16:17
  • 1
    $.serialize](https://api.jquery.com/serialize/) and [$.serializeArray may help :) Commented Dec 25, 2015 at 16:29
  • fiddle added: jsfiddle.net/xf4zt25a/2 Commented Dec 25, 2015 at 16:29
  • are you sure, that this sources[1,2]& is right, or that sources=[1,2]& may be right? Commented Dec 25, 2015 at 16:39

2 Answers 2

2

It looks like you are just having trouble parsing and updating a query string. In which case, I have a function I've been using for that (thank you Google)

function getUriParams(string) {
    var params = {},
    queryString = string.slice(string.lastIndexOf('?')).substring(1),
    regex = /([^&=]+)=([^&]*)/g,
    m;
    while (m = regex.exec(queryString)) {
        params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }
    return params;
}

The input is your requestString and the output is an object of key value pairs of the query string.

To make the object a string, jQuery makes it easy with $.param().

//get key value pairs
var obj = getUriParams(requestString);

//make query string
var str = $.param(obj);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your input this is superb. I ended up using Nina's solution, it was my next train of thought.
1

I suggest to change the logic a bit. I would use some data storage for the wanted parameter and rebuild the request string every time when it's necessary, like the below example.

It is much more better, than rebuild the string each time when some value has changed.

var data = {
        sources: [1, 2],
        plans: [],
        codes: [1, 3, 4]
    };

function buildStr() {
    function get(key) { return key + '=' + JSON.stringify(data[key]); }
    return '/api/bla?' + ['sources', 'plans', 'codes'].map(get).join('&');
}

document.write('<pre>' + buildStr() + '</pre>');

1 Comment

I love ths idea, this is exactly what I thought of last night and am currently implementing. Creating a class with arrays for each type just as you depicted and I have functions to add and remove strings from each of the arrays based on when an id needs to be added and/or removed.

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.