XMLHttpRequest don't include GET request - javascript

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!

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.

how to create radio buttons by JS.

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());

AJAX xmlhttp.open sumit data using POST method

I am trying to send a form data using POST method and xmlhttp.open
Please help find the error in my code
function submitChat() {
if (form1.msg.value == '' ) {
alert ('ALL FIELDS ARE MANDATORY');
return;
}
var xmlhttp = new XMLHttpRequest();
var msg = form1.msg.value;
var params = 'msg=helloooooooo';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('POST', 'rtest.php?rid=14', true);
xmlhttp.send(params);
}
Everything is fine and it is working with GET method. but POST method is not working. Please help.

cannot reach readystate=4

I go this AJAX code that worked fine, but when I moved it to a new file it stopped working.
I managed to find out that the readystate isn't 4 and status isn't 200.
The code was given to my in class by the teacher. It worked find until I made new file.
<script type = "text/javascript">
var request = false;
if (window.XMLHttpRequest)
request = new XMLHttpRequest();
else if (window.AciveXObject)
request = new ActiveXObject("Microsoft.XMLHTTP");
function login(PhpFile,divId,frm)
{
if (request)
{
var obj = document.getElementById(divId);
request.open("POST",PhpFile);
//setting the header
request.setRequestHeader('Content-Type','application/x-www-form- urlencoded');
request.onreadystatechange = function()
{
if (request.readyState == 4 &&
request.status == 200){
obj.innerHTML =request.responseText;
}
else
{
alert("here");
}
}
request.send("log="+frm.log.value+"&pwd="+frm.pwd.value);
}
}
</script>
if you alert(request.responseText) in that else case, that may give you more information
'application/x-www-form- urlencoded'
should be
'application/x-www-form-urlencoded'

Categories

Resources