Kyle
Kyle

Reputation: 3042

Changing page title with javascript

function changeTitle(title) 
{ 
document.title = title;
}

function result()
{
    var fetchTitle;
    fetchTitle = new ActiveXObject("Microsoft.XMLHTTP");
    fetchTitle.open("GET", "title.php", true);
    fetchTitle.send(null);
}

setInterval('changeTitle(result())', 1000);//check every second for update

title.php

<?php echo "This is a new title"; ?>

It doesn't seem to change the title. Am I missing something in order for title.php to be displayed?

Thank you.

Upvotes: 1

Views: 410

Answers (2)

Rylab
Rylab

Reputation: 1295

There are several issues here. Primarily, you should be using a more robust AJAX implementation. I would recommend using a library such as JQuery instead of trying to roll your own implementation like that, in order for your script to be reliable and consistent across as many browsers as possible.

Second, your result function is never actually returning the value from the response, so your changeTitle function is never receiving any actual data.

Upvotes: 0

Quentin
Quentin

Reputation: 943143

Am I missing something

Many things

  1. Your changeTitle function expects to be passed an argument (a string), you always pass it the return value of result which will always be undefined as result has no return statement.
  2. You are using the IE 6/7 ActiveX approach to Ajax instead of the modern, standard, cross-browser compatible approach
  3. You do not assign an onReadyStateChange event handler, so you do nothing with the data returned from the XMLHttpRequest object
  4. You are making an Asynchronous request but you approach appears to be based around a Synchronous request, so would fail based on that too (note that synchronous requests lock up the page and should be avoided).

I suggest reading an introduction to XMLHttpRequest

Upvotes: 3

Related Questions