jQuery AJAX - Simple Chat
Send AJAX requests with this jQuery script to create a simple chat.
HTML
<script src="http://fonts.googlepis.com/css?famaily=Open+Sans:400,700"></script>
<form method="get" data-type="json" action="/echo/jsonp" ajax="true" name="myform">
<span id="result"></span>
<span>
<label>Message: </label>
<input type="text" name="msg" placeholder="Howdy..." />
</span>
<span>
<label>Name: </label>
<input type="text" name="name" placeholder="Who are you...?" />
</span>
<span>
<label><img id="loadingimg" src="http://dev.cloudcell.co.uk/bin/loading.gif"/> </label>
<input type="submit" value="Submit" />
</span>
</form>
CSS
body {
font-family: 'Open Sans', 'Helvetica Neue', 'Arial', sans-serif;
font-size: 13px;
}
form span {
display: block;
margin: 10px;
}
label {
display: inline-block;
width: 100px;
}
input[type="text"] {
border: 1px soild #ccc;
width: 200px;
padding: 5px;
}
input[type="submit"] {
padding: 5px 15px;
}
span#result {
padding: 5px;
background: #ff9;
}
img#loadingimg {
display: none;
}
JavaScript
(function($) {
$.fn.serializeFormJSON = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).serializeFormJSON();
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
var data_type = 'json';
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
datatype: data_type,
data: form_data,
cache: false,
beforeSend: function() {
},
success: function(myresults) {
$("#result").append("<br/>" + myresults.msg + " (" + myresults.name + ")");
$("#loadingimg").hide();
},
error: function(e) {
console.log(e);
}
});
});
});