http_build_query and URLSearchParams - javascript

I have a from with inputs with array name like foo[] so when submitting the form my url become foo[]=lorem&foo[]=ipsum but when using php http_build_query to regenerate this sort of query it adds key to the array like this foo[0]=lorem&foo[1]=ipsum.
My issue is that on the front I'm using URLSearchParams.getAll('foo[]') to get the value, but it works only without the array keys added by http_build_query.
So is there a way to use URLSearchParams with this format ?

Based on #Plamen Nikolov link I fixed my issue by changing my Javascript to handle the inputs that are arrays with or without index keys (added by PHP with http_build_query) like this :
// Before
let urlParams = new URLSearchParams(window.location.search);
// After
let urlQuery = decodeURI(window.location.search).replace(/\[\d+\]/g, "[]");
let urlParams = new URLSearchParams(urlQuery);

Related

Find elements from concatenate strings in JS

How can I search the values in an Object from strings, something like:
const query = "['arg1']['arg2']"
const renderImage = async (index) => {
const data = await fetchImage(index)
const image = document.querySelector('.div')
image.setAttribute("src", data`${query}`)
}
The fetch function is perfect working.
Edit:
The image source is in the data['arg1']['arg2']. If I use image.setAttribute("src", data['arg1']['arg2']) the code runs fine, but I need to do this dynamically and concatenate strings will help me.
Summing up: can I get the same result data['arg1']['arg2'] concatenating object and "query" (['arg1']['arg2'])?
you can store the path as an array of keys and access it like this
const query = ['arg1', 'arg2']
...
image.setAttribute("src", query.reduce((o, k)=>o[k], data))
It seems you are trying to extract the property names you want, from a poorly formatted string. Ideally, you would get query into a better format to begin with, so you don't have to parse the string. For instance, if you could get query as two separate variables:
const query1 = 'arg1';
const query2 = 'arg2';
image.setAttribute("src", data[query1][query2]);
you could also store query in a better data type to do this, like const query = { arg1: 'arg1', arg2: 'arg2' }; then access with dot syntax data[query.arg1][query.arg2].
But if you must keep query as this weirdly formatted string for some reason, you can do something like this, parsing the string into it's parts, putting them into an array, then using the array to access the right data within data.
let query = "['arg1']['arg2']";
query = query.slice( 2 ).slice( 0, -2 ).split( "']['" );
image.setAttribute( "src", data[query[0]][query[1]] );

How to get "&" in urlParams.get in Javascrpt

I'm trying to get the parameter used in URL with java script.
example URL:
`http://localhost:8002/all-products?categories=Events%20&%20Festivals`
I use this code to get the value in categories.
const urlParams = new URLSearchParams(queryString);
const category_name = urlParams.get("categories")`
I only get Events as an output i need to get Events & Festivals but i cant seems to get it
you can add some other character instead of &
for eg. '-'
`http://localhost:8002/all-products?categories=Events-Festivals`
OR
you can encrypt the category value and pass it in URL

There is way to save only part of the string object into async-storage?

There is way to save only part of the string object into async-storage ?
for example if inside the "result.userPrincipalName" it save " bob23#hotmail.com "
so i want it will be save only the "bob23" , so what is the way to do it ?
await AsyncStorage.setItem(
'AZURE-USERNAME',
JSON.stringify(
result.userPrincipalName.substring(0, data.indexOf('#'))
)
);
You condo something like this.
You can remove part of the string after a certain character.
As I can see in the documentation. It stores as a key-value pair.
So I made changes
let data = JSON.stringify(result.userPrincipalName);
//here substring will remove characters after and including `#`
data = data.substring(0, data.indexOf('#'));
await AsyncStorage.setItem('AZURE-USERNAME', data);
I believe that you need to handle your desirable data on top level (add new input to user / new field in db with desired data etc. I don't know whereby you get your userPrincipalName).
But, if it's not possible, you can follow something like this:
const name = result.userPrincipalName.split('#')[0];
if (!name) throw new Error('Invalid email');
await AsyncStorage.setItem('AZURE-USERNAME', name);
Simply you can use split function in Javascript. More information
//Split the mame using split function
const splitName = result.userPrincipalName.split("#");
//Get the split value and save it
//After you splitting [0] mean first character set
const name = splitName[0];
//Save it to AsyncStorage
await AsyncStorage.setItem("AZURE-USERNAME", JSON.stringify(name));

How to get URL parameters names only and not values

There are hundreds of example out here showing how to get URL parameters but I couldn't find any to list ONLY parameters (variables) name and not values?
For example, if I have something like:
www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008
I want to get only makes,models,years and if URL change to
www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler
should be like makes,models
or on
www.mydomain.com/filtres?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008,2010&city=vancouver
the out should be like makes,models,years,city
You can use URLSearchParams
Sample:
const queryString = "?makes=honda,mazda,jeep&models=crv,cx5,wamgler&years=2008"
const urlParams = new URLSearchParams(queryString);
console.log([...new URLSearchParams(urlParams).keys()]);
console.log(
[...new URLSearchParams(window.location.search).keys()].join(',')
);

How to save multiple form values as a consolidated String in Local Storage and retrieve them to be displayed on the browser

I'm trying to create a 'Notes' application which is basically a form that the user uses to enter 2 values, a name and a note.
I am displaying the 2 values as a 'consolidated note' on the browser with a delete button.
There can be any number of notes entered using this form.
How can I save the consolidated notes(i.e with Creator's name and the actual content of the note) in a string or array in the Local Storage and then retrieve it to be displayed on the browser when the browser reloads?
I understand that we save it using JSON.stringify and retrieve the data from the Local Storage using JSON.parse, but I'm unsure of how to save these multiple notes in the LOCAL Storage and retrieve them. Please help!
function addNoteLocalStorage(){
let notes = getNotesFromStorage();
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
obj.creator = creator;
obj.note = note;
let jsonstring = JSON.stringify(obj);
//create an array and push the string to the Object Array
objArray.push(jsonstring);
//store the new note
localStorage.setItem('notes', objArray);
}
The above code saves more than one note in the Local Storage.
Currently, this is how the array looks when stored in LS.
{"creator":"dgfdxsf","note":"dsgdsg"},{"creator":"sfs","note":"asd"}
How can I retrieve the values back into an object so that I can display each creator and note associated with that creator ?
Create an object of the values you get from the form.
var obj = {
creator : note
}
Now store this object in the local storage by stringifying in the same as you are doing (JSON.stringify). While retrieving, do a JSON.parse to retrieve the object.
If you have multiple objects like these, push them into an array and store that array in the local storage.
There is no need to convert a string to a JSON string, so you can play with your data without the need for stringify() and parse(). If you save the notes as array, however, you will need to do that.
// Add Note to Local Storage
function addNoteLocalStorage(){
//get saved notes. Set notes to empty string if it's the first time.
let notes = localStorage.getItem('notes') || '';
console.log("Notes return: "+notes);
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
let consolidatedNotesString = creator+":"+note;
//append the new note to the existing note
notes += '\n'+ consolidatedNotesString;
//store the new note
localStorage.setItem('notes', notes);
}
With your edited question, you're saving notes in the form of array of objects, in which case you will of course need to stringify and parse back the notes. One issue with your current code is that you're converting to string the objects(notes) but you save the array which contains the notes as it is. stringify the whole array instead and that's enough. And the way you access the stored notes is by the getItem method and parse it to get back the array. Make sure to save the empty objArray as notes in the local storage before calling addNoteLocalStorage function though, or you will need to check if notes are already in the storage before trying to parse it.
const objArray = [];
localStorage.setItem('notes', JSON.stringify(objArray));
function addNoteLocalStorage(){
objArray = JSON.parse(localStorage.getItem('notes'));
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
//push the string to the Object Array
objArray.push({creator, note});
//store the new note
localStorage.setItem('notes', JSON.stringify(objArray));
}
//And to get the first note and creator for example, you write like:
let noteArray = JSON.parse(localStorage.getItem('notes'));
let firstNoteCreator = noteArray[0].creator;
let firstNote = noteArray[0].note;

Categories

Resources