Monday, July 31, 2006

Javascript Prototype Library for AJAX - Synchronous Request

I am a big fan of Prototype library and using it for a while with excellent results for most of my AJAX work.

Most of the time i was making asynchronous request to get the response. Today i was trying to make a synchronous request using the following in my request page







<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script src="./src/js/prototype.js" type="text/javascript" >
</script>
<script language="JavaScript" type="text/javascript" >

function makeRequest() {
var myAjax = new Ajax.Request(
"testResponse.php",
{
method: 'post',
asynchronous: false,
onComplete: displayResponse
});
}

function displayResponse(xmlhttp)
{
alert("Am i coming here ");
xmlhttp = null;
}

</script>

</HEAD>

<BODY>
<table>
<Tr>
<td>
< href='javascript:makeRequest("abc")' >Click me
</a>
</td>
</tr>
</table>

</BODY>
</HTML>



My response page is simple php page echoing some message which is. testResponse.php is as under







<?php

echo "What i am sending from here";

?>



With this request setting for my AJAX call i.e. synchronous request is made with asynchronous request set to false. I am not able to fire onComplete method but when i change asynchronous request to true I am able to fire the function registered for my onComplete event.

Then i started looking in my livehttpheader whether request is getting fired at all or not. You guessed it right, request is not going from javascript.

I was not sure is it a bug in prototype library or I am doing something wrong. Later i found that i was passing parameters incorrectly. I have to change the way i was passing parameter i.e.

asynchronous: 'false'

and VOILA it works!!

So it was my editor which was showing keyword when it typed false without single quote and i have kept it like that :)

2 comments:

Richard said...

thats incorrect. it has to be false without the double quotes.

if you have anything else it will default to true, an asynchonous call.

Dipesh Khakhkhar said...

Did you test it? If yes which version of prototype library did you use? If not can you please test the above mentioned code and tell me the results.