michaelmcgurk
michaelmcgurk

Reputation: 6509

Open simple PHP file with Javascript/jQuery

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

Answers (3)

Ismael Miguel
Ismael Miguel

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:

  • The bit $('#username') will select the element with id username inside your page.
  • The load method, when you pass a string, will try to load HTML from a remote location, splitting the string by the space. (Internally, it will use a $.get on the URL)
  • The #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

Romain De Sa Jardim
Romain De Sa Jardim

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

KOUSIK MANDAL
KOUSIK MANDAL

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

Related Questions