Martin Newman Martin Newman - 4 months ago 9
Ajax Question

Function doesn't send data

I have following code. The problem is that ajax doesn't send data, I don't know why. It seems that problem could be in the javascript function. Can you help me please?

When I place the submit button out of the form, it works, why?

<div class="modal fade" id="form-content" tabindex="-1" role="dialog" style="display: none; ">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div class="row">
<div class="col-md-12 text-center">
<div class="pop-up">
<div class="box-1">
<h3>Fill email</h3>
</div>
<img src="img/6.png" class="center-block" alt="..">
<div class="form-search space40">
<form class="contact">
<div class="input-group input-group-lg mtop-10">
<input type="text" name="Email" class="form-control input-lg" placeholder="email">
<span class="input-group-btn">
<button id="submit" class="btn btn-lg-sub model-btn" name="name">submit</button>
</span>
</div>
</form>
</div>
<div class="space30"></div>
<div>
</div>
<div class="space30"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>


$(function() {
$("button#submit").click(function(){
$.ajax({
type: "POST",
url: "process.php",
data: $('form.contact').serialize(),
success: function(msg){
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function(){
alert("failure");
}
});
});
});

Answer

Buttons without the type attribute are considered as a submit button, so when you click the button you need to prevent the default behaviour which submits the form, or you can add type="button":

$(function() {
    $("button#submit").click(function(e) {
        e.preventDefault(); //You need this
        $.ajax({
            type: "POST",
            url: "process.php",
            data: $('form.contact').serialize(),
            success: function(msg) {
                $("#thanks").html(msg)
                $("#form-content").modal('hide');
            },
            error: function() {
                alert("failure");
            }
        });
    });
});

Or:

<button id="submit" type="button" 
        class="btn btn-lg-sub model-btn" 
        name="name">submit</button>

I hope this will help you.

Comments