I am trying to send post id in js. I can send the first post id but how can I send each post's id. inspect element looks like this
<div data-id="post_1"></div>
<div data-id="post_2"></div>
<div data-id="post_3"></div>
<script type="text/javascript" >
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.querySelector('[data-id=post_1]').innerHTML = req.responseText;
}
}
req.open('GET','chat.php?id=1>',true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
here is the code
<div data-id="post_<?php echo $post_id;?>"></div>
<script type="text/javascript" >
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.querySelector('[data-id=post_<?=$post_id?>]').innerHTML = req.responseText;
}
}
req.open('GET','chat.php?id=<?=$post_id?>',true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
All the posts are on the same page. But I am able to get only one post's id. How can I get id post_2 and post_3 in js?
The js shows comment for each post. Only first post is showing comments cause js is getting only the first post's id. Rest are not showing anything.
How can I do the same for every post ?
querySelector will never give you more than 1 element. If you need all elements that satisfy your query, use querySelectorAll.
Using PHP in your JS code means that it will only ever use 1 post_id
Easiest way to do this would be to add a class or other data-attribute to your divs:
<div data-type="post" data-id="1">a</div>
<div data-type="post" data-id="3">b</div>
<div data-type="post" data-id="2">c</div>
You can use the new attribute to get them all and iterate over them.
var elements = document.querySelectorAll('[data-type="post"]')
for (var i = 0; i < elements.length; i++) {
var postId = elements[i].getAttribute('data-id')
// do ajax stuff
// ... then
elements[i].innerHTML = 'ajax response'
}
https://jsfiddle.net/w6kazkm1/4/
edit: Misunderstood your question. Answer is now updated.
Related
so I have am making a GET request to my webservice class to get the emails of all users to store inside of <option> tags within <select> tags. When I print to the console, everything looks correct, but my <select> tags aren't even showing up on the page when I run it in the browser. I have ensured that the id that I'm grabbing is correct, the values are being received from the webservice, information is being parsed correctly, etc... Also, this function is using "onload" from the body tag. Here is my code:
function loader() {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
let val = JSON.parse(this.responseText);
let len = val.length;
document.getElementById("ulistval").innerHTML = "select name='emailname' id='emailget'>";
for(let i = 0; i < len; i++){
document.getElementById("ulistval").innerHTML = `<option value="${val[i].email}">${val[i].email}</option>`;
console.log(`<option value="${val[i].email}">${val[i].email}</option>`);
}
document.getElementById("ulistval").innerHTML = "</select>";
}
}
I want to send a section of html content (not a form data) through AJAX.
I know how to do this in jQuery but i want to achieve with javascript.
HTML (I want to send content who has id=stack)
after clicking on SEND button button, response must be loaded in id=target
<div id='stack'>
<ol>
<li>stack 1</li>
<li>stack 2</li>
<li>stack 3</li>
</ol>
</div>
<button id='btn'>SEND</button>
<article id='target'></article>
AJAX
var btn = document.getElementById('btn');
var target = document.getElementById('target');
// Function for AJAX
function stack(){
var main = document.getElementById('stack');
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
xhr.onreadystatechange = function(){
if(xhr.readyState ==4 && xhr.status == 200){
target.innerHTML = xhr.responseText;
}
}
xhr.send(main);
}
// Bind with the onclick event
btn.addEventListener('click',stack,false);
process.php
<?php
$div = $_POST;
print_r($div);
?>
After running my above code it is just displaying Array()
because Ajax method is not sending the div.
Please help me using Javascript instead of jQuery
Do not send the element reference itself, get the outerHTML property and send that one like so: xhr.send(main.outerHTML);
This sends a string version of the element including its descendants.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML
okay guys !
I asked the above question and finally successfully solved my problem.
So I am going to share my solution with you (love).
SOLUTION :
AJAX
There is one line of code i missed in ajax.
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
So the full Ajax code will be -
var btn = document.getElementById('btn');
var target = document.getElementById('target');
// Function for AJAX
function stack(){
var main = document.getElementById('stack');
//*****new line added
var data = 'key' + '=' + main.outerHTML;
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
//*****(new line added) must add when working with POST data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function(){
if(xhr.readyState ==4 && xhr.status == 200){
target.innerHTML = xhr.responseText;
}
}
xhr.send(data);
}
// Bind with the onclick event
btn.addEventListener('click',stack,false);
process.php
<?php
$div = $_POST;
echo $div['key'];
?>
Thank You !
I have an index which shows a list of orders, each of which calls a function (named dynamically with PHP when I brought the data from the db), to simplify I've reduced the function that each div contains to just an alert. But also every minute an ajax function executes that searches for new orders and appends them on top, with the exact same code as the ones initially loaded. The jQuery works perfectly in the elements that are loaded initially but doesn't work at all in the elements generated dynamically.
This is the index with one initial order inside, BEFORE newOrders runs for the first time. The alert on that order functions properly
<div id="content">
<div id="pedido_4126" class="pedido">
<h4>Pedido 4126</h4>
<button id="btn4126">Alert</button>
<script>
alert("Pedido 4126");
</script>
</div>
</div>
<script>
function newOrders() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "simplereq.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
var element = document.querySelector('#content');
var content = element.innerHTML;
ultimoid = response.ultimoid;
element.innerHTML = response.contenido + content;
}
};
xhttp.send("ultimoid="+encodeURIComponent(ultimoid));
}
setInterval(newOrders, 60000);
</script>
And this is the index when the function has executed once and appended a new order on top with it's corresponding script, dynamically generated and received from the AJAX call:
<div id="content">
<div id="pedido_4255" class="pedido">
<h4>Pedido 4255</h4>
<button id="btn4255">Alert</button>
<script>
alert("Pedido 4255");
</script>
</div>
<div id="pedido_4126" class="pedido">
<h4>Pedido 4126</h4>
<button id="btn4126">Alert</button>
<script>
alert("Pedido 4126");
</script>
</div>
</div>
<script>
function newOrders() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "simplereq.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
var element = document.querySelector('#content');
var content = element.innerHTML;
ultimoid = response.ultimoid;
element.innerHTML = response.contenido + content;
}
};
xhttp.send("ultimoid="+encodeURIComponent(ultimoid));
}
setInterval(newOrders, 60000);
</script>
As you can see, the html and script are exactly the same, but the one on the new order brought by the ajax call, doesn't work.
Ok, so doing more research I came upon the best answer for my case, I'll leave it here in case it helps someone:
In the content I generate in the AJAX call, I print the scripts like this, and obviously hide it with css:
<div class="javascript">
$("body").on("click","#btn4255",function(){
alert("Pedido 4255");
});
</div>
And then I execute this function every time the AJAX call is returned
$('.javascript').each(function() {
eval($(this).text());
});
I only evaluate strings I generate myself so in this case I think it's not unsafe to use eval().
Found on questions on is_ajax- Django request.is_ajax returning false - but that does not solve anything for me. I'm working around this by using 'ajax' in the GET...
I'm also trying to post through AJAX, but I can't find the results.
My AJAX handler is this:
function getContent(pageGet,method,post,target) {
if (typeof(post) ==='undefined') post = "";
if (typeof(method) ==='undefined') method = "GET";
if (typeof(target) ==='undefined') target = "body";
pageGet = '/?ajax=home/'+pageGet.replace('?','&');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var body = document.getElementById(target);
if (this.readyState == 4) {
if (this.status == 200) {
body.innerHTML = this.responseText;
var scripts = body.getElementsByTagName("script");
var script_amount = scripts.length;
for( var i = 0; i < script_amount; ++i)
eval(scripts[i].innerHTML);
} else if (this.status == 0) {
getContent('main.html');
} else {
body.innerHTML = "Failed with "+this.status;
}
}
};
xhttp.open(method, pageGet, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(post);
return false;
}
As, I said this never registers in is_ajax, but AJAX is working fine. This is the value of pageGet:
/?ajax=home/forms/genericForm.html&form=UserForm
and this the value of post:
username=sdf&password=dfs&=Submit&
Obviously method="POST".
This gets to my view.py, and the request.GET is populated properly with 'ajax' (my workaround for the other problem), and 'form'. But request.POST is empty, as well as request.body which is alluded to here - Ajax POST not sending data when calling 'request.POST' in Django view and some other answer.
There are also mentions of a "CSRF" token, but I don't know what I'm doing wrong. The view code just prints request.GET,body, and POST, and is_ajax.
Please, only pure JS solutions.
Progress
I managed to get post to work - by default CSRF is enabled, and you must set the AJAX header with it. If anyone figures the is_ajax part I'd be obliged.
I am trying to create an application that will show, and periodically change, a paragraph of text (like a news article or similar).
I want the data to come from an xml file so other people can add stories/remove old stories etc.
I'm trying to get my JavaScript to populate a single html field with data from an xml file. Then after a given time, for now we'll say 4 seconds, it will change to the next piece of data.
Below is a very crude version of what I've been trying to do:
HMTL:
<head>
<script src="script.js"></script>
</head>
<body>
<div id="text"></div>
</body>
XML:
<document>
<text>one</text>
<text>two</text>
<text>three</text>
</document>
JavaScript:
var timer = setInterval(addText,4000);
var xhttp = new XMLHttpRequest();
xhttp.onreadystaechange = function() {
if(this.readyState == 4 && this.status == 200) {
addText(this);
}
};
function addText(xml) {
var xmlDoc = xml.responseXML;
var count = 0;
var max = xmlDoc.GetElementsByTagName("text");
document.getElementById("text").innerHTML =
xmlDoc.getElementByTagName("text")[count].childNodes[0].nodeValue;
if (count < max.length) {
count++;
} else {
count = 0;
}
}
xhttp.open("GET", "XMLFile.xml",true);
xhttp.send();
The current problem I am experiencing is that the first xml field populates successfully, but then I get an error saying "Unable to get property 'responseXML' of undefined or null reference".
Ideally what I'd also like is for the xml document to be opened everytime the function occurs, so the application doesn't have to be restarted if extra data is added to the xml file - if that makes sense (and is possible)
You can place addText in the scope of onreadystatechange handler. Something like this.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var xmlDoc = this.responseXML;
var count = 0;
var xText = xmlDoc.getElementsByTagName("text");
var max = xText.length;
var docText = document.getElementById("text");
function addText() {
//docText, xText and count are available from parent scope
docText.innerHTML =
xText[(count++) % max].childNodes[0].nodeValue;
}
var timer = setInterval(addText,4000);
}
};
xhttp.open("GET", "XMLFile.xml",true);
xhttp.send();