Reputation: 6509
I have a PHP file on my server that stores one string <div id="username">my.username</div>
. The URL is http://intranet/text.php.
I would like to use some jQuery/Javascript to read this file and grab this element value.
I had tried to put something together but not sure how to open the file with JS.
'use strict';
var template = '<div id="username">replace-me</div>';
var output = document.createElement('div');
output.innerHTML = template;
output.querySelector('#username').innerHTML = 'get replaced';
console.log(output.innerHTML);
Upvotes: 1
Views: 3095
Reputation: 4241
You can use the jQuery .load() method:
$('#username').load('http://intranet/text.php #username');
This should load the content of that remove <div>
into your old <div>
.
How it works:
$('#username')
will select the element with id username
inside your page. $.get
on the URL) #username
bit, after the URL, will apply to the fetched HTML. (The space is important)This code uses the jQuery library! I've answered in jQuery since it is one of the tags.
Upvotes: 2
Reputation: 96
You can use AJAX to retrieve PHP file like this.
var template = null;
var req = new XMLHttpRequest();
req.open('GET', 'http://intranet/text.php', true);
req.onreadystatechange = function (data) {
if (req.readyState == 4) {
if(req.status == 200){
template = data.responseText;
var output = document.createElement('div');
output.innerHTML = template;
output.querySelector('#username').innerHTML = 'get replaced';
console.log(output.innerHTML);
}
else{
dump("An error occured");
}
}
};
req.send(null);
This code is in pure JS, cause i saw that you were not working with JQuery
Upvotes: 1
Reputation: 2052
Try ajax as follow:
$.ajax({
url:"your-phpfile.php",
success:function(data)
{
//data 'll hold the output of the php file
}
})
Remember before doing this include jquery library.
Upvotes: 1