how to create radio buttons by JS. - javascript

i have some problrm creating the radio buttons dynamically. in my problem i am requesting data from server in json formate than i check if it contains options i have to create the radio buttons otherwise simply creates the txt area of field to submit the answer. than again i parse it in json formate and send to the server and if my question is write i get new url for next question and so on...
my question is how can i create the radio buttons and read the data from it and than parse that data like {"answer": "something"}.my code is bellow:
enter code herefunction loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
var data = JSON.parse(this.responseText);
document.getElementById("my_test").innerHTML = data.question;
// Send the answer to next URL
if(data.alternatives !== null){
createRadioElement(div,);
}
var answerJSON = JSON.stringify({"answer":"2"});
sendAnswer(data.nextURL, answerJSON)
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function sendAnswer(url, data) {
xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(this.responseText);
console.log(this.responseText);
loadDoc(data.nextURL);
}
}
// var data = JSON.stringify({"email":"hey#mail.com","password":"101010"});
xhr.send(data);
}
function createRadioElement(name, checked) {
var radioHtml = '<input type = "radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}

I'm only guessing since you have some things in your posted code that won't even run, but createRadioElement returns a detached node which you never actually inject into your document.
E.g.,
document.body.appendChild(createRadioElement());

Related

Joomla 4 Component Development & AJAX - not opening URL but itself

I am trying to develop a component in Joomla 4. I have a simple button that should fire of a script to update the database.
I can make the call to the JavaScript ok, but the JavaScript does not appear to open the request URL, if anything it opens the current URL or refreshes the page. The script works fine outside of Joomla but not inside.
I have tried both the following, and the same thing happens:
*function buttonLike()
{
var xhr = new XMLHttpRequest();
var parentEl = this.parentElement;
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
console.log('Get Here OK' + parentEl.id);
xhr.open('GET', 'liked.php', true);
// Form data is sent appropriately as a POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function ()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var result = xhr.responseText;
console.log('Never Here Result: ' + result);
}
if(xhr.readyState == 4 && xhr.status == 0)
{
console.log('Always Here');
}
};
xhr.send("id=" + parentEl.id);
}*
OR
function buttonLike()
{
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
var request = new Ajax(url, {
method: 'post',
update: some_div,
data: options,
onComplete: function (){
$('some_field').setHTML('I am finished!');
}
}).request();
Been going round in circles on this one, any help would be appreciated.

JS: HTML is not dynamically changing

I am building an web that allows user to like a post when they click a button. CreateLike function calls API and creates a like object however, I would like to have the number of likes updated right away without reloading. I built another API that returns the number of likes for a post. Function LikeCount should put the number of likes into the p tag. It works initially when I load the page however, the value does not change when I click the button even though I can see that the API is called. (After reloading the page the number changes as expected) What am I doing wrong?
I have this HTML:
<p class="like-count" id={{post.id}}></p>
<script>LikeCount({{post.id}});</script>
<button type="button" class="btn-like" onclick="CreateLike({{user.id}},{{post.id}})"></button>
with JS functions:
function CreateLike (userid,postid) {
xhr = new XMLHttpRequest();
var url = "{% url 'likes' %}";
var csrftoken = getCookie('csrftoken')
xhr.open("POST", url, true);
xhr.setRequestHeader("X-CSRFToken",'{{ csrf_token }}')
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({csrfmiddlewaretoken:csrftoken,"user":userid,"post":postid});
xhr.send(data);
LikeCount(postid);
}
function LikeCount(postid) {
var xmlhttp = new XMLHttpRequest();
var url = "{% url 'likecount' id=112233 %}".replace("112233", postid);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = arr.like_count;
document.getElementById(postid).innerHTML = out;
}
}
Like count API looks like this:
{
"like_count": 1
}
if(xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
LikeCount(); //Put your get like count here
} else {
// Handle Errors
}
}
Call LikeCount only after receiving the response of your POST request. Right now you're immediately sending a GET request without ensuring if the previous POST request got completed.
Added
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 201) {
var myArr = JSON.parse(this.responseText);
LikeCount(myArr.post);
}
};
before
xhr.send(data);
and it fixed the issue.

Dynamically filling drop downs on each row of table

I have a table with n number of rows depending on results. There is a drop down on the top of the page. Depending on the selection of that drop down I want to dynamically fill a column on each row with a drop down of its own, based off of an xhttp.response.
This is what I have so far:
function getJobs(taskID){
var xhttp = new XMLHttpRequest();
var url = "dynamicdd.php";
var data = new FormData();
data.append('taskID', taskID);
xhttp.open('POST', url, true);
xhttp.send(data);
$('#cTable tr').each(function(){
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("testSelect").innerHTML = xhttp.responseText;
}
}
});
}
I'm able to change the first row successfully, but subsequent rows don't. I've tried $(this).find(select:eq(0)).html() in replace of the document.getElementById() but no luck. I feel like I'm close but lack expertise in jquery/javascript. Thanks for your help.
You are re-assinging onreadystatechange function for each table row which is wrong,
First assing the function for what it must do,
then send the request
then wait for the response ready
then seek the element you want and replace element html with response text as below,
function getJobs(taskID){
var xhttp = new XMLHttpRequest();
var url = "dynamicdd.php";
var data = new FormData();
data.append('taskID', taskID);
xhttp.open('POST', url, true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
$('#cTable tr').each(function(index, element){
$(element).find('#testSelect').html(xhttp.responseText);
}
}
});
xhttp.send(data);
}

XMLHttpRequest don't include GET request

I'm trying to retrieve JSON data using XMLHttpRequest but it seems like it won't include any of my field data.
var fields = ["ID", "item_id", "item_tag", "item_name", "item_default_price", "item_quantity", "item_comment"];
function loadTable(json_items) {
alert(json_items);
}
var frm = document.querySelector("form.inventory-search-form");
frm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE && this.status == 200){
try {
loadTable(JSON.parse(this.responseText));
} catch(err) {
}
}
};
request.open('GET', '/api/inventory/list', true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // Tells server that this call is made for ajax purposes.
// Most libraries like jQuery/Prototype/Dojo do this
var data = new FormData(frm);
for (i=0; i<fields.length; i++) {
data.append(fields[i], frm.querySelector("[name='" + fields[i] + "']").value);
}
request.send(data);
}
frm.onsubmit(document.createEvent("Event"));
What did I do wrong?
I have checked the FormData and it contained the fields, but it didn't make the required GET request such as /api/inventory/list?ID=2 instead it only issued /api/inventory/list.
Thanks!

Get attribute names are in the main form of entity in dynamics CRM using javascript

I want to fetch logical name of attributes are in main form of account entity from systemform entity using javascript.And also Want to save that names in array or list.
Please Suggest me proper query and how to get name of each attribute from response.
Code:
var serverUrl;
serverUrl = location.protocol + "//" + location.host;
function getformfields() {
debugger;
var oDataUri = "systemforms?$select=formxml&$filter=name eq 'account'";
var data = getODataRecords(oDataUri);
if(data!=null&&data!="")
{
//how to get field name from response
}
}
function getODataRecords(ODataUrl) {
debugger;
var data;
var Query = ODataUrl;
var req = new XMLHttpRequest();
req.open("GET", serverUrl + "/api/data/v8.0/" + Query, false);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Prefer", "odata.include-annotations=OData.Community.Display.V1.FormattedValue");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 200) {
data = JSON.parse(this.response);
}
else {
var error = JSON.parse(this.response).error;
alert(error.message);
}
}
};
req.send();
return data;
}
It is just a matter of parsing the result formxml property.
The only thing to be aware of, is if an attribute is added multiple times, the control's id is appended with a numeric suffix e.g. name1, name2 etc. The datafieldname attribute points to the attribute the control is referring to.
var data = getODataRecords(oDataUri);
if (data && data.value && data.value[0] && data.value[0].formxml) {
var xml = jQuery(data.value[0].formxml);
var controls = xml.find('control');
jQuery.each(controls, function(index, control) {
console.log(jQuery(control).attr('datafieldname'));
});
}

Categories

Resources