Steven Carlton
Steven Carlton

Reputation: 444

Why is my AJAX form still loading my PHP page?

I have been struggling with understanding AJAX so I would appreciate some help. I pulled this example from the world wide web but it not behaving as I expected.

This form is posting the data as expected but the upon submit the .php page is loading. Ideally I would like to just post a "Success" message below the Submit button and not move pages. Thoughts?

<div style="padding:3px 2px;border-bottom:1px solid #ccc">Add a New Invitee</div>
<form id="ff" action="addinvite.php" method="post">
<table>
    <tr>
        <td>First Name:</td>
        <td><input name="fname" type="text"></input></td>
    </tr>
    <tr>
        <td>Last Name:</td>
        <td><input name="lname" type="text"></input></td>
    </tr>
    <tr>
        <td>Phone:</td>
        <td><input name="phone" type="text"></input></td>
    </tr>
    <tr>
        <td></td>
        <td><input type="submit" value="Submit"></input></td>
    </tr>
</table>
</form>

<script>
$('#ff').form({
    success:function(data){
    $.messager.alert('Info', data, 'info');
}
});
</script>

Upvotes: 0

Views: 160

Answers (1)

Drixson Ose&#241;a
Drixson Ose&#241;a

Reputation: 3641

the default behavior of a form is to redirect after submit. And if you want to use AJAX you should prevent the default behavior because AJAX is a web development technique that can send/retrieve data from server without interfering with display and behavior of the existing page.

If you're using a button it's okay not to prevent the default behavior but if you're using form and submit you should do something like this:

$('form').on('submit',function(e){
  e.preventDefault(); //prevent the default behavior

   //my ajax here and etc
});

Upvotes: 2

Related Questions