3

this is my client side code.The server side php code is simply to echo statement.

function load(){if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari     
    xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.xmlhttp");}
    if(xmlhttp==null)
    { alert ("Your browser does not support XMLHttpRequest!");
        return; }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.write("Received");
            document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
        }
    };
    xmlhttp.open("GET", "http://localhost/tphp.php?", true);/*this works separately*/
    xmlhttp.send();document.write("Sent")}

My html code contains

<h4 id="txtHint">to be replaced</h4>
<input type="button" onclick="load()" value="click" />

My PHP code it contains echo statement.i just want to test it

<?php
echo "It's working";
?>
Venkat
  • 351
  • 2
  • 10
  • If i use the URL in a new tab then it works.so no error on server side code..plz help me – Venkat Nov 27 '15 at 07:29
  • Is your client-side code being served from the same server? AJAX by default can't cross domains, this includes when the client-side script is called from the file system (`file:///...`). – RoToRa Nov 27 '15 at 08:29
  • Also don't include the domain in the URL. Just use `"/tphp.php?"`. – RoToRa Nov 27 '15 at 08:30
  • BTW, your code looks very chaotic. At least make sure the indentation is correct, and avoid `document.write` even/especially for test code. – RoToRa Nov 27 '15 at 08:35

2 Answers2

1

I am not sure if you can use jQuery, if so please make these things simple:

$("body").append("Sent<br/>");
$.get("/tphp.php", function (data) {
  $("body").append("Received: " + data + "<br/>");
});

Advantages of using jQuery:

  1. Code is simple.
  2. Excellent cross browser support.
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Please make sure you called load() function correctly. Check your console.

function load() {

   console.log("Called");
   var xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
     document.getElementById("txtHint").innerHTML = xhttp.responseText;
     }
    };
    xhttp.open("GET", "http://localhost/tphp.php", true);
    xhttp.send();
   }
azim hamdan
  • 113
  • 10