Need help, AJAX PHP

OlympicDreamer

Senior Member
Joined
Mar 24, 2009
Messages
1,145
Reaction score
0
index.php

<head>
<script type="text/javascript">
function changePost(datetime)
{
var datetime = datetime;
alert(datetime);
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
}
</script>
</head>

<body>
<strong><i><a href="#" onClick="changePost(<?php echo $datetime;?>)">Previous</a></i></strong>
</body>

the script will not acho if I pass the variable $datetime when I call the function. why doesnt it work? I am trying to implement AJAX to call previous and next blog posts.


Working with Ajax, PHP and MySQL - Ajax Tutorials | w3resource
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,301
index.php

<head>
<script type="text/javascript">
function changePost(datetime)
{
var datetime = datetime;
alert(datetime);
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
}
</script>
</head>

<body>
<strong><i><a href="#" onClick="changePost(<?php echo $datetime;?>)">Previous</a></i></strong>
</body>

the script will not acho if I pass the variable $datetime when I call the function. why doesnt it work? I am trying to implement AJAX to call previous and next blog posts.


Working with Ajax, PHP and MySQL - Ajax Tutorials | w3resource

A couple of advices for you.
1) Please put your codes inside CODE or PHP boxes
2) Go and use jQuery, your code is unnecessarily convoluted.
3) What are you doing here ?
Code:
function changePost(datetime) {
  var datetime = datetime;
  ...
4) Your $datetime is a PHP variable, where is it declared and initialised with data ?
 

OlympicDreamer

Senior Member
Joined
Mar 24, 2009
Messages
1,145
Reaction score
0
How do I pass PHP variable into a JavaScript Function?

Code:
onClick="process('previous',<?php echo "'"+$postID+"'";?>"
to

Code:
function process(direction,postID) {
    var direction = direction;
    var postID = postID;
    
    alert(postID);
    if(xmlHttp.readyState==0 || xmlHttp.readystate==4) {//check if server is ready
        try{
            if (direction == 'previous') {
            xmlHttp.open("GET","getpost.php?postID="+postID+"&direction=previous", true);
            } else if (direction == 'next') {
            xmlHttp.open("GET","getpost.php?postID="+postID+"&direction=next", true);
            }
        
            xml.onreadystatechange = handleServerResponse;
            xmlHttp.send(null);
        } catch(e) {
            alert(e.toString());
        }
    } else {
        setTimeout('process()', 1000)
    }
}

Something somewhere is wrong, I have no experience with this.
 
Last edited:

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,301
How do I pass PHP variable into a JavaScript Function?

onClick="process('previous',<?php echo "'"+$postID+"'";?>"

to

function process(direction,postID) {
var direction = direction;
var postID = postID;

alert(postID);
if(xmlHttp.readyState==0 || xmlHttp.readystate==4) {//check if server is ready
try{
if (direction == 'previous') {
xmlHttp.open("GET","getpost.php?postID="+postID+"&direction=previous", true);
} else if (direction == 'next') {
xmlHttp.open("GET","getpost.php?postID="+postID+"&direction=next", true);
}

xml.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch(e) {
alert(e.toString());
}
} else {
setTimeout('process()', 1000)
}
}

Something somewhere is wrong, I have no experience with this.

How many times must I say, put your codes inside the PHP or CODE box. Help yourself by helping others to read your code easier.......

First of all, PHP is a server side script. Javascript uses in your case is a client side script. You don't pass anything from one system to another system in your way. You basically use PHP to write javascript codes that will be interpreted by the javascript vm in the browser.

Below is an example

PHP:
<?php
$date = date("d/m/y");
?>

<script type="text/javascript">
alert("The date today is <?=$date?>.");
</script>

On the server side, executing the php script basically yield javascript codes that looks like the following
PHP:
<script type="text/javascript">
alert("The date today is 24/05/13.");
</script>


PHP:
<?=...?>
is the shortcut for
PHP:
<?php echo ... ?>
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,301
Code:
function process(direction,postID) {
  var direction = direction;
  var postID = postID;

  alert(postID);
  if(xmlHttp.readyState==0 || xmlHttp.readystate==4) {//check if server is ready
    try{
      if (direction == 'previous') {
        xmlHttp.open("GET ","getpost.php?postID="+postID+"&direction=previous", true);
      } else if (direction == 'next') {
        xmlHttp.open("GET","getpost.php?postID="+postID+"&direction=next", true);
      }

      xml.onreadystatechange = handleServerResponse;
      xmlHttp.send(null);
    } catch(e) {
      alert(e.toString());
    }
  } else {
  setTimeout('process()', 1000)
  }
}

I have advice you to use jQuery for your Ajax requirement. Don't use what you are using now because it's not cross browser compatible. Using jQuery or such other framework, your code will be more pleasant looking and robust across browsers.

Code:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
function process(direction, postID) {
  $.get({
    url: "getpost.php",
    data: { postID: postID, direction: direction },
    success : function(data, textStatus, jqXHR) {
      // react to the response upon post request returns.
    }
  });
}
</script>
 
Last edited:

OlympicDreamer

Senior Member
Joined
Mar 24, 2009
Messages
1,145
Reaction score
0
Thanks! it worked!

Sorry about the Code/PHP boxes, still not used to using them.
I will remember to use them next time.
 

OlympicDreamer

Senior Member
Joined
Mar 24, 2009
Messages
1,145
Reaction score
0
Why is my server ready state always at 3, No response at all?
Why does the alert come out so many times?

getpost.js
Code:
function process(direction,$postID) {
    var direction = direction;
    var postID = $postID;
    
    if(xmlHttp.readyState==0 || xmlHttp.readystate==4) {//check if server is ready
        try{
            if (direction == 'previous') {
                xmlHttp.open("GET","getpost.php?postID="+postID+"&direction=previous", true);
            } else if (direction == 'next') {
                xmlHttp.open("GET","getpost.php?postID="+postID+"&direction=next", true);
            }
            xmlHttp.send();
            xmlHttp.onreadystatechange = handleServerResponse;
        } catch(e) {
            alert(e.toString());
        }
    } else {
        setTimeout('process(direction,postID)', 1000)
    }
}

The following code from getpost.js needs focus
Code:
function handleServerResponse() {
    if (xmlHttp.readyState==1) {
//        alert('Connection established');
    } else if (xmlHttp.readyState==2) {
//        alert('Request received');
    } else if (xmlHttp.readyState==3) {
        alert('Processing request');
    } else if(xmlHttp.readystate==4) {
        alert('Ready');
        if(xmlHttp.status==200) {//200 means no error
            xmlResponse = xmlHttp.responseXML;
            xmlDocumentElement = xmlResponse.documentElement;
            message = xmlDocumentElement.firstChild.data;
            document.getElementById("journalcontent").innerHTML = '<span style="color:blue">'+ message + '</span>';
            
            setTimeout('process()',1000);
            
        } else {
            alert(xmlHttp.statusText);
        }
    }
}

getpost.php
Code:
include'connectDatabase.php';

header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';

echo '<response>';
$direction = $_GET['direction'];
$postID = $_GET['postID'];

if ($direction == 'previous') {
    $sql1 = "SELECT * FROM journal WHERE accountID = '1' AND privacyID = '0' and journalID < " . $postID . " ORDER BY datetime DESC LIMIT 1";
} else if ($direction == 'next') {
    $sql1 = "SELECT * FROM journal WHERE accountID = '1' AND privacyID = '0' and journalID > " . $postID . " ORDER BY datetime DESC LIMIT 1";
}

$result1 = executeSelectQuery($sql1);
echo $result1[0][0];
echo $result1[0][1];
echo $result1[0][2];
echo $result1[0][3];
echo $result1[0][4];
echo '</response>';

Click on Journal then click Previous
 
Last edited:

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,301
Why is my server ready state always at 3? No response at all?

getpost.js
Code:
function process(direction,$postID) {
...
}

The following code from getpost.js has ERROR
Code:
function handleServerResponse() {
...
}

Is there any compelling reason for you to use the XMLHttp object directly ? Why you are making your own development complicated and tedious when ajax framework exist to help you lighten on these intricacies ?

Please go and use the jQuery api to shift your focus on your web application first. Revisit on the innards of low level ajax stuffs later.

getpost.php
Code:
include'connectDatabase.php';

header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';

echo '<response>';
$direction = $_GET['direction'];
$postID = $_GET['postID'];

if ($direction == 'previous') {
    $sql1 = "SELECT * FROM journal WHERE accountID = '1' AND privacyID = '0' and journalID < " . $postID . " ORDER BY datetime DESC LIMIT 1";
} else if ($direction == 'next') {
    $sql1 = "SELECT * FROM journal WHERE accountID = '1' AND privacyID = '0' and journalID > " . $postID . " ORDER BY datetime DESC LIMIT 1";
}

$result1 = executeSelectQuery($sql1);
echo $result1[0][0];
echo $result1[0][1];
echo $result1[0][2];
echo $result1[0][3];
echo $result1[0][4];
echo '</response>';

http://darrendaantonio.dyn-o-saur.com:50000/darrenda/getpost.php?postID=4&direction=previous

http://darrendaantonio.dyn-o-saur.com:50000/darrenda/getpost.php?postID=5&direction=previous

Demo @ http://darrendaantonio.dyn-o-saur.com:50000/darrenda/#
Click on Journal then click Previous

The way you are handling database query is highly insecure. The main loophole is SQL injection.

Never attempt to have tainted inputs with SQL statement in this manner.

If I access your getpost.php script using
/getpostphp?postID=0%3BDROP%20TABLE%20journal%3B%23

and you will be screwed immediately.

"0%3BDROP%20TABLE%20journal%3B%23"
is equal to
0;DROP TABLE journal;#

Basically your SQL statement becomes
"SELECT * FROM journal WHERE accountID = '1' AND privacyID = '0' and journalID > 0;DROP TABLE journal;# ORDER BY datetime DESC LIMIT 1";

The least you should be doing is apply mysqli_real_escape_string on your SQL variables.

But the CORRECT approach is use SQL binding instead. Binding is semantics enforcement instead of syntax enforcement by escaping SQL syntax.

Go use the PDO.

Construct your SQL statement as

$stmt = $dbh->prepare("SELECT * FROM journal WHERE accountID = '1' AND privacyID = '0' and journalID < ? ORDER BY datetime DESC LIMIT 1");

Bind using

$stmt->bindParam(1, $postID);

Read up more from PHP: PDO - Manual

I already gave you the right approach to your problems, go change the way you are coding today.
 

OlympicDreamer

Senior Member
Joined
Mar 24, 2009
Messages
1,145
Reaction score
0
Is there any compelling reason for you to use the XMLHttp object directly ? Why you are making your own development complicated and tedious when ajax framework exist to help you lighten on these intricacies ?

Please go and use the jQuery api to shift your focus on your web application first. Revisit on the innards of low level ajax stuffs later.



The way you are handling database query is highly insecure. The main loophole is SQL injection.

Never attempt to have tainted inputs with SQL statement in this manner.

If I access your getpost.php script using
/getpostphp?postID=0%3BDROP%20TABLE%20journal%3B%23

and you will be screwed immediately.

"0%3BDROP%20TABLE%20journal%3B%23"
is equal to
0;DROP TABLE journal;#

Basically your SQL statement becomes
"SELECT * FROM journal WHERE accountID = '1' AND privacyID = '0' and journalID > 0;DROP TABLE journal;# ORDER BY datetime DESC LIMIT 1";

The least you should be doing is apply mysqli_real_escape_string on your SQL variables.

But the CORRECT approach is use SQL binding instead. Binding is semantics enforcement instead of syntax enforcement by escaping SQL syntax.

Go use the PDO.

Construct your SQL statement as

$stmt = $dbh->prepare("SELECT * FROM journal WHERE accountID = '1' AND privacyID = '0' and journalID < ? ORDER BY datetime DESC LIMIT 1");

Bind using

$stmt->bindParam(1, $postID);

Read up more from PHP: PDO - Manual

I already gave you the right approach to your problems, go change the way you are coding today.

Thanks, I was following a tutorial from youtube for Ajax programming. User TheNewBoston.

I am already fixing the codes that are prone to sql injection, it's a bad habit of mine to do that after I finish the code. Will change that from now on.

Thanks!
 
Last edited:

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,301
Thanks, I was following a tutorial from youtube for Ajax programming. User TheNewBoston.

Apparently that is a lousy developer tutorial. Please don't follow it. I'm now teaching you the right approach.

3 main things

1) Go use jQuery
2) Use PHP PDO
3) Go use a template engine like www.smarty.net/. Please do not write spaghetti php codes!
 

OlympicDreamer

Senior Member
Joined
Mar 24, 2009
Messages
1,145
Reaction score
0
Apparently that is a lousy developer tutorial. Please don't follow it. I'm now teaching you the right approach.

3 main things

1) Go use jQuery
2) Use PHP PDO
3) Go use a template engine like www.smarty.net/. Please do not write spaghetti php codes!

ok, thank you!

btw, isit necessary to do the floowing when printing php variables?

Code:
print $the_d = mysql_real_escape_string($_POST['d']);// see if the scripts are working fine until here, if so, then see below.
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,301
ok, thank you!

btw, isit necessary to do the floowing when printing php variables?

Code:
print $the_d = mysql_real_escape_string($_POST['d']);// see if the scripts are working fine until here, if so, then see below.

Don't understand what you mean by flowing
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,301
ok, thank you!

btw, isit necessary to do the floowing when printing php variables?

Code:
print $the_d = mysql_real_escape_string($_POST['d']);// see if the scripts are working fine until here, if so, then see below.

mysql_real_escape_string is for sql purpose, nothing to do with printing.

You can always print to the STDERR using error_log, it will show up in the php_errors.log or your web server error logfiles.

At times, when I'm trying to do debugging. I also print to the HTML page without affecting the layout using HTML comments, or javascript comments. There are some lazy ways and some official standard ways. Just make sure you don't litter them all over the place. Just for temporary debugging is fine.
 
Important Forum Advisory Note
This forum is moderated by volunteer moderators who will react only to members' feedback on posts. Moderators are not employees or representatives of HWZ Forums. Forum members and moderators are responsible for their own posts. Please refer to our Community Guidelines and Standards and Terms and Conditions for more information.
Top