Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a string at a variable index

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

like image 694
geostima Avatar asked Jun 20 '26 14:06

geostima


2 Answers

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);
like image 50
Donnie D'Amato Avatar answered Jun 23 '26 04:06

Donnie D'Amato


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>');
like image 45
Nina Scholz Avatar answered Jun 23 '26 03:06

Nina Scholz