Pierce McGeough
Pierce McGeough

Reputation: 3086

How to use jquery ajax with a form submission

Changed the code to this now. Form is located in subscribe.php which in included into the index page.

<form class="subscribe" id="email" method="get">
    <input class="email" id="emailaddress" name="email" type="text" placeholder="[email protected]" required>
    <input class="button" type="submit" id="emailSub" value="Subscribe">
</form>
<div id="subResult"></div>

Jquery is at bottom of the index page

$(document).ready(function() {
    $('#emailSub').click(function() {
        var email = $('#emailaddress').val();
        alert(email);
        $.ajax({
            type: "GET",
            dataType: 'script', //<-Data Type for AJAX Requests(xml | html | script | json)
            url: 'checksub.php',
            data: {
                'e': email
            },
            success: function(result) {
                $("#subResult").html(result);
            }
        });
    })
});

Checksub page is this now for testing.

<?php include 'admin/includes/db_connection.php'; ?>
<?php 
$email = mysqli_real_escape_string($db, $_GET['e']);
echo "test string:";
echo $email;
?>

Upvotes: 0

Views: 2310

Answers (2)

mehdi
mehdi

Reputation: 1755

maybe you should to change dataType? try it:

$.ajax({
    type: "GET",
    dataType: 'html', //<-Data Type for AJAX Requests(xml | html | script | json)
    url: 'checkemail.php',
    data: {
        'e': email
    },
    success: function(data) {
        $("#subResult").html(result);
    }
});

and

<input class="button" type="submit" id="emailSub" value="Subscribe">
                              ^ HERE

should be :

<input class="button" type="button" id="emailSub" value="Subscribe">

because of submit is submiting form and refreshing the page.. so jquery not work..

Specifying the Data Type for AJAX Requests

Upvotes: 2

Zach
Zach

Reputation: 3207

Are you preventing the default click event from firing submit?

$('#emailSub').click(function(e){
    e.preventDefault();
    var email = $('#emailaddress').val();
    $.ajax({url:"checkemail.php?e="+email,success:function(result){
        $("#subResult").html(result);
    }});
})

Upvotes: 3

Related Questions