I don't understand this. I have an innerHTML request.
<div id="targetDiv"></div>
One of the includes is:
<?php
echo ("Hello, world");
?>
and works fine, but if I do:
<?php
echo ("Hello, world");
?>
<!--
lots of code I'm trying to debug
-->
it doesn't work.
Why?
getData:
<script language = "javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
It looks mostly likely to be a bug in your PHP code rather than your javascript code. I recommend that you type in the PHP script's URL into your browser and check if it produces the expected output. Better still I recommend that you install firebug. That will allow you to check each and every ajax request as it happens. Better still it will allow you to debug your javascript and inspect variables.
Related
I have script like this:
<script language="JavaScript" type="text/javascript">
function enter() {
this.chrono = new Date().getMilliseconds();
}
function leave() {
this.chrono = new Date().getMilliseconds() - this.chrono;
alert("test" + this.chrono);
var blockingRequest = new XMLHttpRequest();
blockingRequest.open("GET", "visitor_log/ajax_store_visit_duration.php?visit_duration=" + this.chrono, false); // async = false
blockingRequest.send();
return null;
}
window.onload = enter;
window.onbeforeunload = leave;
</script>
PHP part (visitor_log/ajax_store_visit_duration.php file):
<?php
if(isset($_GET["visit_duration"]))
{
$text = $_GET["visit_duration"];
logtxt($text);
echo "OK";
}
else die("application error");
function logtxt($text)
{
$myFile = "test.txt";
$fh = fopen($myFile, 'wb');
fwrite($fh, $text);
fclose($fh);
}
?>
It works in Chrome perfectly, but it doesn't work in Opera.
How to make it cross-browser?
It shouldn't work anywhere. getMilliseconds() returns the milliseconds portion of the date object, not some ultimate milliseconds value. The value is always under 1000. Not useful in comparisons of your magnitude. What you really want is universal time.
(new Date()).valueOf() should get you a value you can work with.
This may be a partial answer, since you didn't actually specify what's not working.
I want to change the content the div named john to the output from the php file when an image is clicked. I'm sure it's simple but I can't find an example that fits. Here's my code:
function ajaxFunction(){
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("john").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "test.php", true);
ajaxRequest.send(null);
}
html
<img class='cross' src='images/cross.png' onclick="ajaxFunction();">
<div id='john'>john</div>
test.php
<?php echo "hello"; ?>
Looks to me like you've got a syntax error with your javascript. Your trying to get the responseText from xmlhttp but your XMLHttpRequest is stored in ajaxRequest
Try this
function ajaxFunction(){
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
document.getElementById("john").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "test.php", true);
ajaxRequest.send();
}
may I suggest for cross browser/version, use:
var ajaxRequest = getXMLHttpRequest();
and then,
function getXMLHttpRequest() {
var re = "nothing";
try {re = new window.XMLHttpRequest();} catch(e1) {};
try {re = new ActiveXObject("MSXML2.XMLHTTP.4.0");} catch(e) {};
try {re = new ActiveXObject("Msxml2.XMLHTTP");} catch(e2) {};
try {re = new ActiveXObject("Microsoft.XMLHTTP");} catch(e3) {};
try {re = new ActiveXObject("MSXML2.XMLHTTP.3.0");} catch(ex) {};
if (re != "nothing") {return re;}
else {return null;};
};
as well as changing it to
ajaxRequest.responseText();
I've managed to solve it with the code below. This code also returns the ID of the element after getting "hello" from the php file.
<script language="javascript">
function calldislike(str){
if (str==""){
document.getElementById("john").innerHTML="";
return;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("john").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?q="+str,true);
xmlhttp.send();
}
</script>
<img src='images/cross.png' onclick="calldislike(this.id);" id='3'>
<div id='john'>john</div>
test.php
<?php echo "hello".$_GET["q"]; ?>
I know that there is a JQuery way of doing this but that's not what I need right now.
I have the following javascript that pulls a page content into a div, however I don't want the whole page, just the content of a DIV from that page:
function ahah(url, target) {
document.getElementById(target).innerHTML ='<img src="ajax-loader.gif"/>';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
And then I call it like this:
LOAD
Where should specify the selector I want to load from page.php?
Normally in AJAX application, in order to get the HTML Fragment the server is the one who is returning the fragment instead of having it selected on the client's side. For example, see this Simple Example on Section 4. Cool AJAX example. Code from the website is provided below for your reference:
<?php
function validate($name) {
if($name == '') {
return '';
}
if(strlen($name) < 3) {
return "<span id=\"warn\">Username too short</span>\n";
}
switch($name) {
case 'bob':
case 'jim':
case 'joe':
case 'carol':
return "<span id=\"warn\">Username already taken</span>\n";
}
return "<span id=\"notice\">Username ok!</span>\n";
}
echo validate(trim($_REQUEST['name']));
?>
Notice that the PHP page is just returning an HTML Fragment containing the <span> only instead of the full html. This is one of the benefits of AJAX call that you don't need to return the full page thereby saving the bandwidth cost since the payload is smaller
In my index.html page I want to load a seperate ajax page when the app is loading,
what is the best way of doing that?
This is my index code:
loading ajax subpage here.....
And the subpage is just:
content..............
Thanks.
using JavaScript you can do that. You have to do that on page load. Here is an example in jQuery.
$(function(){
$('#content').load('/content.html');
});
As an example, you can call a javascript function when the body of your main page loads using the onload property of body:
<html>
<head>
...
</head>
<body onload="loadContent();">
...
</body>
</html>
Among your javascript functions, you will need your loadContent function as well as some functions that perform the HTTPRequest-related operations.
function loadContent()
{
var contentURL = "contentpage.xml";
http.Open("GET", contentURL, true);
http.onreadystatechange = useHttpResponse;
http.send(null);
}
var http = getXMLHTTPRequest();
function getXMLHTTPRequest()
{
try
{
req = new XMLHttpRequest();
}
catch (err1)
{
try
{
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (err2)
{
try
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (err3)
{
req = false;
}
}
}
return req;
}
function useHttpResponse()
{
if (http.readyState == 4)
{
if (http.Status == 200)
{
var xml = http.responseXML;
// do something with loaded XML (such as populate a DIV or something)
}
}
}
You should check out some AJAX tutorials online for more complete information.
Use jQuery: www.jquery.com
There are loads of examples and docs on the website, as well as tons of tutorials on the web.
Good luck
I have a bit of code which alerts the $response from a php code in IE, but for some reason it doesn't work in FF..
Here's the code:
function contactfunction() {
var url = "scripts/php/cbb.php?pname=";
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatecontact1;
xmlHttp.send(null);
}
function updatecontact1() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
alert(response);
}
}
And here's the PHP file (cbb.php)
<?php
$fp=fopen("ip.txt","a+");
fwrite($fp, "cib\r\n");
fclose($fp);
$response = "something";
return $response;
?>
Can anyone help me out here? I'm not sure how to get it to work in FF, it just gives a blank popup..
Do yourself a favour, and use one of the many ajax capable Javascript libraries out there, like jQuery, which frees the user from hacking up code to deal with browser discrepancies (for the most part, at least):
//using jQuery's $.get method
function update(name) {
$.get('cbb.php?name=' + name, function(response) {
alert(response);
$('#someDiv').html(response);
});
}
or:
//using jQuery's $.load method
function update(name) {
//directly inject div id="someDiv" with output of url
$('#someDiv').load('cbb.php?name=' + name);
}
Putting it together:
//when the DOM is ready
$(document).ready(function() {
//bind to click event of all anchors with class="contact"
$('a.contact').click(function(e) {
//stop the link from being followed
e.preventDefault();
//get the name from the link text
var name = $(this).text();
update(name);
});
});
Timmy
McLovin
<div id="someDiv">This is where the output will be injected</div>
See http://docs.jquery.com/Ajax for more information.
I managed to get the code working by using:
function getFile(fileToOpen) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.open("GET",fileToOpen,false);
xmlhttp.send(null);
alert( xmlhttp.responseText );
}
function contactfunction() {
getFile('scripts/php/cbb.php?pname=');
}
If anyone else has the same problem :)