Monday, November 03, 2008

Posting a Contact form Using Ajax

Here's the challenge - to make a form that appears by ajax, post to a page, and then have it return the response text. My friend digitalbart pointed out the futility of server side validation on a form that is only visible by javascript, but hey, that's just how I roll.

I would have posted the actual code here, but syntax highlighter doesn't seem to like me very much. I'll try to get the code posted in a bit.

Ah here we go - As you can see, the primaryAction button drives the post. There are five arguments to the $.ajax function... and they are type, url, data, success and dataType.

<script>
$(function(){

$(".primaryAction").click(
function(){
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var office_email = $("input#office_email").val();
var urlt = $("input#urlt").val();
dataString = "name="+name+"&email="+email+"&subject="+subject+"&message="+message+"&office_email="+office_email+"&urlt="+urlt;


$.ajax({
type: "POST",
url: "/includes/emailform.php",
ata: dataString,
success: function(data) {
alert (dataString);
$("#ajaxresults_"+urlt).html(data);
},
dataType: "html"
});

return false;
});
});
</script>

No comments: