Skip to content

Instantly share code, notes, and snippets.

@attilabacso
Last active November 15, 2022 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save attilabacso/ec02f4765e58b6a0b24962fc285c61ec to your computer and use it in GitHub Desktop.
Save attilabacso/ec02f4765e58b6a0b24962fc285c61ec to your computer and use it in GitHub Desktop.
// SELECT ON CHANGE VALUES FETCHING TO PHP
document.querySelectorAll(`select.collect`).forEach(dropdown =>
dropdown.addEventListener(`change`, (e) => {
// GET VALUES
let value = e.target.value;
let text = dropdown.options[dropdown.selectedIndex].text;
let price = dropdown.options[dropdown.selectedIndex].getAttribute(`attr-price`);
let name = e.target.name;
let data = {
name: name,
value: value,
text: text,
price: price,
};
// FETCH
fetch('response-ajax.php', {
method : 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then(response => response.text())
.then(text => {
// TRY RESPONSE TYPE
try {
// JSON
let data = JSON.parse(text);
console.log(`JSON:`);
console.log(data)
} catch(err) {
// NOT JSON
console.log(`NOT JSON:`);
console.log(text)
}
})
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment