jQuery TypeError: 'undefined' is not a function on AJAX submit

BBB picture BBB · Jan 6, 2012 · Viewed 18.6k times · Source

Does anybody see a problem with the following?

jQuery(document).ready(function($) {
    $("#ajax-form").submit(function(e) {
        e.preventDefault();
        $("#result").html('Sending…').fadeIn();
        var fields = '{';
        $('#ajax-form').filter(':input').each(function() {
            fields = fields + $(this).attr("name")+' : '+$(this).val()+', ';
        });
        fields = fields + '}';
        url = '/scripts/form-submit.php';

        $.post(url,fields, function(data, respText, xhr){
            alert('ok-'+data+'-'+respText+'-'+xhr);
        })
        .error(function(d) {
            alert('no good');
        });
    });
});

In Inspector, I get the following error on submit:

TypeError: 'undefined' is not a function (near '....error(function(d) {...')

on the line that closes .error ( }); ). That's line 17.

On submit I get one alert which reads: "ok--success-[object XMLHttpRequest]". The script I'm submitting to is supposed to send an email and return "It worked" as AJAX response data, and the email is never sent nor is the response received. I know the script works, because when I post do it regularly (not asynchronously), it all works perfectly.

Any insight is very appreciated. Thanks.

Answer

diEcho picture diEcho · Jan 6, 2012

use serialize to generate post data

$('#form').submit(function(){
            $.ajax({
                type: "POST",
                url: "/scripts/form-submit.php",
                data: $(this).serialize(),
                success:function(response){
                    alert('ok-'+data+'-'+respText+'-'+xhr);
                    alert("Details saved successfully!!!");
                },
                error: function (request, status, error) {
                    alert(request.responseText);
                }                  
            });
        })