Why won't this javascript code work in Wordpress post? - javascript

I have xml file test.xml with the content
<?xml version= "1.0" encoding= "UTF-8" ?>
<LIST><script />
<ONEP>
<LINK>/wordpress/new_1.html</LINK>
<CHAPTER >One 1</CHAPTER>
</ONEP>
<ONEP>
<LINK>/wordpress/new_2.html</LINK>
<CHAPTER>One 2</CHAPTER>
</ONEP>
</LIST>
I want to load this content into my Wordpress page so I insert the code which is given below into my Wordpress page directly.
<div id="demo">
</div>
<script type="text/javascript">
window.onload = function() {
loadXMLDoc();
};
function loadXMLDoc( ) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "../wordpress/test.xml", true);
xmlhttp.send( );
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<strong>Chapter</strong>";
var x = xmlDoc.getElementsByTagName("ONEP");
for (i = 0; i <x.length; i++) {
table += "<br/><a href=\".." +
x[i].getElementsByTagName("LINK")[0].childNodes[0].nodeValue +
"\">" +
x[i].getElementsByTagName("CHAPTER")[0].childNodes[0].nodeValue +
"</a>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
Now I preview the page.Nothing is found in the page.
I even tried the code using the plugin "Jquery in posts and page" but still the code does not work.I am completely lost.Note the code works perfectly fine in normal html file.It is not working only in Wordpress page and posts.Any help please.
Thank you in advance.

Try Below code to get data from xml file into PHP:
if (file_exists('path to test.xml')) {
$xml = simplexml_load_file('path to test.xml');
echo '<pre>';
print_r($xml);
} else {
exit('Failed to open test.xml.');
}
you will get multidimensional array with all tags and inner content into PHP.

Related

TVMaze api error

I am creating a site for listing TV shows and I am using TVMaze api for it. I am beginner in working with JSON so maybe my problem is that, but here is the weird thing happening.
My table is generated with this code:
var keyword = "";
var $url = "";
$('#submit').on('click', function (e) {
//e.preventDefault();
keyword = $('#search').val();
window.sessionStorage['keyword'] = keyword;
});
if (!window.sessionStorage['keyword']) {
$url = " http://api.tvmaze.com/shows?page=1";
} else {
keyword = window.sessionStorage['keyword'].toString();
keyword = keyword.toLowerCase().replace(/\s/g, "");
$url = "http://api.tvmaze.com/search/shows?q=" + keyword;
//alert($url);
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var $obj = JSON.parse(this.responseText);
for (var i = 0; i <= $obj.length - 1; i++) {
var $item = '<div> \
<div>\
<h2>' + $obj[i].name + '</h2> \
<div> ' + $obj[i].rating.average + ' </div>\
<p>' + $obj[i].summary + '</p>\
Track\
</div>\
</div>';
$('.show-items-container').append($item);
}
}
};
//alert($url);
xmlhttp.open("GET", $url, true);
xmlhttp.send();
So first it checks if there is keyword entered in a search bar and if there isn't it sends a request to the /page=1, and if there is a keyword entered, it should print the show. But, in my case, it reads to url like it is supposed to, but nothing shows up. And if I search that link in the browser it lists the correct show.
For example if I put 'kirby' in the search bar, it reads this url -> http://api.tvmaze.com/search/shows?q=kirby , but nothing shows in the table and there are no errors in the console. If you enter that same url in the browser, it works.
Can anyone tell me what the problem is?
Looks like onclick you are not making the xhr request. You call xmlhttp.open and xmlhttp.send outside of the click event so nothing happens on click. Also I noticed you were accessing the wrong property it should be $obj[i].show.___ vs $obj[i].___
var keyword = "";
var $url = "";
var xmlhttp = new XMLHttpRequest();
function makeRequest() {
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// clear the current search results
$('.show-items-container').empty();
var $obj = JSON.parse(this.responseText);
for (var i = 0; i <= $obj.length - 1; i++) {
// make sure you access the correct property
var $item = `<div>
<div>
<h2> ${$obj[i].show.name} </h2>
<div> ${$obj[i].show.rating.average} </div>
<p> ${$obj[i].show.summary} </p>
Track
</div>
</div>`;
$('.show-items-container').append($item);
}
}
}
// make the xhr request on click
xmlhttp.open("GET", $url, true);
xmlhttp.send();
}
$('#submit').on('click', function(e) {
keyword = $('#search').val();
$url = "https://api.tvmaze.com/search/shows?q=" + keyword;
// call on click
makeRequest();
});
// call on page load
makeRequest();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='search' />
<button type="button" id='submit'>Submit </button>
<div class="show-items-container">
</div>

is it possible to display an image from a xml file using DOM?

I'm new to this forum and I want to ask a question on how can I make an image from an xml file to load itself using DOM? here is my code and I don't know what's wrong in it. Can anyone help me debug this please? thanks :)
<html>
<head>
<script language="javascript" type="text/javascript">
function showImage(){
var xmlimg = document.getElementById("myphoto");
var photo=xmlimg.getElementsByTagName("photo");
var showImg =document.createElement("div");
showImg.createElement("IMG");
showImg.setAttribute("src","sunset.jpg");
var getImage=document.createElement("div");
getImage.setAttribute("class","fileko");
showImg.appendChild(getImage);
var viewimage= document.createTextNode(photo.getElementsByTagName("fileko")[0].firstChild.data);
getImage.appendChild(viewimage);
getImage.appendChild(viewimage);
var getAttr=document.createElement("div");
getAttr.getAttribute("stolen");
showImg.appendChild(getAttr);
document.getElementsByTagName("body")[0].appendChild(showImg);
}
</script>
</head>
<body onload="showimage()" style="display:none">
<xml id="myphoto" >
<photo kind="stolen">
<fileko>sunset.jpg</fileko>
<desc>Sunrise</desc>
</photo>
</xml>
</body>
</html>
You can do an Ajax request to the xml file and get the data needed. Then create an Image element with the proper properties based on retrieved data and then append that image element into the DOM.
yes it is possible just follow below code and you will get that easily what you need to do. this is my code that is fetching data from xml file
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
my xml look like this
xml file

How to show php file output on Page where from it is called?

I have webpage on which i run a php file by javascript as given below
<script type="text/javascript">
var bhs = document.createElement('script');
var bhs_id = "yvw3lwc1tnvqfh4k4k4hisossew";
bhs.src = "//example.com/insert.php?site=" + bhs_id + "";
document.head.appendChild(bhs);
document.write("<span id='calc'></span>");
</script>
This JavaScript successfully insert data into insert.php file and then send to database. Besides i want to show one variable value generated in insert.php file in span id calc on a webpage where from above JavaScript is executed. How to do this? Thanks in advance.
It´s better use AJAX:
function loadDoc() {
var xhttp = new XMLHttpRequest();
var bhs_id = "yvw3lwc1tnvqfh4k4k4hisossew";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert('OK!');
}
};
xhttp.open("GET", "//example.com/insert.php?site=" + bhs_id, true);
xhttp.send();
}
Reference:
http://www.w3schools.com/xml/ajax_intro.asp

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!

Categories