Bastiaan Zwanenburg
Bastiaan Zwanenburg

Reputation: 143

Jquery form doesn't send?

A simplified version of my code:

JS:

$(function() {
    $("submit").click(function() {
        var msg_to = $("#msg_to").val();

        var dataString = 'msg_to=' + msg_to;

        $.ajax({
            type: "POST",
            url: "sendmessage.php",
            data: dataString,
            success: function(){
                $('.success').fadeIn(200).show();
                $('.error').fadeOut(200).hide();
            }
        });

        return false;
    });
});

HTML

<form method="post" name="form">
            <label class="label-left" for="msg_to">Message to</label>
            <input name="msg_to" id="msg_to" type="text">
 <input type="submit" value="" class="submit" />

The php file mails the form to my e-mail, and that works for sure when I just post the form to the PHP file. Via jquery, it just won't work. Can anyone find the bug in my code?

Upvotes: 0

Views: 77

Answers (4)

Bastiaan Zwanenburg
Bastiaan Zwanenburg

Reputation: 143

It works! It was a combination of @Vulcan 's solution and @Jacedc 's, and I made mistake of importing jquery AFTER the script above..

Upvotes: 0

jeroenvisser101
jeroenvisser101

Reputation: 881

I think that your form submits before a AJAX request can be made. Using the event.preventDefault() function prevents the form from submitting, so the AJAX request can finish loading.

$(function() {
    $(".submit").click(function(event) { // Added the '.' for the class, and the event parameter
        event.preventDefault(); // This prevents the submit-event to be fired
        var msg_to = $("#msg_to").val();

        var dataString = 'msg_to=' + msg_to;

        $.ajax({
            type: "POST",
            url: "sendmessage.php",
            data: dataString,
            success: function(){
                $('.success').fadeIn(200).show();
                $('.error').fadeOut(200).hide();
            }
        });

        return false;
    });
});

Upvotes: 0

Jace Cotton
Jace Cotton

Reputation: 2014

Try this:

$(document).ready(function() { // use document query selector then test for ready state
    $(".submit").click(function() { // submit query selector should have class "."
        var msg_to = $("#msg_to").val();
        var dataString = "msg_to=" + msg_to;

        $.ajax({
            type: "POST",
            url: "sendmessage.php",
            data: dataString,
            success: function() {
                $(".success").fadeIn(200); // no need for show()
                $(".error").fadeOut(200); // no need for hide()
            }
        });

        return false;

    });
});

Upvotes: 3

Barmar
Barmar

Reputation: 782166

$("submit")

should be:

$(".submit")

The first looks for a <submit> tag.

Upvotes: 4

Related Questions