tags:

views:

57

answers:

2

Hi all, 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..

+3  A: 

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);
    });

});

<a href="no-script.php" class="contact">Timmy</a>
<a href="no-script.php" class="contact">McLovin</a>

<div id="someDiv">This is where the output will be injected</div>

See http://docs.jquery.com/Ajax for more information.

karim79
Yeh I know, I think jQuery is easier, but was told it HAD to be ajax.. *sigh* I managed to work it out, but thank you, will use this if I have to do it again :)
SoulieBaby
ajax is a built in functionality OF jQuery. that's what the .load() command is.
contagious
A: 

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 :)

SoulieBaby