Quick AJAX example
Tue, 03/18/2008 - 18:53 — john
zone_default.php:
There are many ways to make the ajax request. This probably isn't the best, but it's the one I am most comfortable using. This example requires that you have the json extension for php. It can be done without it, but json makes the data transfer from php to javascript much cleaner.
testAjax.tpl:
{zoop_file_js files="ajax/dojo/dojo.js"} <form id="main_form" name="main_form" method="POST" action="{$VIRTUAL_URL}" enctype="multipart/form-data"> <script type="text/javascript"> {literal} function submitForm(action) { if(window.verifyFormFunction) { if (!verifyFormFunction(action)) return false; } document.main_form.actionField.value = inAction; document.main_form.onSubmit(); document.main_form.submit(); } function checkUserName() { dojo.io.bind({ {/literal} url: "{$SCRIPT_URL}/checkUserName", {*url: "{$zoneUrl}/checkUserName",*} {literal} mimetype: 'text/json', method: 'post', formNode: document.main_form, handler: function(type, data, e){handleUsernameData(data);} }); } var usernameOk = false; function handleUsernameData(data) { if(data.exists == true) { div = document.getElementById('usernameExists'); div.style.display = ''; } if(data.bad == true) { div = document.getElementById('usernameBad'); div.style.display = ''; } if(data.ok == true) { div = document.getElementById('usernameExists'); div.style.display = 'none'; div = document.getElementById('usernameBad'); div.style.display = 'none'; usernameOk = true; } } function verifyFormFunction(action) { if(action == 'submit' && !usernameOk) { alert('Please enter a valid username.'); return false; } return true; } {/literal} </script> <input type="text" name="username" onBlur="checkUserName();"> <div id="usernameExists" style="color: red; display:none">This username already in use.</div> <div id="usernameBad" style="color: red; display:none">This username is too short, or contains invalid characters.</div><br/> <input type="password" name="password"><br/> <input type="password" name="password2"><br/> <input type="submit" onclick="submitForm('submit'); return false;"> <input type="hidden" name="actionField" value="default"> </form>
zone_default.php:
function pageTestAjax($p) { $this->guiDisplay('testAjax.tpl'); } function postTestAjax($p) { //save the user } function postCheckUserName($p) { $username = getPostText('username'); $answer = array(); if(strlen($username) < 2) $answer['bad'] = true; else $answer['bad'] = false; if(sql_check("select id from user where username = '$username'")) $answer['exists'] = true; else $answer['exists'] = false; $answer['ok'] = !$answer['bad'] && !answer['exists']; echo json_encode($answer); }
- john's blog
- Login or register to post comments

Hi
Good info!!
Header Missing
I also send a header with my JSON data which will help Prototype decode the data automatically. I am not sure it this helps DOJO or not. Just thought I would add this if others needed to know