PHP code does not run - php

I'm trying to run a PHP code by the click of a button, but it does not seem to work. I'm running this on a MAPM server.
<html>
<head>
</head>
<div onClick="count();">Click!</div>
<script>
function count() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('GET', 'count.php');
xhr.send();
}​
</script>
</body>
</html>
In the PHP file (count.php) we have this code:
<?php
Print "Hello, World!";
?>

you need your page to listen to the request;
function count() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function (){
if(xhr.readyState == 4){
if(xhr.status == 200){
// WHAT HAPPENS ON SUCCESS
alert(xhr.responseText);
}else{
alert('timeout error or something');
}
}
};
xhr.open('GET', 'count.php');
xhr.send();
}​;

You need to pass null to the send() method like below (also be sure that the URL is correct, my hunch is that it should be "/count.php"):
xhr.send(null) // it's a GET request
For a detailed tutorial, check out this MDN doc https://developer.mozilla.org/en/AJAX/Getting_Started

Related

DIV auto refresh

I try to refresh div every 5 sec but it doesn't work, I have 3 files.
index.php that contains:
<html>
<head>
<script type="text/javascript" src="javascript/jquery-1.3.2.js" ></script>
<script type="text/javascript" src="javascript/javascript.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval ("newmsg()", 5000);
setInterval ("newpause()", 5000);
});
</script>
</head>
<body>
<div id="msgs">
<?php echo date("H:i:s"); ?>
</div>
</body>
</html>
Then I have javascript.js that contains
function GetXmlHttpObject() {
var xmlHttp = null;
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function newmsg(){
var request = GetXmlHttpObject();
request.open("get", "msgsprint.php", true);
request.send(null);
request.onreadystatechange = function response() {
if (request.readyState === 4) {
if(request.responseText != "false"){
$('#msgs').html(request.responseText);
}
}
}
}
function newpause(){
var request = GetXmlHttpObject();
request.open("get", "newpauseprint.php", true);
request.send(null);
request.onreadystatechange = function response() {
if (request.readyState === 4) {
if(request.responseText != "false"){
$('#newpauselist').html(request.responseText);
}
}
}
}
and i have msgsprint.php that contains
<?php
echo 'ivan';
?>
Could anybody please tell me what i did wrong.
There doesn't seem to be anything wrong in your code, maybe you are not getting a valid answer from msgsprint.php.
Here is a Demo based on your code that is working fine
I advise you to:
- you test the request status for an error.
- you use setTimeout to plan the next call to newmsgs
That's what i did in the demo.

jQuery - Ajax XMLHttpRequest?

In jQuery you can easily just use their Ajax library. The problem is that I only need it ONE time in my code, so it would not be nessesary to call the whole JavaScript library.
I have this code I have been working on, but I can't seem to get it working. I am trying to start a PHP script by the click of a button. How do I do that?
Here is how far I am right now:
<div onClick="count();">Click!</div>
<script>
function count() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
xhr.open('GET', 'count.php', false);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
while (results.hasChildNodes()) {
results.removeChild(results.lastChild);
}
results.appendChild(document.createTextNode(xhr.responseText));
}
}
xhr.send();
}, false);
}
</script>
And here is the code inside the PHP file:
<?php
mysql_connect("myhost", "username", "password") or die(mysql_error());
mysql_select_db("mydatabase") or die(mysql_error());
mysql_query("INSERT INTO `table` (`field`) VALUES(\'+1\'); ")
or die(mysql_error());
?>
<script>
function count() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
xhr.open('GET', 'count.php', false);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
while (results.hasChildNodes()) {
results.removeChild(results.lastChild);
}
results.appendChild(document.createTextNode(xhr.responseText));
}
}
xhr.send();
}, false); // This Line looks extra. Remove this and try
}
</script>
Very short method.
HTML:
<input type="button" onclick="count()" value="count">
JS:
function count() {
url="yourphp.php";
objX=new XMLHttpRequest();
objX.open("GET",url,false);
objX.send(null);
}

Include js file in Ajax XMLHttpRequest

I'm using Ajax and code which is described below. I want to include .js file in Ajax XMLHttpRequest. Does anybody know how to do that?
For example:
I have code below:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest(id)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "updatesite.admin.php?id="+id, true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('Vsebina').innerHTML = response;
}
When program call function MakeRequest(id) then i want to also executed some .js file.
Is it possible to do that?
You could always put this code in your function to cause a script to be loaded and executed...
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://location-of-script.js";
document.body.appendChild(script);
Here's a complete example. These two files just need to be in the same folder on the server.
This is hello.html:
<html>
<head>
<script type="text/javascript">
function doit()
{
var scr = document.createElement('script');
scr.type = "text/javascript";
scr.src = "hello.js";
document.body.appendChild(scr);
}
</script>
</head>
<body>
<input type="button" value="hello" onclick="doit();">
</body>
</html>
And this is hello.js:
alert("helloooo!!");

AJAX Not Responding

So I'm trying to just alert out my "Hello" from my php file, it's pretty straight forward but it's not working for some reason.
JS
function dynamic()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
window.alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", "hello.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
dynamic();
PHP
<?php
echo "Hello";
?>
HTML
<html>
<head>
<title>Hello</title>
<script src="dynamic.js"></script>
</head>
<body>
test
</body>
</html>
I can't get the alert box to alert my "Hello". It should just come straight from responseText.
You didn't invoke send method. It sends the request MDN
xmlhttp.send();
If you want to put any data in POST put it in send methods parameter as urlencoded form.
xmlhttp.send("foo=bar&hello=world");
try this:
function dynamic()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
window.alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "hello.php", true);
xmlhttp.send(null);
}
dynamic();
I think you forgot to send the request:
xmlhttp.send();
try this
xmlhttp.setRequestHeader("Content-type", "text/plain");
or
xmlhttp.setRequestHeader("Content-type", "text/html");
instead of
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
and you have to put
xmlhttp.send(null);
beside the answer, logging in php file is a useful behaviour in similar situations.

AJAX: sending xmlhttp requests in a loop

I have this function below and I call that function in a loop I get the alert n times but only n-1 or sometimes n-2 responses
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
//document.getElementById("warnings_panel").innerHTML+=xmlhttp.responseText;
}
}
alert("in ajax)
xmlhttp.open("GET","getresponse.php?start="+ start + "&end=" + end,true);
xmlhttp.send();
I have made a class (that you can modify easily) for calling a function in loop and it calls the functions correctly. Maybe this could apply to your need.
(Also if anyone sees something wrong it's good to hear from others)
test.htm
<html>
<head>
<script type="text/javascript">
function myXmlHttp() {
/*constructor simulator*/
this.setPersitent=
function (file, onReadyFunc,params,loop)
{
myXmlHttpObj.loop = loop;
myXmlHttpObj.file=file;
myXmlHttpObj.onReadyFunc='myXmlHttpObj.'+onReadyFunc;
myXmlHttpObj.params=params;
myXmlHttpObj.mySetRequest();
}
this.setParams=
function ( params )
{
myXmlHttpObj.params=params;
}
<!--Standard initial code-->
this.mySetRequest =
function ()
{
request = false;
try { request = new XMLHttpRequest(); }
catch (trymicrosoft) {
try { request = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (othermicrosoft) {
try {request = new ActiveXObject("Microsoft.XMLHTTP");}
catch (failed) {request = false;}/*catch3*/}/*catch2*/}/*catch1*/
if (!request)
alert("Error initializing XMLHttpRequest!");
} /*func*/
this.mySendReq=
function()
{
var url = myXmlHttpObj.file;
request.open("POST", url, true);
//Some http headers must be set along with any POST request.
request.setRequestHeader
("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
request.setRequestHeader("Content-length", myXmlHttpObj.params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = eval(myXmlHttpObj.onReadyFunc);
request.send(myXmlHttpObj.params);
}
this.listenPHP =
function ( ) {
if ( request.readyState == 4) {
if ( request.status == 200)
{
alert(request.responseText);
myXmlHttpObj.loop--;
if(myXmlHttpObj.loop>0)
{
myXmlHttpObj.setParams("js_rand="+Math.random()+"");
myXmlHttpObj.mySendReq();
}
}//inner if
else{alert("status is " + request.status);}
}//outer iff
}//function
}//END
myXmlHttpObj = new myXmlHttp();
myXmlHttpObj.setPersitent
('getresponse.php', 'listenPHP',"js_rand="+Math.random()+"",3) ;
myXmlHttpObj.mySendReq();
</script>
</head>
<body >
</body>
</html>
and getresponse.php
<?PHP
echo 'I recived this random from js:',$_POST['js_rand'],'
this rand is from php:',rand(1,9999);
?>
onreadystatechange gets terminated when your function ends because the xmlhttp object gets removed as it is not a global variable. Am I right?
Better would be to put only the AJAX request in a function, so that the xmlhttp object is only created once (I used a shorter version to create the xmlhttp object in this example).
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
function request() {
xmlhttp.open('GET', 'getresponse.php?start=' + start + '&end=' + end, true);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(null);
}
Generally, this should work, but we need more information about how you actually run that loop to know what might be wrong.
I also added encodeURIComponent and changed the condition inside the callback function, because status isn't always 200 when readyState reaches 4.
function request(start, end) {
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open('GET', 'getresponse.php?start=' + encodeURIComponent(start) + '&end=' + encodeURIComponent(end), true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4)
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
} else {
// status ≠ 200, output useful error message
}
};
xmlhttp.send();
}

Categories