I am trying to use Ajax/JQuery to submit a form, and on the target page (response.cfm) I am returning a Json which will return either a success or a failure message (based on the checkbox) on the form page (form.cfm). But I can’t seem to access the data sent by the ajax request.
form.cfm
<form id="frm_test">
<input type="text" name="firstname" id="firstname" placeholder="First name" required /><br>
<input type="text" name="surname" id="surname" placeholder="Surname" required /><br>
<input type="email" name="email" id="email" placeholder="Email" required /><br>
<input type="checkbox" name="error" id="error" />Return error (check to see the error message. leave empty to see a success message)<br>
<input type="submit" value="Save changes" id="submitdata" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$("#frm_test").submit(function (eventData) {
event.preventDefault();
$("#message").empty();
var postData = {
first_name: $('#firstname').val(),
family_name: $('#surname').val(),
email: $('#email').val(),
error: $('#error').is(':checked')
};
$.ajax({
url: "response.cfm",
method: "POST",
data: postData
}).done(
function(response) {
if (response["SUCCESSMESSAGE"] !== null) {
$("#message").append(response["SUCCESSMESSAGE"]);
} else if (response["EXCEPTIONMESSAGE"] !== null) {
$("#message").append(response["EXCEPTIONMESSAGE"]);
}
});
$("#frm_test").trigger("reset");
});
</script>
<div id="message"></div>
response.cfm
<cfprocessingdirective suppresswhitespace="Yes">
<cfset response = {
SuccessMessage: 'checkbox value' ? JavaCast("null", "") : "Success",
ExceptionMessage: 'checkbox value' ? "An error occurred" : JavaCast("null", "")
}>
<cfheader name="Content-Type" value="application/json">
<cfoutput> #serializeJSON(response)# </cfoutput>
</cfprocessingdirective>
2
Answers
You need to check for the posted value for
error
which will be available in theform
scope.Expanding on Dan’s solution
So what are the changes?