Sparky Sparky - 1 month ago 10
Ajax Question

Using jQuery ajax() with Perl causes flicker on success

I'm trying to update some existing code that normally runs a Perl script which outputs a dynamically generated html page for messages, etc. Ultimately, my end result is to simply update a

div
with the output of the Perl file rather than sending the user to a new page.

I've been down a couple roads trying to find the best way to do this. After failing to find a way to do this on the Perl side, I'm now looking at jQuery
ajax()
.

Here is what I have so far and it's partially working:

Perl:

#!/usr/bin/perl
# =====================================================================

print "Content-type: text/html \n\n";
print "<p>Hello</p>";


HTML:

<form id="myForm" action="#">
<input type="submit" value="click me" />
</form>

<div id="message"></div>


jQuery/JavaScript:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').submit(function() {
$.ajax({
type: 'POST',
url: '/cgi-bin/myPerl.cgi',
async: false,
success: function(data) {
$('#message').html(data);
}
});
});
});
</script>


1) When I click the button, the
#message
div
only flashes the message for a second and then it goes blank. Why is that happening? This is my primary question.

I also do not fully understand all the settings in
.ajax()
despite my reading of the documentation:

2) It only works at all if I use
async: false
, otherwise with
true
or leaving this setting out, I get a "failed to load resource" error. Can somebody explain.

3) Is there a better way to do this? PHP? I just want to dynamically update a
div
with the message coming from the Perl file, avoiding page refreshes or new pages.

Answer

Add return false or e.preventDefault() to the submit event.

    $('#myForm').submit(function(e) {
        e.preventDefault()
        $.ajax({
            type: 'POST',
            url: '/cgi-bin/myPerl.cgi',
            async: false,
            success: function(data) {
                $('#message').html(data);
            } 
        });
        // return false;
    });
Comments