jQuery Ajax form submit disregards 'success' function, reloads page

Go To StackoverFlow.com

0

I'm submitting an html form to a mySQL db with jQuery .ajax. When I submit the form (after all the fields are validated), the data IS inserted as a new record into the db, but the success function doesn't run.

jsFiddle

*This is all taking place in a google maps infoWindow, but I'm not sure that that's relevant.

HTML:

<div id="formDiv">
    <form name="htmlForm" id="htmlForm">

    <p id="contactP">
    <label for="contact">Email:</label>
    <input type="text" name="contact" id="contact"/> <br/>
    </p>

    <p id="phoneP">
    <label for="phone">Phone:</label>
    <input type="text" name="phone" id="phone"/> <br/>
    </p>

    <p id="datepickerP">
    <label for="datepicker">Date:</label>
    <input type="text" name="date" id="datepicker"/> <br/>
    </p>

    <p id="latP">
    <label for="lat">Latitude:</label>
    <input type="text" name="lat" id="lat" class="location"/> <br/>
    </p>

    <p id="lngP">
    <label for="lng">Longitude:</label>
    <input type="text" name="lng" id="lng" class="location"/> <br/>
    </p>        

    <p id="descP">
    <label for="desc" id="dos">Description of Sighting:</label> <br/>
    <textarea name="desc" id="desc"></textarea><br/>
    </p>

    <input type="submit" class="button" id="submitBtn" value="Post Sighting!" onClick="postSighting();"/>

</div>

Javascript / jQuery:

function postSighting() {
    // jQuery Validate
    $('#htmlForm').validate({
        rules: {
            contact: {required:true, email:true},
            phone: {required:true},
            date: {required:true, date:true},
            lat: {required:true},
            lng: {required:true},
            desc: {required:true},
        },
        messages: {
            desc: 'Please be descriptive!'
        },
        errorPlacement: function(error, element) {
            error.appendTo($('#' + element.attr('id') + 'P'));
            return false;
        };
    });

    //jQuery ajax form submit
        var contact = $('input#contact').val(),
            phone = $('input#phone').val(),
            date = $('input#datepicker').val(),
            lat = $('input#lat').val(),
            lng = $('input#lng').val(),
            desc = $('textarea#desc').val();
        var dataString = "contact=" + contact + '&phone=' + phone + "&date=" + date + "&lat=" + lat + "&lng=" + lng + "&desc=" + desc;
        $.ajax({
            type: "POST",
            url: "Includes/test.php",
            data: dataString,
            error: function(xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                alert(ajaxOptions);
                alert(thrownError);
            },
            beforeSend: function() {
                return $('#htmlForm').validate().form();
            },
            success: function() {
                $('#formDiv').html('<div id="message"></div>');
                $('#message').html('<h2>Thank You!</h2>')
                    .append('<h3>Your sighting has been reported</h3>')     
                return false;
            }   
        });
        return false;  
    };

I've alerted out the jQuery ajax errors, and I'm getting:

alert(xhr); => 0

alert(thrownError) => error

http://jsfiddle.net/rhewitt/u3C4U/

2012-04-04 17:46
by Roy
What do you see with firebug - gdoron 2012-04-04 18:00
What do you expect, your success function starts with return false, is that not what it's supposed to do ? If so place the return false at the bottom of the success function - adeneo 2012-04-04 18:00
is there any chance to get a repro @ jsfiddle ... otherwise it's like fishing around .. - Andreas Niedermair 2012-04-04 18:11
@Andreas http://jsfiddle.net/rhewitt/u3C4U - Roy 2012-04-04 18:36


0

Try this instead of the inline javascript function:

$("#map_canvas").on('click', '.submitBtn', function(e){
    e.preventDefault();
    postSighting();        
});
2012-04-04 18:03
by adeneo
Sorry about that, it got mixed up in the shuffle. Same result tho -- Reloads the current page - Roy 2012-04-04 18:06
Are you preventing the default action of the submit button - adeneo 2012-04-04 18:09
That's what the return false is doin - Roy 2012-04-04 18:15
That's probably a bit too late, edited my answer - adeneo 2012-04-04 18:16
No luck there -- updated using that code in my jsFiddl - Roy 2012-04-04 18:47
@Roy - It's all dynamic, you will have to delegate the events to the parent element. Edited my answer, could be other things that will need updating to delegated events, and you should try this on a webserver where the Ajax function will work, not on JSfiddle - adeneo 2012-04-04 18:59
I'm not familiar with an online editor that supports webserver (this is my first php project). Suggestion - Roy 2012-04-04 19:04
Test it on a local webserver, any LAMP, XAMP, WAMP thingy should do - adeneo 2012-04-04 19:14
Got it, thanks so much - Roy 2012-04-05 11:40


0

The jQuery can not attach to the submit button, as it has the id submitBtn and you try to attach to class submitBtn.

Change from:

$('.submitBtn').click(function(e){
    e.preventDefault();
    postSighting();        
});

to:

$('#submitBtn').live("click", function(e){
    e.preventDefault();
    postSighting();        
});

Also note the use of .live() because the form is created dynamically.

2012-04-05 11:46
by fragmentedreality
e.preventDefault(); // This should already prevent the default 'submit' action of the button, shouldn't it - Roy 2012-04-05 11:49
That's right, @Roy. Updated my answer to reflect that - fragmentedreality 2012-04-05 12:47
I caught that in his post and made the correction, thanks tho - Roy 2012-04-05 12:59
Attaching to the click-event on the #map_canvas may or may not be successful, depending on how fast the popup ist generated. The usage of .live() makes sure, that events will be attached to all elements matching the selector – even if they are created later (like your form) - fragmentedreality 2012-04-05 13:18
Ads