use of ajax in django problem with the code - ajax

I am new to ajax and using Django for web development.
Now My Template contains : sample.html
<html>
<body>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "/showtime/", true);
ajaxRequest.send(null);
}
</script>
<form name='myForm'>
Name: <input type='text' onBlur="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
In views.py my function is :
def showtime(request):
string = "Ajax Application"
data = {"string" : string}
pprint (data)
return render_to_response("sample.html",data)
Now, The output is not as expected . The template does not receives the response sent by the server
What is wrong with the code ?

If you're trying to populate the text-field with AJAX returned string, you should not use render_to_response. Just return the string.
def showtime(request):
s = "Ajax Application"
print "Returning %s"%s #is this line executed?
return HttpResponse(s, mimetype="text/plain")

try if /showtime/ works as expected when you type in your browser!
using a js framework like jquery will save you time and energy implementing ajax stuff, eg. see this tutorial http://lethain.com/entry/2007/dec/11/two-faced-django-part-5-jquery-ajax/
there are also some django-built-ins that you can use, eg request.is_ajax to verify if the request is really comng from ajax!

Related

How to correctly set the request header in an ajax containing non-alphanumeric characters?

My HTML file contains a form with just a textarea whose contents are sent to a java servlet (called "Compiler"). The textarea text will always be java code, so it might include characters like +, %, =, etc.
I'm using ajax to get and display the response from the servlet.
But using ajax breaks the whole data being sent by the form, because it strips out part of the text or completely ignores the characters I mentioned above.
This is my html file:
<html>
<head>
<script type="text/javascript">
function objetoAjax(){
http_request= false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
return http_request;
}
function devolver_resultado(){
var llamadaAjax = objetoAjax();
var codigo = document.getElementById('codigo').value;
llamadaAjax.open("POST",'Compiler',true);
llamadaAjax.onreadystatechange = function() {
if(llamadaAjax.readyState == 4){
document.getElementById("resultado").innerHTML = llamadaAjax.responseText;
}
};
llamadaAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
llamadaAjax.send('codigo='+codigo);
}
</script>
</head>
<body>
<form action="Compiler" method="post">
<textarea rows="18" cols="70" id="codigo" name="codigo"></textarea>
<input type="submit" value="Compile" onclick="devolver_resultado(); return false;">
</form>
<div id="resultado">
</div>
</body>
</html>
I've debugged the javascript to see if the problem was where I assign the textarea value to the "codigo" variable:
var codigo = document.getElementById('codigo').value;
(screenshot)
But this variable is being correctly set, so I suspect the request is being incorrectly encoded (screenshot).
I'm new to ajax, but I assume this is controlled by llamadaAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
From this page I get that I should encode the form as multipart/form-data. I tried adding the encoding type to the form: but this didn't help.
So, two questions here:
1) Is actually this line the faulty one? llamadaAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
If so, how do I fix it?
2) If that's not where the bug is, what else could be happening? (remember that removing all the ajax and leaving a plain form that calls my "Compiler" servlet works as expected, so the servlet is not buggy).
Thanks!
SOLVED.
All I needed was to encode the text before sending it:
llamadaAjax.send('codigo='+encodeURIComponent(codigo));

How to send data to 'post.php' using AJAX? (without Jquery)

I'm newbie on this webdeveloper matters. I have already made a form where i've used Ajax (JQuery lib) to create a chat box.
Now, i wanna try to do something similar without using Jquery to understand how Ajax works. First i just want to write my messages on log.html using AJAX, so then i can read them later. But i dont understand why i can't send my textarea data into post.php.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Teste</title>
<script type="text/javascript">
function sendXMLDoc(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var message=document.getElementById('msg').value;
xmlhttp.open("POST", "post.php", false);
xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 0 ) {
alert("UNSENT");
}
if(xmlhttp.readyState == 1 ) {
alert("OPENED");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 2 ) {
alert("Headers Received");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 3 ) {
alert("Loading response entity body");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert("Data transfer completed");//check if the data was revived successfully.
}
}
}
xmlhttp.send(message);
}
</script>
xmlhttp.send(data) : Why im not sending my data to post.php?
Post.php is where i write my log.html (but i cant send my messages and i dont understand why):
<?php
$text = $_POST['message']; // WHY I CAN'T RECEIVE MY POSTED MESSAGE?
$fp = fopen("log.html", 'a');
fwrite($fp, "<div>\n(".date("g:i A").")<br>".$text."<br>\n</div>\n");
fclose($fp);
?>
And this is my form.html
<body>
<h1>Insert text on log.html</h1>
<form method="post" onsubmit="sendXMLDoc();">
<textarea name="message" maxlength="196" rows="8" ></textarea>
<br>
<input type="submit" value="Send"/>
</form>
</body>
have you taken a look at this link ?
It seems to have a complete explanation on how to build an AJAX request with PHP and MySql.
EDIT:
The problem in your code is both on your post.php, which has incorrect syntax (lacking double quotes before the last <br>), and should be something like :
post.php
<?php
$text = $_POST['message'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div>\n(".date("g:i A").")<br>".stripslashes(htmlspecialchars($text))."<br>\n</div>\n");
fclose($fp);
?>
and with the request header, which should have the content-type set (see code below)
I based this answer on w3.org.
The final html here presented shall help you understand how Ajax requests behave on different browsers. Try it out.
It seems though that for Firefox to load the request, you need to do something when the Status is OPENED (1), and I don't quite understand why.
Try this code on different browsers to see the different approaches to XMLHttpRequest.
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript">
function sendXMLDoc(obj){
var message=obj["message"].value;
var data = "message=" + message;
var xmlhttp;
try{
// Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
url = "http://localhost/AjaxPhp/post.php"
xmlhttp.open("POST", url , true);
xmlhttp.onreadystatechange = display_data;
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
function display_data() {
if(xmlhttp.readyState == 1 ) {
alert("OPENED");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 2 ) {
alert("Headers Received");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 3 ) {
alert("Loading response entity body");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert("Data transfer completed");//check if the data was revived successfully.
}
}
}
}
</script>
</head>
<body>
<h1>Insert text on log.html</h1>
<form method="post" onsubmit="sendXMLDoc(this);">
<textarea name="message" maxlength="196" rows="8" ></textarea>
<br>
<input type="submit"/>
</form>
</body>
</html>
I don't truly understand the whys, but according to w3, the order of the requests should, in my understanding, be :
OPENED (after invoking the open method), HEADERS_RECEIVED (after setRequestHeader), LOADING (request body received). DONE (Data transfer completed, after send) .
Chrome handles the post.php but doesn't present any alert box (maybe its my popup settings, maybe not)
IE shows only the OPENED alert message
Firefox goes "Headers Received", "Data transfer completed","OPENED", "Data transfer completed".
Hope this helps understanding it a little bit more. Always go check w3.org for the ultimate source on the web. It might not be very user-friendly and intuitive, but provides some tips on the whys and the shoulds.

AJAX update for Spring <form:select> element

I'm using Spring MVC for a project. In it, on a particular page, I'm using the Spring form tags to display an ArrayList added to the model in the controller as below:
<form:select path="myList">
<form:options items="${listElements}"/>
</form:select>
Now, listElements may be edited from another page (a child window), so I want myList to be auto updated every 2 sec or so. As of now I am refreshing the parent window when an element is added; the form in the parent page however has other fields in which the user simply keys in data, so a full refresh resets that data as it has not yet been posted. As such, I want to use AJAX to update just my form:select element every 2 seconds.
How can I do this?
Note: I am an AJAX noob. I went through a few similar posts on SO and elsewhere, but sadly I was not able to figure it out. Any help would be extremely appreciated!
1.Add Id attribute in select element.
2.Add ajax method handler in mvc controller which returns arrayList (I would prefer return json object).
3.Fire ajax call in jquery/javascript
JSP code:
<head>
<link href="<c:url value="/resources/form.css" />" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<c:url value="/resources/jquery/1.6/jquery.js" />"></script>
<script type="text/javascript">
var interval =2000;
setInterval("getServerData()",interval);
function getServerData(){
$.getJSON("/MyApp/data/jsonList", function(response){
$("#selectBox option").remove();
var options = '';
$.each(response, function(index, item) {
options += '<option value="' + item + '">' + item + '</option>';
$("#selectBox").html(options);
});
});
}
</script>
</head>
<body>
<form:form id="form" method="post">
<select id="selectBox">
<select>
</form:form>
</body>
Controller Code:
#RequestMapping(value="/data/jsonList", method=RequestMethod.GET)
public #ResponseBody List<String> getDataList() {
List<String> myList = new ArrayList<String>();
myList.add("option1");
myList.add("option2");
myList.add("option3");
myList.add("option4");
return myList;
}
if you plan to user jquery check
Updating select box options via jQuery AJAX?
Good read: Spring ajax 3.0 page.
I found what I was looking for! :)
In case someone else finds it useful in the future, what I did is as follows:
Gave an id to my <form:select>:
Created reloadlist.html, a page with only a copy of the relevant <form:select>.
Added the following script:
<script type="text/javascript">
function Ajax(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();// Firefox, Opera 8.0+, Safari
}catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("No AJAX!?");
return false;
}
}
}
xmlHttp.onreadystatechange=function(){
document.getElementById('ReloadList').innerHTML=xmlHttp.responseText;
setTimeout('Ajax()',10000);
}
xmlHttp.open("GET","reloadlist.html",true);
xmlHttp.send(null);
}
window.onload=function(){
setTimeout('Ajax()',10000);
}
</script>
This probably isn't a very good way to get this done, but it worked. Better answers will be greatly appreciated!

AJAX not working with XAMPP or is it just impossible

I'm still relatively new to AJAX and am trying to figure out why my simple test is not working. From what I read AJAX will not work under one domain, and other words pop up like cross-site and remote server. Anyways my problem is is that I'm not sure if my code is wrong or simply what I'm trying to do is impossible. I created a simple ajax request to submit data when I click on the button. Here is the code for the first script.
<html>
<head>
<script type="text/javascript" >
function load(thediv, thefile) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile, true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="submit" onclick="load('adiv', 'hello.php');">
<div id="adiv"></div>
</body>
</html>
Here is the code for the file hello.php
<?php
echo 'aaa';
?>
AJAX is just an http request done in the background. But yes, there are security restrictions that prevent you doing a normal ajax request to any arbitrary server.
What your code is missing is actually setting the URL that you're placing the request to. You've got hello.php as a parameter to your load() function, but you never actually USE it. So you're doing an AJAX request to... "nowhere".

server crashes when i use onreadystatechange

I am trying to create a chat for my website.
To load the new data, i run a function every 1.5''.
If i use asynchronous mode, my website is fast, my server does not crash, but browser freezes until the response.
When i use synchronous mode, my server crashes after a while, and i have to restart Apache (! ?).
I thought that i was requesting too much data and my (virtual) server crashes, but why in asynchronous mode works fine ?
function loadchat() {
xmllive.open('GET','live.php', false);
xmllive.send(null);
myelemen('dcdd').innerHTML = xmllive.responseText;
}
function loadchatv() {
xmllive.onreadystatechange=function() {
if (xmllive.readyState==4 && xmllive.status==200){
myelemen('dcdd').innerHTML = xmllive.responseText;
}
}
xmllive.open('GET','live.php', true);
xmllive.send();
Thank you for your answer, MMM. Since your response, i read about your suggestions.
(http://dsheiko.com/weblog/websockets-vs-sse-vs-long-polling).
I figured that, in Long Pooling the server makes a loop until finds new data and only then browser receives and makes a new request.
So, tell me please, what do you think about this solution (simplified):
/////////// html file //////////////
<script type="text/javascript" charset="utf-8">
var xmlff;
if (window.XMLHttpRequest) {
xmlff=new XMLHttpRequest();
} else {
xmlff=new ActiveXObject("Microsoft.XMLHTTP");
}
function waitForMsg(){
xmlff.onreadystatechange=function() {
if (xmlff.readyState==4 && xmlff.status==200){
document.getElementById('messages').innerHTML = xmlff.responseText ;
setTimeout('waitForMsg()', 1000 );
}
}
xmlff.open('GET','msgsrv.php' ,true);
xmlff.send();
}
</script>
</head>
<body>
<div id="messages">
</div>
<script type=text/javascript>
waitForMsg()
</script>
</body>
</html>
/////// php file ///////////
<?
do {
sleep(3);
$result = mysql_query("SELECT message FROM chat ");
while ($row = mysql_fetch_array($result)){
$msg .= $row[0];
}
} while (mysql_num_rows($result) == 0);
header("HTTP/1.0 200");
print $msg;
?>
Thanks in advance.

Resources