Clickable images in JS request - javascript

Since we are talking about setInterval, clickable objects do not work. I do, however, have an SVG on the page that displays an additional div using jQuery. It would be important to make this image clickable after my query.
<script>
const intervalId = setInterval(function() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
document.getElementById("table").innerHTML = this.responseText;
}
xhttp.open("GET", "https://example.com/abc.php");
xhttp.send();
contentLoaded = true;
}, 6000);
</script>
<div id="table"></div>
The process of clicking on the SVG contained in abc.php:
<img id='svg' src='https://example.com/image.svg' class='svg'>
$('#svg').click(function() {
var text = '<?php echo $text; ?>';
$.post("https://example.com/def.php", {get-php: true, text: text, function(data) {
alert(data);
});
});

Related

How would I make a div containing the image I got from an online json?

So I want to grab the link off of https://nekos.life/api/v2/img/meow and the image on my site. I saw on the official nekos main page that they put the image on the front without doing a script. So something like that would be nice. If you check on the site, it is in a small box, but I basically want that but full-screened so I can use the API easier.
If there is not enough detail, COMMENT PLEASE about the question.
Thanks!
This should work
<html>
<head>
<title>
Title of you site
</title>
</head>
<body>
<div>
<img id="myImg" src="" alt="You can have other details added"></img>
</div>
</body>
<script>
let response = await fetch('https://nekos.life/api/v2/img/meow');
let data = await response.json();
document.getElementById("myImg").src = data.url;
</script>
</html>
<div id='container'></div> <!-- THIS DIV HOLDS THE IMAGE-->
<script>
var div = document.getElementById('container'); //change to actaul id of div on your site
var url = 'https://nekos.life/api/v2/img/meow'; //url of image
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
getJSON(url, callback);
function callback(n, data) {
div.innerHTML = "<img src='"+data.url+"'/>";
}
</script>
I combined all of your into a shorter one! Thanks!
<script>
function Get(yourUrl){
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET",yourUrl,false);
Httpreq.send(null);
return Httpreq.responseText;
}
var div = document.getElementById('myImg');
var json = JSON.parse(Get("https://nekos.life/api/v2/img/meow"));
div.innerHTML = "<img src='"+json.url+"'/>";
</script>

How to make several img-wrappers

I am trying to display several images in img-wrapper divs. In the example below, there are 2 divs. But when I append an image to the second img-wrapper, it becomes shown not only in the second div as needed, but it appears over my first image. How to make several distinct images inside respective img-wrappers? My code uses a get http request to get second and later (a loop) image links. Thanks.
Here's my code:
view_topic.php
<div id="myDiv" class="img-wrapper"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$('.img-wrapper').append($('<img id="theImg">').attr({
'src': "https://nerdist.com/wp-content/uploads/2018/02/year-or-the-tank-girl-header.jpg" ,
'alt': 'test image 1'
})
).scrollTop(9999)
</script>
<div id="myDiv1" class="img-wrapper"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
var xhttp = new XMLHttpRequest();
var get_a_image = "";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText != "no image") {
get_a_image = this.responseText;
}
console.log(this.responseText);
}
};
xhttp.open("GET", "get_a_img.php?answer_id="+<?php echo $rows2_a_id; ?>+"&id="+<?php echo $id; ?>, false);
xhttp.send();
$('.img-wrapper').append($('<img id="theImg2">').attr({
'src': get_a_image ,
'alt': 'test image 2'
})
).scrollTop(9999)
</script>

How do I append HTML from a document loaded with AJAX?

I am trying to append the contents of a .html file to the body of my main page. Basically, I am trying to make a reusable chunk of html that I can load into any page with a simple JavaScript function.
Here is the content of my nav bar, the content I want to reuse:
<div id = "navbar">
<div class = "Tab">
<h1>Home</h1>
</div>
<div class = "Tab">
<h1>Contact</h1>
</div
</div>
That is in a file called navbar.html
Now in my main index.html I want to import it by doing something like this:
<head>
<script src = "importHTML.js" type = "text/javascript"></script>
</head>
<body>
<script type = "text/javascript">
importHTML("navbar.html");
</script>
</body>
That should take care of importing the html in navbar.html.
The content of importHTML.js is this:
function importHTML(url_) {
var request = new XMLHttpRequest();
request.addEventListener("load", function(event_) {
//This is the problem line of code
//How do I get the contents of my response to act like an element?
document.body.appendChild(this.responseText);
}, false);
xmlhttprequest.open("POST", url_, true);
xmlhttprequest.send(null);
}
So, I guess my question is pretty simple: How do I convert that response text to an HTML element so I can append all of it to the body?
Ajax HTML Injection
jQuery $.get() and JavaScript XMLHttpRequest()
This is a demonstration of 2 ways to inject, include, import, etc. There's 3 pages:
index.html
It has 2 links and 2 divs
data1.html
It's data will be imported to index.html by $.get()
data2.html
It's data will be imported to index.html by XMLHttpRequest()
I added jQuery to show the difference in complexity, but they do the same thing. The live demo is at the end of this mess.
jQuery $.get() Setup
HTML on index.html
div#data1 is the element that'll have the HTML of data1.html appended to it.
<h3 id="import1">
Import data1.html by jQuery<code>$.get()</code>
</h3>
<div id="data1"></div>
jQuery on index.html
$('#import1').on('click', function(e) {
e.preventDefault();
$.get('data1.html', function(data) {
$("#data1").html(data);
});
});
JavaScript XMLHttpRequest() Setup
HTML on index.html
div[data-x] is the element that'll have the HTML of data2.html appended to it.
<h3 id="import2">
<a href="">
Import data2.html by JavaScript<code>XMLHttpRequest()</code>
</a></h3>
<div data-x="data2.html"></div>
javaScript on index.html
function xhr() {
var tags, i, clone, file, xhttp;
tags = document.getElementsByTagName("*");
for (i = 0; i < tags.length; i++) {
if (tags[i].getAttribute("data-x")) {
clone = tags[i].cloneNode(false);
file = tags[i].getAttribute("data-x");
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
clone.removeAttribute("data-x");
clone.innerHTML = xhttp.responseText;
tags[i].parentNode.replaceChild(clone, tags[i]);
xhr();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
document.getElementById('import2').addEventListener('click', function(e) {
e.preventDefault();
xhr();
}, false);
README.md
Plunker
Note: This demo relies on user interaction via anchor links. This of course is probably not exactly what you need. You probably want it automatically loaded, so the following modifications are needed:
jQuery
$(function() {
$.get('data1.html', function(data) {
$("#data1").html(data);
});
});
JavaScript
(function xhr() {
xhr();
var tags, i, clone, file, xhttp;
tags = document.getElementsByTagName("*");
for (i = 0; i < tags.length; i++) {
if (tags[i].getAttribute("data-x")) {
clone = tags[i].cloneNode(false);
file = tags[i].getAttribute("data-x");
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
clone.removeAttribute("data-x");
clone.innerHTML = xhttp.responseText;
tags[i].parentNode.replaceChild(clone, tags[i]);
xhr();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
})();
Interestingly there is an upcoming W3C draft for HTML imports
https://www.w3.org/TR/html-imports/
Until then we can append the required markup to the DOM using Javascript.
JQuery approach
$(document).ready(function(){
$( "body" ).load( "navbar.html" );
});
Js haven't native method for this task, but you can use jquery method load
${element}.load('./template.html');
Or, create element-container, and use innerHTML prop
request.addEventListener("load", function(event_) {
//This is the problem line of code
//How do I get the contents of my response to act like an element?
var container = document.createElement("div");
container.innerHTML = this.responseText;
document.body.appendChild(container);
}, false);
UPD
Convert string to DOM.
function strToDom(str) {
var tempEl = document.createElement('div');
tempEl.innerHTML = str;
return tempEl.children[0];
}
NOTE: string element should be one root element, that wraps others
<div> ... </div>
not
<div></div><div></div>
The importHTML.js file will look like this :
function importHTML(url_) {
var request = new XMLHttpRequest();
request.addEventListener("load", function(event_) {
var iDiv = document.createElement('div');
iDiv.innerHTML = this.responseText;
document.getElementsByTagName('body')[0].appendChild(iDiv);
}, false);
request.open("POST", url_, true);
request.send(null);
}
I assume you can create a div and then modify the div.innerHTML to have the content of the response:
function importHTML(url_) {
var request = new XMLHttpRequest();
request.addEventListener("load", function(event_) {
var myDiv = document.createElement("div")
myDiv.innerHTML = this.responseText
document.body.appendChild(myDiv);
}, false);
xmlhttprequest.open("POST", url_, true);
xmlhttprequest.send(null);
}
you need a reference to DOM to know where to innest your loaded page. in your case you could think about appending it to body like this:
function importHTML(url_) {
var request = new XMLHttpRequest();
request.addEventListener("load", function(event_) {
document.body.innerHTML += this.responseText
}, false);
xmlhttprequest.open("POST", url_, true);
xmlhttprequest.send(null);
}

Pull working PHP file (with scripts) into div using JavaScript without iframes

Working within system constraints, I needed a way to put working code from a local .php or .html into a target div without additional libraries, jfiddle, iframes, etc. (jquery was fine)
Here are my failed attempts.
First part of file
This is some page!
<script>$("#fruit").click(function(){Expand01("fruit.php"); return false;});</script>
A pretty good page...
<script>$("#orange").click(function(){Expand01("orange.php"); return false;});</script>
I like this page
<script>$("#tomato").click(function(){Expand01("tomato.php"); return false;});</script>
Later in file (after Expand01 function declared)
<div id="thisdiv"></div>
Attempt 1
<script> function Expand01(targetUrl){
document.getElementById('thisdiv').style.display = "block";
document.getElementById('thisdiv').innerHTML = targetUrl;
document.getElementById('thisdiv').append = '<div id="thatdiv"></div>';
} </script>
Attempt 2
<script> function Expand01(targetUrl){
var myTargetUrl = new XMLHttpRequest();
document.getElementById('thisdiv').style.display = "block";
myTargetUrl.open("GET", targetUrl, true);
myTargetUrl.setRequestHeader("Content-Type","text/plain");
myTargetUrl.send("");
document.getElementById('thisdiv').innerHTML = myTargetUrl.responseText;
document.getElementById('thisdiv').append = '<div id="thatdiv"></div>';
} </script>
Attempt 3
<script> function Expand01(targetUrl){
document.getElementById('thisdiv').innerHTML = $.get(targetURL);
} </script>
Attempt 4
<script> function Expand01(targetUrl){
var myFile = getHTTPObject();
myFile.onreadystatechange = function() {
if(request.readyState == 4) {
if(myFile.status == 200 || request.status == 304) {
var targetDiv = document.getElementById('thisdiv');
targetDiv.innerHTML = myFile.responseText;
} else {
alert("Failure");
}
}
}
myFile.open("GET", targetUrl, true);
myFile.send(null);
} </script>
This is the method I use when doing this for ajax applications. It also allows for the usage of $_SESSION[] variables as well as any Javascript or jQuery located in the php file you are pulling into your container.
jQuery:
$.post('pageloader.php', {url: 'path/to/file.php'}, function(data){
var o = $.parseJSON(data);
if(o.status == 1){
$('#yourContainer').html(o.markup);
} else {
alert(o.message);
}
});
PHP: (pageloader.php)
$url = $_POST['url'];
$response = array();
ob_start();
include("markup/" . $url); // Replace or remove '"markup/" . ' depending on file locations
$response['markup'] = ob_get_clean();
if($response['markup']){
$response['status'] = 1;
} else {
$response['status'] = 0;
$response['message'] = 'There was an issue loading the page.';
}
echo json_encode($response);
Hope this helps!

Generated anchor links in ajax not working

Problem:
I have a which is filled via Ajax. There are some local anchors which are created in this table. When an anchor is clicked, it is supposed to turn a which is hidden to visible and scroll to it automatically. All of this is working when I am filling my by hand (visibility + scroll), but not at all when the is filled via Ajax.
I have the following structure in my index.php file:
<section id="section1">
<table></table>
</section>
<section id="section2>
(this section is hidden via CSS)
</section>
<!-- When the link "More infos" is clicked -->
<script>
$('.moreInfos').click(function() {
if ($('#section2').is(':hidden')) {
$('#section2').slideDown('slow');
}
});
</script>
<!-- Ajax call -->
<script language="JavaScript">
function createInstance()
{
var req = null;
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e)
{
alert("XHR not created");
}
}
}
return req;
};
function storing(data)
{
var element = document.getElementById('banques');
element.innerHTML = data;
}
function submitForm()
{
var req = createInstance();
var montant = document.getElementById("montant").value;
var mois = document.getElementById("selectMois").value;
var taux = '<?php echo $taux; ?>' ;
var data = "taux=" + taux + "&montant=" + montant+ "&mois=" + mois+"&tag=" + 1;
req.onreadystatechange = function()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
storing(req.responseText);
}
else
{
alert("Error: returned status code " + req.status + " " + req.statusText);
}
}
};
req.open("POST", "fonction/table.php", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(data);
}
</script>
The "Simulate" link calls a php file in ajax which will load the table.
Here is the php file called in Ajax :
<?php
include('BDD.php');
echo' <tr>
<th></th>
<th>Banque</th>
<th>Taux</th>
<th>Frais</th>
<th>Mensualité</th>
<th>Plus d\'infos</th>
</tr>';
$tag=1;
$sql="select * from banque where BAN_change=0 and BAN_tag=".$_POST['tag']." ORDER BY BAN_Ordre";
$select=$bdd->query($sql);
$result=$select->fetchAll();
$nb=count($result);
if ($nb!=0){
foreach($result as $value){
$taux=$_POST['taux']+$value['BAN_Taux_Credit'];
$mensu=$_POST['montant']/$_POST['mois'];
$mensu+=$mensu*$taux/100;
echo'<tr>';
echo'<td><img width="50" height="20" src="img/'.$value['BAN_Id'].'/img.jpg" /></td>';
echo'<td>'.$value['BAN_Nom'].'</td>';
echo'<td>'.$taux.'</td>';
echo'<td>'.$value['BAN_Frais'].'</td>';
echo'<td>'.$mensu.'</td>';
echo('<td>More infos</td>');
echo'</tr>';
}
}
?>
Summary: When the user clicks on "More infos", the #section2 is supposed to appear and the browser window scrolls to it. Now this is working perfectly when I fill the by hand. Then the #section2 is showing and the browser is scrolling to the #section2. When I am doing it via Ajax, the anchors are not working anymore.
Thanks
Because events do not magically get attached when you add new ones
$('.moreInfos').click(function() {
if ($('#section2').is(':hidden')) {
$('#section2').slideDown('slow');
}
});
Your code needs to use event delegation
$(document).on("click", '.moreInfos', function() {
if ($('#section2').is(':hidden')) {
$('#section2').slideDown('slow');
}
});
This maybe due to the HTML not being loaded into the DOM. Please try using:
$(document).on('click', '.selector', function() {
alert("Working");
});
"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page."
If this works then you can fine tune it afterwards.
Regards,

Categories