Hi,
There are several issues with that JavaScript code (I can't comment on
the PHP). Two of the main issues:
* You're checking the return value from a function (`ajaxRequest`)
that you never return a value from. That means that the value you're
checking is `undefined`, which is falsey, and so the condition `!
ajaxRequest(...)` will always be true -- hence your seeing error
alerts. It has nothing to do with the ajax request, which is still
processing at that point (they're asynchronous by default, which is a
good thing).
* You're treating the ajax request as though it were synchronous. You
_can't_ return a value from your `ajaxRequest` function indicating
whether the request was successful, since the request is asynchronous
(the `ajaxRequest` function returns before the ajax call completes; it
returns immediately having *started* the request). Although you could
make the ajax requests synchronous using a flag, doing so a very bad
idea. Instead, you need to update your logic so that the next thing
you want to do after the ajax request is done by the `onSuccess` and
`onFailure` callbacks you pass into the request, not code following
the `ajaxRequest` call. This is a fundamental change in approach that
tends to throw a newcomer to it initially, but people soon get the
hang of it.
Basically, this requires a small change to your code layout. Where
before you might have had:
function someNiftyThing() {
if (doAjaxRequest(url, { /* ... */ })) {
// The call worked
doSomethingUseful();
doSomethingElseCool();
}
else {
// The call failed
showFailureMessage();
doSomethingToRecover();
}
}
...in this new approach you'd have something like:
function someNiftyThing() {
new Ajax.Request(url, {
onSuccess: handleSuccess,
onFailure: handleFailure
});
}
function handleSuccess(response) {
// The call worked
doSomethingUseful();
doSomethingElseCool();
}
function handleFailure(response) {
// The call failed
showFailureMessage();
doSomethingToRecover();
}
The `someNiftyThing` function *starts* the process and returns
immediately. When the ajax request completes at some point in the
future, either the `handleSuccess` or `handleFailure` callback gets
triggered and completes the processing. (The code above is
simplified; for more details on bulletproof ajax request with
Prototype, check out this article[1] on the unofficial wiki.)
I've used named functions there at the same scope as the
`someNiftyThing` function, but you can also make them closures within
`someNiftyThing` if that's more appropriate for what you're doing. If
so, though, beware the memory overhead when dealing with JavaScript
implementations that don't do garbage collection effectively, and only
do it when necessary.
[1] http://proto-scripty.wikidot.com/prototype:how-to-bulletproof-ajax-requests
HTH,
--
T.J. Crowder
Independent Software Consultant
tj / crowder software / com
www.crowdersoftware.com
On Jan 7, 10:23 am, Sanil Music wrote:
> Below is code I am using and it's not working. As you can see in code,
> I have coded it to display alert if there is issue with ajax, and
> every time I run script I got error.
>
> var c = new Array();
> function ajaxRequest(loc,callback) {
> new Ajax.Request(loc, {
> method: 'post',
> onSuccess: callback});
> }
>
> function chat(type,e) {
> if(type == 'submit') {
> if(!ajaxRequest('/chat.php?a=chat_post&m='+encodeURIComponent
> (e.value),'')) {
> alert('Cannot post your message!');
> }
> e.value = '';
> e.focus();} else if(type == 'receive') {
>
> if(!ajaxRequest('/chat.php?a=chat_list','rec_content')) {
> alert('Cannot receive messages list!');
> clearInterval(cs);
> }}
> }
>
> function rec_content(o) {
> if(o.list) {
> if(c[1] != o.list) {
> c[1] = o.list;
> $('#chatwindow').update(o.list);
> }}
> }
>
> Event.observe(window,'load',function() {
> cs = setInterval("chat('receive','#chatwindow')",1000);
>
> });
>
> and this is chat.php file
>
> $a = htmlspecialchars($_GET['a']);
> if(!mysql_connect('localhost','root','pass') || !mysql_select_db
> ('db')) {
>
> exit();
>
> }
>
> if($a == 'chat_list') {
>
> $query = mysql_query("SELECT * FROM messages");
> $o = '
';
> while($row = mysql_fetch_assoc($query)) {
> extract($row);
> if(($time - microtime(true)) < 86400) {
> $o .= '- '.$user.': '.
> $message.'
';
> }}
>
> $o .= '
';
> echo '{\'list\':'.json_encode($o).'}';
>
> } elseif($a == 'chat_post') {
>
> $m = htmlspecialchars($_GET['m']);
> $u = 'Guest';
> $n = microtime(true);
> $query = mysql_query("INSERT INTO messages(user,message,time)
> VALUES ('$u','$m','$n')");
>
> }
>
> ?>
> It always outputs me an error, because I have set that it output an
> alert if ajaxRequest