Validating with Ajax - php

I wrote some ajax code that sends values to a php file for validation but I have a problem with it. This is my ajax code:
<html>
<body>
<style>
#displayDiv{
background-color: #ffeeaa;
width: 200;
}
</style>
<script type="text/javascript">
function ajaxFunction(str)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById("displayDiv").innerHTML=httpxml.responseText;
}
}
var url="username_exists.php?username=";
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<input type="text"
onkeyup="ajaxFunction(this.value);" name="username" /><div id="displayDiv"></div>
</body>
</html>
and the above code send values to username_exists.php :
<?php
$username = trim($_REQUEST['username']);
if (usernameExists($username)) {
echo '<span style="color:red";>Username Taken</span>';
}
else {
echo '<span style="color:green;">Username Available</span>';
}
function usernameExists($input) {
// in production use we would look up the username in
// our database, but for this example, we'll just check
// to see if its in an array of preset usernames.
$name_array = array ('k','steve', 'jon', 'george', 'admin');
if (in_array($input, $name_array)) {
return true;
}
else {
return false;
}
}
?>
My problem is that when any username is put in the textbox returns "Username Available"! What did I do wrong?

You are sending an empty string as username to check thru your ajax call.
var url="username_exists.php?username=";
I would suggest you to start using jQuery to help you in handling this case.You don't need to worry about the cross browser issue and you dont need to write all these lines of code.
jQuery is a wonderful javascript library. http://www.jquery.com
Include jquery library (i will use the CDN Version) in your head section of HTML document and change your code like this.
HTML
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id=txtUserName" />
</body>
javascript
$("#txtUserName").keyUp(function(){
if($("#txtUserName").val()!="")
{
$.ajax({
url: 'username_exist.php?username'+$("#txtUserName").val(),
success: function(data) {
alert(data);
}
});
}
}

Related

php echod JavaScript won't run?

I have a problem where when I echo JavaScript from a PHP page to a HTML page using AJAX it won't run however, when I Inspect Element the JavaScript is there, I also echo some text and the text does show.
When I add the JavaScript manually in the HTML it works perfectly and the PHP, HTML and AJAX files are all in the same directory so there is no problem there.
I have 3 pages index.html, boo.php and ajax.js
index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/jquery.gritter.css" />
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('jquery', '1.7.1');</script>
<script type="text/javascript" src="js/jquery.gritter.js"></script>
<script src="ajax.js"></script>
</head>
<body>
<script type="text/javascript"><!--
refreshdiv();
// --></script>
<div id="timediv"></div>
</body>
</html>
boo.php
<?php
// Fetch the data
$query = "SELECT * FROM $tablename";
$result = mysql_query($query);
// Return the results, loop through them and echo
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$name = $row['name']; // this equals Admin
if($name == 'Admin') {
echo $name; // this echos Admin and shows on index.html
// the javascript below doesnt
echo "
<script type='text/javascript'>
$(function(){
$(document).ready( function () {
var unique_id = $.gritter.add({
title: 'title text',
text: 'description text',
image: 'icon.jpg',
sticky: true,
time: '',
class_name: 'my-sticky-class'
});
return false;
});
});
</script>
";
}
}
?>
ajax.js
// Customise those settings
var seconds = 5;
var divid = "timediv";
var url = "boo.php";
////////////////////////////////
//
// Refreshing the DIV
//
////////////////////////////////
function refreshdiv(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Timestamp for preventing IE caching the GET request
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// Start the refreshing process
var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}
What the script is suppose to do check every 5 seconds if there is if there is a username in the database called Admin then show a gritter notification if there is.
Any ideas what I can do? thanks.
reverse your string notation on the second echo statement that doesn't work.
change double quote to a single qoute like this
echo "<script type='text/javascript'>
...more stuff...
title: 'title text',
...more stufff...
";
to
echo '<script type="text/javascript">
...more stuff..
title: "title text",
...more stuff...
';
why this works is because double quotes will look for variables inside the string and single quotes doesn't. so when you have $(document) this inside of the double quote php thinks its a var
EDIT: since the echo statement is working
the use of innerHTML method doesn't evaluate scripts it only evaluates html tags.
so if you want the response to evaluate the in coming echo statement use the jQuery function append()
that being said change
document.getElementById(divid).innerHTML=xmlHttp.responseText;
to
$('#divid').append(xmlHttp.responseText);

Refresh PHP Page using ajax

I have a php page that needs to be refreshed every 5 secs. On embedding the ajax file, I don't find the updates taking place in Firebug. Here is the skeleton of the code:
**notification.php**
<?php
....
....
?>
<html>
<head>
<script src="./refresh.js"></script>
<script type="text/javascript">
refreshContents();
</script>
</head>
<body>
....
<div id="identifier">
<p>Waiting area</p>
</div>
</body>
</html>
**refresh.js**
var seconds = 5;
var content = "identifier";
var url = "notification.php";
function refreshContents()
{
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(f)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(g)
{
alert("Browser not supports Ajax");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState == 4)
{
document.getElementById(content).innerHTML = xmlHttp.responseText;
setTimeout('refreshContents()', seconds*1000);
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
var seconds = 5;
window.onload = function startrefresh(){
setTimeout('refreshContents()', seconds*1000);
}
Though it may not be the ideal solution, jQuery has a pretty simple way of implementing exactly this:
$(document).ready(function () {
function reload() {
$("#content").load("notification.php");
}
setTimeOut(reload, seconds*1000)
}
I'm not sure that will work perfectly, haven't done it in a little while, but its a much more elegant solution I do believe.
Why not just put a <meta http-equiv="refresh" content="5"> tag into your <head>? It will refresh the page every 5 seconds without the need for any javascript.
see the following example :
<html>
<head>
<title>Refresh a page in jQuery</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
<button id="PageRefresh">Refresh a Page in jQuery</button>
<script type="text/javascript">
$('#PageRefresh').click(function() {
location.reload();
});
</script>
</body>
</html>
this code definetly help you.
or we can use -
<meta http-equiv="refresh" content="5">

How to submit a form in a page which is being accessed by AJAX?

I am trying to figure out how to submit a form in a page being accessed by AJAX?
Here are some code snippets to help demonstrate what I am trying to say.
HTML BODY - THIS IS WHAT THE USER WILL SEE:
<html>
<head>
<script language="javascript" src="linktoajaxfile.js">
</head>
<body onLoad="gotoPage(0)">
<div id="fillThis">
</div>
</body>
</html>
Ajax file:
var xmlhttp
function gotoPage(phase)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="pageofstuffce.php";
url=url+"?stg="+phase;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("fillThis").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
PAGE OF DATA:
<?php
$stage = $_GET['stg'];
if($stage == 0)
{
echo '<a onClick="gotoPage(1)">click me</a>';
}
elseif($stage == 1)
{
<form>
<input type="text" name="name">
<input type="submit" name="submit">
</form>
}
elseif(somehow can reach here)
{
show data from form.
}
?>
How to get past the form and display the data in the same page?
I have tried submitting the form to itself (same file) and that destroyed the AJAX link, and opened the page. I have also tried just having the button move the page onto another step, but the $_POST variable is empty.
hey u can go through this link
http://www.ajaxlines.com/ajax/stuff/article/how_to_submit_a_form_with_ajax_in_jquery.php
let me know if any issues regarding this
I think there's a bug in your code. You are not setting the stage variable anywhere.
Look at:
url=url+"?stg="+phase;
Probably you'll have to change stg => stage.
Don't see any other issue with it.
Hi for displaying the result or form in the same page u can use
form method ="POST" action =
or if u want to use ajax then write one function in jquery something like this
function call() {
$.ajax({
type:'POST',
url:'path to same file name?action=submit',
// data u want to pass
data:',
success:function() {
}
});
}//function ends
and ur php code
check if $_GET['action'] is there then execute ur function
Thanks
Here are the scripts that you are looking for.
pageofstuffce.php
<?php
$stage = $_GET['stg'];
if($stage == 0)
{
echo '<a onClick="gotoPage(1)">click me</a>';
}
elseif($stage == 1)
{
echo '<form>
<input type="text" name="name">
<input type="submit" name="submit">
</form>';
}
else
{
echo 'show data from form.';
}
?>
Your HTML
<html>
<head>
<script type="text/javascript" language="javascript" src="linktoajaxfile.js"></script>
</head>
<body onload="gotoPage(0)">
<div id="fillThis">
</div>
</body>
</html>
Javascript for making Ajax Calls linktoajaxfile.js
var xmlhttp
function gotoPage(phase)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="pageofstuffce.php";
url=url+"?stg="+phase;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("fillThis").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
Hope this will Help!
Thanks!
Hussain.

PHP return empty json string?

My html page sends an ajax request (POST) to PHP, PHP echo a json object.
Code has been tested and worked fine at my development view.
However, after they are uploaded to a VPS hosting server, the returned json string is empty (I used alert() at the response function to display the responseText and found out it was empty).
any idea about the problem?
I am new here. I have not figured out how to add a comment. (Please let me know.)
I changed the PHP code to return a string, it worked. so the problem is after json encoding.
new test.php (worked).
if(!isset($_POST['A'])||!isset($_POST['B']))
{
echo "Failed";
}
else
{
echo "OK";
}
HTML:
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
var NORMAL_STATE = 4;
function ajax_create_http()
{
var xmlHttp = 0;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return 0;
}
}
}
return xmlHttp;
}
var http_req_inst = ajax_create_http();
function sendHttpRequest(params)
{
if( !http_req_inst ) return;
http_req_inst.open('POST', 'test.php', true);
http_req_inst.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_req_inst.onreadystatechange = handleHttpResponse;
http_req_inst.send(params);
alert("Request sent");
}
function handleHttpResponse()
{
if( !http_req_inst ) return;
if (http_req_inst.readyState == NORMAL_STATE)
{
alert(http_req_inst.responseText);
}
}
</script>
</head>
<body>
<div>
<input type="button" value="click" onclick="sendHttpRequest('A=a&B=b')"/>
</div>
</body>
</html>
PHP:
<?php
if(!isset($_POST['A'])||!isset($_POST['B']))
{
$rc = 1;
$arr = array ('rc'=>(integer)$rc,'msg'=>'Testing failed.');
echo json_encode($arr);
}
else
{
$rc = 0;
$arr = array ('rc'=>(integer)$rc,'msg'=>'Testing passed.');
echo json_encode($arr);
}
?>
When I tested, the responseText is empty.
Just check the php configuration on both machines. Like on my machine $text will work on my provider I have to write like $_GET['text'] due to security settings. The PHP configuration will give you an idea of what's wrong, or what packages need to be installed.

Unable to call javascript from PHP

On the click of a button this Javascript is called:
var xmlhttp;
function register()
{
xmlhttp=GetXmlHttpObject();
alert("pass");
if(xmlhttp==null)
{
alert("Your browser does not support AJAX!");
return;
}
var url="register.php";
url=url+"?id="+uniqueid+"&name="+name+"&passwrd="+passwrd1+"&email="+email;
xmlhttp.onreadystatechange=statechanged;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function statechanged()
{
//alert("statechanged function");
if(xmlhttp.readyState==4)
{
//alert(xmlhttp.responseText);
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function testing()
{
document.getElementById("mainbody").innerHTML="This is my first JavaScript!";
}
And then this PHP script is called:
<?php
echo "<script type=\"text/javascript\">testing();</script>";
?>
The HTML has two DIV tags with IDs of mainbody and response:
<HTML>
<HEAD>
<SCRIPT SRC=javascriptname.js></SCRIPT>
</HEAD>
<BODY>
<DIV ID=mainbody>
<DIV ID=response>
</DIV>
</DIV>
</BODY>
</HTML>
I am unable to call the javascript from my php.
If anyone know what I am doing wrong or has an idea what I should do, it will be very helpful.
I don't think changing the innerHTML of an object and inserting a script will cause it to fire. I certainly wouldn't want to depend on that behavior.
Why not just do some kind of string comparison on the responseText, (in a case statement, for example) and then call the appropriate function?
EDIT: You could also remove the script tags, and call eval on the responseText, but eval is not the nicest function in the world.
I've successfully done this by passing the script tags within the string
Example:
<?php
function outputResults($var1)
{
$jsStringOut = "
<script type='text/javascript'>
document.write('".$var1."');
</script>
";
return $jsStringOut;
}
echo outputResults("Hello Stackers");
?>

Categories