Member Avatar for RudyM

I am trying to submit a form and get a result from an AJAX call. However, the error block is triggered when submitting the form.

If I change the <form> to a <div> and change the $("form#main_frm").submit(...) to $("#main_frm").click(...), it works. What am I doing wrong with form? Thanks in advance.

<!DOCTYPE html>
<HTML>
<HEAD>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<TITLE>main</TITLE>
<SCRIPT>
    $(document).ready(function(){
        $("form#main_frm").submit(function(){
            process();
        });
    });
    function process()
    {
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "process.php",
            data: "",
            success: function(data, textStatus, jqXHR)
            { $("#result").text(JSON.stringify(data)); },
            error: function(jqXHR, textStatus, errorThrown)
            { $("#result").append(errorThrown + ": " + textStatus); }
        });
    }
</SCRIPT>
</HEAD>
<BODY>
    <FORM METHOD=POST ID='main_frm'>
        <BUTTON TYPE=SUBMIT>SUBMIT</BUTTON>
    </FORM>
    <DIV ID='result'></DIV>
</BODY>
</HTML>

The problem i see here without looking at your code in detail is that your form is going to behave by generating a post and the page will reload. you need to prevent that behavior if you dont want the page to reload.

I may be able to take a closer look later, but just try this and see if it solves your problem

$("form#main_frm").submit(function(e){
     e.preventDefault();            
     process();
});
Member Avatar for RudyM

That seems to work just fine, thanks!!!

My bit to add - just have a normal non submit button and wire up to the click event on that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.