Reputation: 49
This is my HTML code:
<div class="page__question">
<ul>
<li class="question__item" data-answer="A">Вариант А</li>
<li class="question__item" data-answer="Б">Вариант Б</li>
<li class="question__item" data-answer="В">Вариант В</li>
</ul>
</div>
<div class="page__transition">
<a href="#" class="btn">продолжить</a>
<div>
Is it possible to somehow pass the values in JSON that are in "data-answer" without the form tag?
Upvotes: 0
Views: 215
Reputation: 3964
Yes it is possible. You can send your data as json
to a url
and call a method on the server side to do something for you. Here's is simple example to send json
data. In this example I'm sending userId
as our data to remove a User.
function removeUser(userId) {
$.ajax({
url: '/Admin/RemoveUser',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
async: true,
processData: false,
cache: false,
data: JSON.stringify({
'userId': userId
}),
success: function (data) {
alert('successfully removed');
},
error: function (xhr) {
alert('error');
}
});
}
So you can send whatever you want.
Upvotes: 0
Reputation: 2381
Of course this is possible. Most web applications send many AJAX calls from the client that are not related to user input at all. Fetch is a relatively new native API that leverages promises
and is easier to work with than previous implementations.
Here's an example using fetch
:
var options = {
method: 'POST',
mode: 'cors',
body: JSON.stringify({
someKey: 'someValue'
})
}
fetch('someUrl', options);
.then( response => console.log(response) )
.catch( error => console.log( error ) )
Upvotes: 0
Reputation: 644
Yes, using jQuery with ajax, it's quite easy.
$('.btn').click(function() {
var obj = [];
for (var i = 0; i < $('.question__item').length; i++) {
obj.push($($('.question__item')[i]).data('answear'));
}
$.ajax({
url: '#',
method: 'POST',
data: {
key: obj
},
success: function(resp) {
}
});
});
Upvotes: 1
Reputation: 1
You can set key, value pairs at a FormData
object and POST
the FormData
to server using XMLHttpRequest()
or fetch()
.
const fd = new FormData();
for (let el of document.querySelectorAll(".question__item[data-answear]")) {
fd.append(el.dataset.answear, el.textContent)
}
console.log([...fd]);
// fetch("/path/to/server", {method: "POST", body:fd})
// .then(response => console.log(response.ok))
// .catch(err => console.error(err))
<div class="page__question">
<ul>
<li class="question__item" data-answear="A">Вариант А</li>
<li class="question__item" data-answear="Б">Вариант Б</li>
<li class="question__item" data-answear="В">Вариант В</li>
</ul>
</div>
<div class="page__transition">
<a href="#" class="btn">продолжить</a>
<div>
Upvotes: 0