Ajax Issue

7 views
Skip to first unread message

Sanil Music

unread,
Jan 7, 2010, 5:23:12 AM1/7/10
to Prototype & script.aculo.us, music...@gmail.com
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);
});</code>


and this is chat.php file

<?php
$a = htmlspecialchars($_GET['a']);
if(!mysql_connect('localhost','root','pass') || !mysql_select_db
('db')) {


exit();


}
if($a == 'chat_list') {

$query = mysql_query(&quot;SELECT * FROM messages&quot;);
$o = '&lt;ul&gt;';
while($row = mysql_fetch_assoc($query)) {
extract($row);
if(($time - microtime(true)) &lt; 86400) {
$o .= '&lt;li&gt;&lt;b&gt;'.$user.':&lt;/b&gt; '.
$message.'&lt;/li&gt;';
}
}
$o .= '&lt;/ul&gt;';
echo '{\'list\':'.json_encode($o).'}';


} elseif($a == 'chat_post') {

$m = htmlspecialchars($_GET['m']);
$u = 'Guest';
$n = microtime(true);
$query = mysql_query(&quot;INSERT INTO messages(user,message,time)
VALUES ('$u','$m','$n')&quot;);


}
?>
It always outputs me an error, because I have set that it output an
alert if ajaxRequest is not created.

T.J. Crowder

unread,
Jan 11, 2010, 6:56:49 AM1/11/10
to Prototype & script.aculo.us
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

ColinFine

unread,
Jan 11, 2010, 9:58:16 AM1/11/10
to Prototype & script.aculo.us
Also, do you really mean to have &amp; in your querystring?

>     if(!ajaxRequest('/chat.php?a=chat_post&amp;m='+encodeURIComponent

&amp; is HTML escaped. I think you mean & (an unescaped CGI
separator).

Sanil Music

unread,
Jan 12, 2010, 9:34:25 AM1/12/10
to Prototype & script.aculo.us
I use & instead of &amp;, but I don't know why you can't see it here.
For you Cowder, that I wanted a Ajax Request like that, I would use
it. I want something else. As in my code, I want to create a one
function for all ajax requests. So, I just call that function, and in
it I define callback function, url.

david

unread,
Jan 12, 2010, 12:15:04 PM1/12/10
to Prototype & script.aculo.us
Hi Sanil Music,

What TJ (it's not CORWDER) want to explain is that you can't do what
you're trying to do or use the ajax request in synchronous mode .
In execution mode, the JS thread in the browser will execurt the
AJAX.Request, and continue like if nothing was done by this function.
There is just a mechanism inside the browser which get the thread back
on the receveid value. And at that time the defined callback for
ONSUCCESS or ONFAILURE or ... will just be launch with the result as
first parameter.

So you need to split ypour code to handle the behaviour you want.

I think you should re-read TJ response, he gives you the answer.

--
david

Reply all
Reply to author
Forward
0 new messages