I have this code which works, but hard coded.
$(document).ready(function(){
$('form').live('submit', function(){
var title = this.elements.title.value;
var owner = this.elements.owner.value;
var users = this.elements.users.value;
var groups = this.elements.groups.value;
var begin_date = this.elements.from.value;
var end_date = this.elements.to.value;
var anchor = this.elements.anchor.value;
var type = $(this).find('input:radio[name="ctype"]:checked').val() || '';
var aform = $('form[name="create_form"]');
I need aform
for a nested Ajax call later on.
Question
How do I construct aform
so it is not hard coded? There are many forms on the page.
It should contain
var title = this.elements.title.value;
var owner = this.elements.owner.value;
var users = this.elements.users.value;
var groups = this.elements.groups.value;
var begin_date = this.elements.from.value;
var end_date = this.elements.to.value;
var anchor = this.elements.anchor.value;
var type = $(this).find('input:radio[name="ctype"]:checked').val() || '';
and should work with the nested Ajax call later on.
$.ajax({
type: "GET",
url: "/cgi-bin/ajax.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: aform.serialize(),
You don't need to do all this by yourself. Jquery itself has a form plugin , which submits the form via ajax. It is self explainatory.
Here is a simple example of converting some form elements into a JSON object - although Abdul Kader's suggestion is better if you only want to do this to send the data in JSON format.
<form method="post" action="" id="example">
<p><label>Name<br><input type="text" name="name" value="Bob"></p>
<p><label>Happy<br><input type="checkbox" name="happy" checked></p>
<p><textarea name="information">Some text "data" here!</textarea>
</form>
<div id="exampleOutput">
</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function exampleFormData() {
var formData;
var jsonString = "({";
var jsonCount = 0;
// This will add each input to a JSON string
$("#example input, #example textarea").each( function () {
if (jsonCount > 0) {
jsonString += ", "
}
var key = this.name;
var value = this.value;
jsonString += key + ': "' + value.replace(/"/g, '\\"') + '"';
jsonCount++;
});
jsonString += "})"
// This converts the string into a JSON object
formData = eval(jsonString);
// Now you can use the formData JSON object...
$("#exampleOutput").html(formData.name + " " + formData.happy + " " + formData.information);
}
exampleFormData();
</script>
var aform = $(this);
(as requested by Sandra :-)