Jump to content

Ajax & PHP: On the same page?


birdbrain24

Recommended Posts

Ok i just started learning ajax and i was wondering if i can have the ajax and the php on the same page?

 

Here's my pages:

register.html

registercheck.php

 

    register.html

<html>
<head>
<title>Register</title>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function checkusername(){
var ajaxRequest;  // The variable that makes Ajax possible!

try{
	// Opera 8.0+, Firefox, Safari
	ajaxRequest = new XMLHttpRequest();
} catch (e){
	// Internet Explorer Browsers
	try{
		ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try{
			ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e){
			// Something went wrong
			alert("Your browser do not support ajax!");
			return false;
		}
	}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
	if(ajaxRequest.readyState == 4){
		var ajaxDisplay = document.getElementById('username_div');
		ajaxDisplay.innerHTML = ajaxRequest.responseText;
	}
}
var username = document.getElementById('username').value;
var query = "?username=" + username;
ajaxRequest.open("GET", "registercheck.php" + query, true);
ajaxRequest.send(null); 
}
//-->
</script>
</head>
<body>
<form>
<table border="1" bordercolor="#000000" cellspacing="0">
  <tr>
    <td>Username:</td>
    <td><input type="text" id="username" onkeyup="checkusername()" /></td>
    <td><div id="username_div">Username Status!</div></td>
  </tr>
</table>
</form>
</body>
</html>

 

    registercheck.php

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "race";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
//Set variables
$username = $_GET['username'];
//Mysql Variables
$result_query = mysql_query("SELECT * FROM `users` WHERE `username`='$username'") or die(mysql_error());
$result_num_rows = mysql_num_rows($result_query);

  if(isset($username)):
  
    if($result_num_rows == 0):

    echo '<font color="green"><strong>Username avaliable!</strong></font>';

    elseif($result_num_rows != 0):

    echo '<font color="red"><strong>Username unavaliable!</strong></font>';

    endif;

  endif;
?>

 

I hope someone could help! Thanks anyways!

Link to comment
Share on other sites

i want to do something like this?

 

<html>
<head>
<title>Register</title>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function checkusername(){
var ajaxRequest;  // The variable that makes Ajax possible!

try{
	// Opera 8.0+, Firefox, Safari
	ajaxRequest = new XMLHttpRequest();
} catch (e){
	// Internet Explorer Browsers
	try{
		ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try{
			ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e){
			// Something went wrong
			alert("Your browser do not support ajax!");
			return false;
		}
	}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
	if(ajaxRequest.readyState == 4){
		var ajaxDisplay = document.getElementById('username_div');
		ajaxDisplay.innerHTML = ajaxRequest.responseText;
	}
}
var username = document.getElementById('username').value;
var query = "?username=" + username;
ajaxRequest.open("GET", "register.php" + query, true);
ajaxRequest.send(null); 
}
//-->
</script>
</head>
<body>
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "race";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
//Set variables
$username = $_GET['username'];
//Mysql Variables
$result_query = mysql_query("SELECT * FROM `users` WHERE `username`='$username'") or die(mysql_error());
$result_num_rows = mysql_num_rows($result_query);

  if(isset($username)):
  
    if($result_num_rows == 0):

    echo '<font color="green"><strong>Username avaliable!</strong></font>';

    elseif($result_num_rows != 0):

    echo '<font color="red"><strong>Username unavaliable!</strong></font>';

    endif;

  endif;
?>
<form>
<table border="1" bordercolor="#000000" cellspacing="0">
  <tr>
    <td>Username:</td>
    <td><input type="text" id="username" onkeyup="checkusername()" /></td>
    <td><div id="username_div">Username Status!</div></td>
  </tr>
</table>
</form>
</body>
</html>

Link to comment
Share on other sites

Yes you can do that. A little explanation of what PHP and javascript are will probably help you understand it a little better:

 

PHP is basically a script that takes in a bunch of factors (users input, dates, times, database info etc) runs it through a code, and outputs text. It can really output any text, but is mostly used for outputting (x)html. PHP runs entirely on the server. The user does some stuff on his machine, clicks submit (or links to a php page) and by doing that sends information to the server. This information is part of what the php script uses (or in some scripts, it wont use any information sent by the user). But all PHP is run on the server, and not at all on the computer that the person is viewing the page on. After it has outputted text, it sends it back to the computer that called it. Since it is usually (x)html that is outputted, and usually a browser that is reading it, it becomes a website.

 

Javascript is a script that also takes in a bunch of factors and runs it through a script. It however doesn't only output text but does a bunch of other things (such as sending out the XMLHttpRequest object that javascript is based off). But the main key here is that javascript is run on the computer of the person who is viewing the site. It is not run on the server side at all, and all processing takes place on the user's computer.

 

But in order for javascript to get to the user's computer, it has to be sent to the browser. In classic non-dynamic (x)html it is saved in the head of the document. The document is then saved on the server. When the user accesses a page, it sends the document to the browser, and the javascript in the head is executed on the user's computer. When thought of it in this way, php can do the exact same thing - it can output text that is actually javascript in the head of your document, and send that document to your browser, where the javascript (ajax) is executed. You can even include php variables in the javascript, so that the javascript will be dynamic. Since php outputs before sending the document to the browser, this is no problem. What you cant do is use javascript variables IN php. Javascript is executed in the browser, and has no interaction with php directly, which is why it doesn't work this way. AJAX sometimes plays around with this, but in its purest sense, you cant use javascript variables in php, you can only use php variables in javascript.

 

Finally, my last point is that you should keep all your javascript in an external file and just link to it in the head of your document using this code:

 

<script type="text/javascript" src="path/to/document.js"></script>

 

You can use php to output this line of code. (x)html, CSS and Javascript should all be kept in separate files, and using the above code will achieve this goal.

 

Good luck!

Link to comment
Share on other sites

javascript and php can be on the same page, it's done all the time!  The thing to understand is that those 2 languages execute at 2 different times. 

 

First, the page is parsed for php, and php only, on the server side. Next that php is executed and the results of that execution are inserted into the html text stream being sent to the browser.  No javascript will be executed server side. Any javascript code found by the php interpreter server side will be treated exactly the same as it treats html code, it will just send it down to the browser unchanged.

 

if you want, you can execute php code right inside of javascript!  You might want to do that in order to initialize your javascript dhtml interface with values retrieved from some server resource:

 

<script type="text/javascript">
    var myname = "<?php echo $myname; ?>";
    var starting_score = <?php echo $mystarting_score; ?>;
</script> 

the thing to understand about the code above is that the php code is found and executed on the server side but none of the javascript is executed on the server side.  When the browser recieves the code above, it will look something like this:

<script type="text/javascript">
    var myname = "mainewoods";
    var starting_score = 1,200;
</script> 

 

when that code arrives to the browser, the browser will execute the javascript and create the variables and assign the values as shown.  The browser recieves no php, the php has all been  executed by then and the browser only recieves the results of the php execution.

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.