<p>There are some problems with your JavaScript that I expect is the cause of your issue.</p>

<p>From your code I'm assuming you're using <a href="http://jqueryvalidation.org/" rel="nofollow noreferrer">jQuery Validate</a> to validate the form before submission. Your first issue is the line</p>

<pre><code>event.preventDefault();
</code></pre>

<p>within the <code>submitHandler()</code> method – jQuery Validate will actually prevent the default form submission for you, so this line is redundant. Also, there is no variable called <code>event</code>, so that's going to cause trouble.</p>

<p>The second issue is that you're using the wrong syntax for the <a href="http://api.jquery.com/jquery.ajax/" rel="nofollow noreferrer"><code>$.ajax()</code></a> method. Considering your current code, I believe you want to use the <a href="http://api.jquery.com/jquery.post/" rel="nofollow noreferrer"><code>$.post()</code></a> method instead.</p>

<p>Finally, you're serializing the wrong object – <code>$(this).serialize()</code> should actually read <code>$(form).serialize()</code>.</p>

<p>With the above issues fixed, your code should look like this:</p>

<pre><code>$(document).ready(function () {

    $('form#brick').validate({

        ignore: ":hidden",

        rules: {
            "fields[firstName]": {
                required: true,
            },
            "fields[lastName]": {
                required: true
            },
            "fields[email]": {
                required: true,
                email: true
            }
        },

        messages: {
            "fields[email]": "Email is required"
        },

        submitHandler: function (form) {

            var data = $(form).serialize();

            $.post('/', data, function (response) {
                if (response &amp;&amp; response.success) {
                    $('#thanks').fadeIn();
                    $('#brick').fadeOut();
                } else {
                    alert('An error occurred. Please try again.');
                }
            });

        }

    });

});
</code></pre>

<p>Finally, for some pointers on how you could handle errors within the <code>response</code> payload, see <a href="https://craftcms.stackexchange.com/questions/8722/how-do-you-correctly-handle-errors-using-pt-contact-form-when-submitting-via-aja?rq=1">this thread</a>.</p>

CC BY-SA 3.0
2016-01-24T14:49:30.760Z
2016-01-24T14:57:07.117Z
2017-04-13T12:51:00.253Z
Mats Mikkel Rummelhoff
<p>I am a bit mystified by how to utilize templates for Guest entries plugin working fine for normal post saving custom fields.</p>

<p>When I use ajax to submit I get an XHR 200 response but an HTML response - no JSON. Ideally I don't want to redirect to another page but just manipulate the DOM and pass some variables into the page form JSON returned on success.</p>

<p>I have read and reread every ajax post but still can't get a pure JSON response</p>

<p>Is it necessary to utilize some kind of detection within the template for Craft ajax?</p>

<p>Just when I thought i had ajax understood...</p>

<p>Here is my JS:</p>

<pre><code>$(document).ready(function () {
//validation rules
$("form#brick").validate({
    ignore: ":hidden",
    rules: {
        "fields[firstName]": {
            required: true,
        },
        "fields[lastName]": {
            required: true
        },
        "fields[email]": {
            required: true,
            email: true
        }
    },
    messages: {
        "fields[email]": "Email is required"
    },

    submitHandler: function (form) {
        // Prevent default posting of form
        event.preventDefault();

        var data = $(this).serialize();

        $.ajax('/', data, function(response) {
            if (response.success) {

                console.log(response);
                $('#thanks').fadeIn();
                $('#brick').fadeOut();
                console.log(response);
            } else {
                // response.error will be an object containing any validation errors that occurred, indexed by field name
                // e.g. response.error.fromName =&gt; ['From Name is required']
                alert('An error occurred. Please try again.');
            }
        });
    }
});
</code></pre>

<p>});</p>

CC BY-SA 3.0
2016-01-23T23:34:43.870Z
What is the HTML that is being received? Are entries getting saved when you perform this AJAX request?
Ben Fleming
CC BY-SA 3.0
2016-01-24T09:17:01.350Z
There's a bug in your JavaScript – `function (form) {...` should be `function (event) {...`; the bug means you're not properly preventing the form's default submission. Not sure if that's the root cause of your issue, though.
Mats Mikkel Rummelhoff
CC BY-SA 3.0
2016-01-24T10:44:00.173Z
Updated JS above
Works fine.
The html in the ajax response is the core index.html template being loaded....
So confused
joomkit
<ajax>
Template for submit via ajax to Guest Entries plugin
# Template for submit via ajax to Guest Entries plugin

(Asked by: username_0 on 2016-01-23)

I am a bit mystified by how to utilize templates for Guest entries plugin working fine for normal post saving custom fields.
When I use ajax to submit I get an XHR 200 response but an HTML response - no JSON. Ideally I don't want to redirect to another page but just manipulate the DOM and pass some variables into the page form JSON returned on success.
I have read and reread every ajax post but still can't get a pure JSON response
Is it necessary to utilize some kind of detection within the template for Craft ajax?
Just when I thought i had ajax understood...
Here is my JS:
$(document).ready(function () {
//validation rules
$("form#brick").validate({
    ignore: ":hidden",
    rules: {
        "fields[firstName]": {
            required: true,
        },
        "fields[lastName]": {
            required: true
        },
        "fields[email]": {
            required: true,
            email: true
        }
    },
    messages: {
        "fields[email]": "Email is required"
    },

    submitHandler: function (form) {
        // Prevent default posting of form
        event.preventDefault();

        var data = $(this).serialize();

        $.ajax('/', data, function(response) {
            if (response.success) {

                console.log(response);
                $('#thanks').fadeIn();
                $('#brick').fadeOut();
                console.log(response);
            } else {
                // response.error will be an object containing any validation errors that occurred, indexed by field name
                // e.g. response.error.fromName => ['From Name is required']
                alert('An error occurred. Please try again.');
            }
        });
    }
});

});

**Tags:** ajax
> **Comments:**
> **username_1**: What is the HTML that is being received? Are entries getting saved when you perform this AJAX request?  
> **username_2**: There's a bug in your JavaScript – `function (form) {...` should be `function (event) {...`; the bug means you're not properly preventing the form's default submission. Not sure if that's the root cause of your issue, though.  
> **username_0**: Updated JS above Works fine. The html in the ajax response is the core index.html template being loaded.... So confused  

---

## 1 answers

### Answer by username_2 on 2016-01-24. Score: 3 | Accepted answer

There are some problems with your JavaScript that I expect is the cause of your issue.
From your code I'm assuming you're using jQuery Validate to validate the form before submission. Your first issue is the line
event.preventDefault();

within the submitHandler() method – jQuery Validate will actually prevent the default form submission for you, so this line is redundant. Also, there is no variable called event, so that's going to cause trouble.
The second issue is that you're using the wrong syntax for the $.ajax() method. Considering your current code, I believe you want to use the $.post() method instead.
Finally, you're serializing the wrong object – $(this).serialize() should actually read $(form).serialize().
With the above issues fixed, your code should look like this:
$(document).ready(function () {

    $('form#brick').validate({

        ignore: ":hidden",

        rules: {
            "fields[firstName]": {
                required: true,
            },
            "fields[lastName]": {
                required: true
            },
            "fields[email]": {
                required: true,
                email: true
            }
        },

        messages: {
            "fields[email]": "Email is required"
        },

        submitHandler: function (form) {

            var data = $(form).serialize();

            $.post('/', data, function (response) {
                if (response && response.success) {
                    $('#thanks').fadeIn();
                    $('#brick').fadeOut();
                } else {
                    alert('An error occurred. Please try again.');
                }
            });

        }

    });

});

Finally, for some pointers on how you could handle errors within the response payload, see this thread.


---

