Jump to content

Help with AJAX, Post, and PHP


Dan06

Recommended Posts

I'm trying to learn AJAX. I've gone through a few tutorials and books, and I want to practice/implement what I've learned. To that end, I created a simple php file that connects to a MySQL database and displays the stored content (which is made up superheros). I'm now trying to use AJAX techniques to have the content displayed when a button is clicked. I've put together some code, but am confused/lost as to what I should do next to make the code work. If anyone can tell me what I've done right, wrong, and the next steps it would be appreciated. Below is the code so far:

 

<html>
<head>
<title>Heros!</title>
<script type="text/javascript" src="ajaxgold.js"></script>
<script language="javascript">

function getData(dataSource){
var XMLHttpRequestObject = false;

if (window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHttp");
}

if(XMLHttpRequestObject){
XMLHttpRequestObject.open("POST", url, true);
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

XMLHttpRequestObject.onreadystatechange = function(){
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
	callback(XMLHttpRequestObject.responseText);
	delete XMLHttpRequestObject;
	XMLHttpRequestObject = null;
	}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>

<center><h1>Heros!</h1></center>
<body>
<center> <input type="button" name="viewHeros" id="viewHeros" value="View Heros" onClick="getData()"> </center>
<script language = "php">

//make db connection
$conn = mysql_connect("localhost", "username", "password");

if (!$conn){
  print "Unable to connect to the database";
  exit();
}

mysql_select_db("database", $conn);

//create query
$sql = "SELECT * FROM heroinfo";
$result = mysql_query($sql, $conn);

print "<center><table border = 1> \n";

//get field names
print "<tr>\n";
while ($field = mysql_fetch_field($result)){
  print " <th>$field->name</th>\n";
} //end while

//get row data
while ($row = mysql_fetch_assoc($result)){
  print "<tr>\n";
  //look at each field
  foreach ($row as $col=>$val){
    print " <td>$val</td>\n";
  } //end foreach
  print "<tr>\n\n";
  } //end while

print "</table></center>\n";

</script>
</body>
</html>

Link to comment
Share on other sites

Thanks. I did not know that the php code needed to be in a different file - I thought that since HTML could be in the same file, so could php.

 

As for the dataSource variable - that is where I'm confused. As I understand it, in AJAX when using the GET method and a text file, I would use the dataSource variable to hold the text file name and then use the .responseText method to retrieve the information from the text file. But I don't understand if or how I would use the dataSource variable with the POST method.

Link to comment
Share on other sites

OK, after looking at your code a little closer, you haven't assigned variable "url" a variable. As far as a separate PHP file, I suppose you COULD do it all in one, but you'd have to do some pretty tricky stuff. Your JS code looks a little more complicated than necessary. Remember that this is basically how AJAX works:

[*]HTML code calls a JS function

[*]The JS function calls a PHP file and sometimes passes one or more variables to it. This can ONLY be done using the get method.

[*]The PHP generated code is used. This can either be PHP-generated JS code that is then run with the first JS function (using JS's eval() function), or it is PHP-generated HTML code that is then assigned to an element in the first HTML code (usually assigned to a DIV element using .innerHTML)

Because that second PHP file (the one being called by the JS) outputs the code to be used, you would get duplicate stuff in the output.

Link to comment
Share on other sites

Thanks for the help. I was able to get my code to work. I separated the code in two files and I adjusted the js script by defining the url variable (I set it to the php file) and set document.getElementById("targetDiv").innerHTML = XMLHTTPRequestObject.responseText. By making these changes I was able to get the content to display, as formatted in a table (in the HTML file).

Link to comment
Share on other sites

Remember that this is basically how AJAX works:

[*]HTML code calls a JS function

[*]The JS function calls a PHP file and sometimes passes one or more variables to it. This can ONLY be done using the get method.

[*]The PHP generated code is used. This can either be PHP-generated JS code that is then run with the first JS function (using JS's eval() function), or it is PHP-generated HTML code that is then assigned to an element in the first HTML code (usually assigned to a DIV element using .innerHTML)

Because that second PHP file (the one being called by the JS) outputs the code to be used, you would get duplicate stuff in the output.

A little clarification:

  • Javascript creates a browser XMLHttpRequest or ActiveX object.
  • The object accesses a URL, with out without GET and/or POST data. (Yes, it can be both.) (POST to a something.php?do=1 URL)
  • The page can return XML or plaintext.  The plain text can be anything, such as javascript code to be evaluated once returned to the main page.

 

It's not good practice to make your page an all in one page, but to prevent duplicated data from being displayed you would setup your page to be similar to this:

<?php
if(isset($_GET['do'] && $_GET['do']=='something')){
  //do some stuff
  //output text / xml to return
  die();
}
?>
...
//rest of your code with javascript and what not

This works because the 'AJAX' part of it makes a NEW page request.  As far as the browser is concerned, it's a brand new page (since HTTP is stateless).  And since you would use ajax to call some url like  mypage.php?do=something, it would stop and die() after that if, returning only stuff inside that function.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.