ajax live search with node.js - ajax

I'm new to node.js. Now I'm trying to write a simple website where users can input something for the server to process, and receive a result, e.g. search for something.
I try to implement it as follows:
write the index.html
write the server.js, it creates a server, and display the index page using var index = fs.readFileSync('index.html'); response.end(index);
add ajax codes in index.html, to receive input from users and send it to the server
the last step will be adding codes in server.js, which processes the request and send a result to ajax to display it.
My question is about step 4. In the server.js, when it receives ajax request, should it somehow add the result to the index.html file, and send back usingresponse.end(index), OR send back only the result? If the latter one, which I tried, it will send both the index.html page and the result. But I only want the result.
Below is the two files index.html and server.js:
index.js
<!DOCTYPE html>
<html>
<!-- Client search using Ajax -->
<head>
<title>live search</title>
<script>
function getResults(query) {
if (query.length===0) {
document.getElementById("results").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://127.0.0.1:2000/search?"+query,true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("results").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.send();
}
</script>
</head>
<body>
<hr>
<input type="text" id="search" onkeyup="getResults(this.value)"/>
<br>
<div id="results">
</div>
</body>
</html>
server.js
var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
var url = require('url');
http.createServer(function (req, res) {
res.writeHead(200, {'ContentType': 'text/html'});
res.end(index);
//codes for request processing
result="";
var path = url.parse(req.url).pathname;
console.log(path);
if (path.length!==0) {
result = "I'm the result";
}
res.write(result);
}).listen(2000);

If I understood your question correctly.
You want to send data between index.html and server.js on runtime.
For that, you need to use socket.io library.
For client(index.html)
use client side library for socket.io like following.
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
Now If you want to send the data which you get in index.html(client) then you can send it to server using
socket.emit("EventName",{"data1": value1 , "data2" : value2 , [...]})
Then you can receive it on server using event listeners like.
socket.on("EventName",function(data){
//here you can use "data" parameter that contains values sent from client
});
This was the client to server send/receive scenario.
For server to client, do the same thing i.e use socket.emit() on server to send to client and socket.on() at client to receive from server.

Related

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 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".

basic ajax with external server problem

I want to use a yahoo api for place finding and I want to write something like that:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://where.yahooapis.com/geocode?location=701+First+Ave,+Sunnyvale,+CA&appid=yourappid",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
the yahoo link works properly as you can see here:
http://where.yahooapis.com/geocode?location=701+First+Ave,+Sunnyvale,+CA&appid=yourappid
and the ajax format works if I open a local txt file (this is a w3 example) instead of external link.
but when running this code like that it won't work.
i get:
xmlhttp.status==0
when
xmlhttp.readyState==4
and as i found out in another question here it's due to security reasons.
so how do i work around the problem to get the same result?
thanks.
To access an external domain you would usually have to do the query on the server and let your ajax call go to your own domain. The server script will query yahoo and return the values for you. How exactly depends on your environment.
You can proxy the response. On your own server, set up a script that simply loads a page from another server and query the page on your server instead of the remote server.

Can I use this Ajax script to communicate and exchange data between client and server?

This block of code is for client.html (it is located in this www.client.com/client.html) - client side.
The I have the code below that goes something like this:
ajaxRequest.open("GET", "http://www.server.com/ajax.php", true);
This is how I call the file ajax.php located in the server. Unfortunately I have no luck at all. It cannot connect to the server I'm calling. BTW, the ips /test site I've been using are all no restrictions, and is accessible to all.
However, I tried to simulate by putting both client.html and ajax.php in same site and it works well.
So my question is does this script works only if you are in same site? or does it work also in client-server scenario? What else do I have to do in order to make this work?
//client.html
<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", "http://www.server.com/ajax.php", true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
// ajax.php
<?php
echo date("H:i:s");
?>
Browser follow the same origin policy for security reasons. So you will not be able to make an AJAX request to a different domain.
If you have control to the server, you can send special headers that allows cross-domain AJAX. Otherwise I think you have to find different methods.
Another thing you can do is to add a script to your page, whose source resides on www.server.com. Then in the source you can transmit data, for instance by assigning it to a new variable. In this way you are not constrained by cross-domain restrictions, but will only be able to do a GET request (not POST, PUT, DELETE...). Moreover there needs to be some collaboration from the server. Unlike in AJAX requests, the server will not spit out any page, but has to output valid javascript.
Usually the server actually encodes the data in JSON, and passes it to a given function, so the response may look like
someCallback({foo: 'bar', bar: 'foo'});
This techique is called JSONP, and you can find more details here.

use of ajax in django problem with the code

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!

Resources