Page 1 of 1

ajax/php question

Posted: Sat Dec 02, 2006 6:36 pm
by giarkcom
ok i did not know where to put this so dont get mad at me if i put it in the wrong place---mods move this if it is in the wrong place

i am making a site and need a posting thingy
here is the posting form page:

Code: Select all

<?php include('pre.php'); ?>
<script src="mysql/edit/ajax.js"></script>

<div id="breadcrum">Home > NewsPost</div>
			<h1>NewsPost</h1>
			
			<div class="content">
				
				<h2>NewsPost</h2>
				<p><div id="output"><form action="" method="post" name="happy">
				Category:<select name="cat">
<option value="1">Home Page</option>
<option value="2">Halo 2</option>
<option value="3">Halo PC</option>
</select>
<br>
				Title:<input type="text" name="title">
				<br>
				<table><tr><td>Body:</td><td><textarea name="body" rows=5 cols=20>your post goes here</textarea></td></tr></table>
				<br>
				<input type="button" value="post" onclick="javascript:sndReq(this.form)">
				</form>
				</div>
				</p>
			</div>
			<?php include('end.php'); ?>
here is the ajax.js:

Code: Select all

function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

var http = createRequestObject();

function sndReq(form) {
    http.open('get', 'addpost.php?title='+form.title.value+'&body='+form.body.value+'&cat='+form.cat.value);
    http.onreadystatechange = handleResponse;
    http.send(null);
}

function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();

        if(response.indexOf('|' != -1)) {
            update = response.split('|');
						document.getElementById(update[0]).innerHTML = '';
            document.getElementById(update[0]).innerHTML = update[1];
        }
    }
}
and the processing page

Code: Select all

<?php include('prelogin.php');
//processing

@extract($_REQUEST);
$username = ( $userdata['user_id'] != ANONYMOUS ) ? $userdata['username'] : '';
if($userdata['session_logged_in']){
//its all good in the hood!!
$database='ffleag00_thg';
include('connect.php');
$sql="INSERT INTO newspost (id, user, title, body, cat) VALUES ('', '$username', '$title', '$body', ".$cat.")";
mysql_query($sql);
mysql_close();
echo 'output|success';
} else {
echo 'output|error';
}
?>
it does not do anything when i click post

Posted: Sat Dec 02, 2006 6:52 pm
by Ollie Saunders
Thank you and well done for making use of the [syntax] tags. On to your problem:

Code: Select all

<input type="button" value="post" onclick="javascript:sndReq(this.form)">
Possibly should be:

Code: Select all

<input type="button" value="post" onclick="sndReq(this.form)">
No sure if that will make a difference tho. Also you have unquoted attributes:

Code: Select all

 rows=5 cols=20>
should be [quote]

Code: Select all

rows="5" cols="20">
Other points I would seriously recommend using a javascript library for your AJAX bit. Stuff using ActiveXObjects alone will only work on IE also you are using the earliest possible version of Microsoft.XMLHTTP. I posted this here before (can't find where so I'll post it again) it does work fine on every browser in common use. You might find better out there though:

Code: Select all

<?php
if (!empty($_POST)) {
    echo "Hi JavaScript, I'm PHP.\n\nThanks for sending me these key value pairs:\n\n";
    // Remove this later, outputting everything in $_POST is a real security hazard
    foreach ($_POST as $k => $v) {
        echo "$k: $v\n";
    }
    exit;
}
?>
<html lang="en">
    <head>
        <title>AJAX Test</title>
<script type="text/javascript"><!--

////////////////////////////////////////////////////////////////////////////////
//
// TOOLKIT (you might want to include this as a separate file)
//

if (typeof XMLHttpRequest == 'undefined' && window.ActiveXObject) {
    function XMLHttpRequest()
    {
        var sPre = 'MSXML2.XMLHTTP';
        var aSigs = [sPre + '.5.0', sPre + '.4.0', sPre + '.3.0', sPre, 'Microsoft.XMLHTTP'];
        for (var i=0; i<aSigs.length; i++) {
            try {
                var oRequest = new ActiveXObject(aSigs[i]);
                return oRequest;
            } catch (oError) {
                // ignore
            }
        }
        throw new Error(Pre + ' is not installed on your system.');
    }
}

var Http = {
    sNoSupport:'Browser does not support HTTP requests',
    sHeaderContentType:'application/x-www-form-urlencoded',
    delay:10,
    getParamFormat:function(sUrl, sName, sValue)
    {
        sUrl += (sUrl.indexOf('?') == -1 ? '?' : '&');
        sUrl += encodeURIComponent(sParamName) + '=' + encodeURIComponent(sParamValue);
        return sUrl;
    },
    postParamFormat:function(sParams, sParamName, sParamValue)
    {
        if (sParams.length > 0) {
            sParams += '&';
        }
        return sParams + encodeURIComponent(sParamName)
               + '=' + encodeURIComponent(sParamValue);
    }
};
if (typeof XMLHttpRequest == 'object' || window.ActiveXObject) {
    Http.get = function(sUrl, fnCallback)
    {
        var oRequest = new XMLHttpRequest();
        oRequest.open('get', sUrl, true);
        oRequest.onreadystatechange = function()
        {
            if (oRequest.readyState == 4) {
                fnCallback(oRequest.responseText);
            }
        }
        // space is supposed to be better than null but if
        // you have problems replace space with null
        oRequest.send(' ');
    }
    Http.post = function(sUrl, fnCallback, sParams)
    {
        var oRequest = new XMLHttpRequest();
        oRequest.open('post', sUrl, true);
        oRequest.setRequestHeader('Content-Type', Http.sHeaderContentType);
        oRequest.onreadystatechange = function()
        {
            if (oRequest.readyState == 4) {
                fnCallback(oRequest.responseText);
            }
        }
        oRequest.send(sParams);
    }
} else if (navigator.javaEnabled() && typeof java != 'undefined' && typeof java.net != 'undefined') {
    Http.get = function(sUrl, fnCallback)
    {
        setTimeout(function ()
        {
            var oUrl = new java.net.URL(sUrl);
            var oStream = oUrl.openStream();
            var oReader = new java.io.BufferedReader(new java.io.InputStreamReader(oStream));
            var sResponseText = '';

            var sLine = oReader.readLine();
            while (sLine != null) {
                sResponseText += sLine + '\n';
                sLine = oReader.readLine();
            }

            oReader.close();
            fnCallback(sResponseText);
        }, Http.delay);
    }
    Http.post = function(sUrl, fnCallback, sParams)
    {
        setTimeout(function ()
        {
            var oUrl = new java.net.URL(sUrl);
            var oConnection = oUrl.openConnection();

            oConnection.setDoInput(true);
            oConnection.setDoOutput(true);
            oConnection.setUseCaches(false);
            oConnection.setRequestProperty('Context-Type', Http.sHeaderContentType)

            var oOutput = new java.io.DataOutputStream(oConnection.getOutputStream());
            oOutput.writeBytes(sParams);
            oOutput.flush();
            oOutput.close();

            var sResponseText = '';
            var oInput = new java.io.DataInputStream(oConnection.getInputStream());
            var sLine = oInput.readLine();

            while (sLine != null) {
                sResponseText += sLine + '\n';
                sLine = oInput.readLine();
            }

            oInput.close();
            fnCallback(sResponseText);
        }, Http.delay);
    }
} else {
    throw new Error(http.sNoSupport);
}

//
// ^ THAT WAS THE TOOLKIT, YOU TOOL
//
//////////////////////////////////////////////////////////////////////////////// 

// EXAMPLE CODE //

var myEvents = {
    onThingerClick:function()
    {
        // Remember these can be tampered with like anything else on the client

        // check this is outputting the correct page
        var requestPage = 'http://<?php echo $_SERVER['HTTP_HOST'], $_SERVER['SCRIPT_NAME']; ?>';
        var sParams = Http.postParamFormat('', 'requestId', 'dbIncrement');
        sParams = Http.postParamFormat(sParams, 'time', '<?php echo time(); ?>');

        document.getElementById('thinger').style.backgroundColor = '#fff';
        Http.post(requestPage, myEvents.onAjaxResponse, sParams);
    },
    onAjaxResponse:function(sResponseText)
    {
        document.getElementById('thinger').style.backgroundColor = '#f90';
        alert(sResponseText); // this'll tell you if it worked.
    }
}


</script>
    <style type="text/css">
    div#thinger {
        position:absolute;
        top:100px; left:100px;
        background-color:#f90;
        border:solid #000 1px;
        width:100px; height:100px;
    }
    </style>
    </head>
    <body>
        Click the thinger:
        <div id="thinger" onclick="myEvents.onThingerClick(); return false">
            I'm the thinger
        </div>
    </body>
</html>

Posted: Sat Dec 02, 2006 7:20 pm
by giarkcom
um......yeh......very confusing code.....thanx for the help though