Paulo Coghi
Paulo Coghi

Reputation: 14959

jQuery ajax form doesn't work

I tried many ways to create a simple jquery ajax form but don't know why it is not submitting and/or returning the notification.

Here is my code:

Javascript

...
<script type="text/javascript" src="assets/js/jquery1.11/jquery-1.11.0.min.js"></script>
...

$('#form_signup').submit(function(event) {
    event.preventDefault();
    $.ajax({
        type: 'POST',
        url: 'signup.php',
        data: $(this).serialize(),
        dataType: 'json',
        success: function (data) {
            console.log(data);
            $('#form_signup_text').html(data.msg);
        },
        error: function (data) {
            console.log(data);
            $('#form_signup_text').html(data.msg);
        }
    });
});

HTML

<form id="form_signup" name="form_signup" method="POST">
    <div>
        <input type="email" id="inputEmail1" name="inputEmail1" placeholder="[email protected]">
    </div>
    <div>
        <a type="submit">Sign up!</a>
    </div>
    <div id="form_signup_text">
        <!-- A fantastic notice will be placed here =D -->
    </div>
</form>

PHP

<?php

$our_mail =    "[email protected]";
$subject  =    "Wohoo! A new signup!";
$email    =    $_POST['inputEmail1'];

$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;

if(preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)){

    $message = "Yesss!! We receive a new signup!
    E-mail: $email
    ";
    mail($our_mail, $subject, $message);

}
else {
    $return['error'] = true;
    $return['msg'] .= 'Something is wrong... snifff...';
}

return json_encode($return);

Solved:

There were three problems. And different users solve each of these problems.

  1. In PHP, you must "echo" the return array instead of "return"
  2. At first, you should use a submit button instead of an anchor in the form
  3. In the input, you must set both "id" and "name"

If any of these users want, you can edit or add a new answer with these details, and the points are yours.

Upvotes: 0

Views: 17395

Answers (6)

Vipul Verma
Vipul Verma

Reputation: 31

I am trying to call webmethod in a ajax using jquery in asp.net, but sometimes it works well and sometimes it doesn't.

Here is my ajax code :

$.ajax({
    type: "POST", 
    url: "frmTest.aspx/fncSave", 
    data: "{}"
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: "false",
    cache: "false", //True or False
    success: function (response) 
    result = response.d;
    if (result != "") {
        alert(response);
    }
},
Error: function (x, e) {
    alert("err");
    return false;
}
});

Here My Server Side Code :

<WebMethod()>
    Public Shared Function fncSave() As String
    Dim sResult As Int16
    Try
        Dim obj As New ClsCommon()
        sResult = obj.Save()
    Catch ex As Exception
                ex.Message.ToString()
    End Try
    Return sResult
End Function

Upvotes: 0

Raz Wilson
Raz Wilson

Reputation: 64

doesn't your a type="submit" need to be an input instead? or a button

Upvotes: 1

rm-vanda
rm-vanda

Reputation: 3158

The php code needs to echo instead of return.

just like this:

echo json_encode($return);

Also, your form needs a submit button - type="submit" on an <a> tag doesn't trigger the browser's functionality for handling <form>s

Finally, you need to ensure that your special submit handler is loaded at just the right time -- which, if it is included at the bottom of the page, right before the footer, it should be just fine. However, you can ensure this by wrapping it in

$(document).ready(function(){
     //[...]
 }); 

Upvotes: 1

Ijas Ameenudeen
Ijas Ameenudeen

Reputation: 9259

You need to do 3 things.

First, wrap your jQuery codes inside $(document).ready() function,

<script type="text/javascript">
    $(document).ready(function()
    {
        $('#form_signup').submit(function(event) {
            event.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'signup.php',
                data: $(this).serialize(),
                dataType: 'json',
                success: function (data) {
                    console.log(data);
                    $('#form_signup_text').html(data.msg);
                },
                error: function (data) {
                    console.log(data);
                    $('#form_signup_text').html(data.msg);
                }
            });
        });
    });
</script>

Second, Add a submit button to your form. Also you are missing the name attribute for the email input field. That causes the error in the php file.

<form id="form_signup" name="form_signup" method="POST">
    <div>
        <input type="email" id="inputEmail1" name="inputEmail1" placeholder="[email protected]">
    </div>
    <div>
        <input type="submit" name="signup" value="Sign Up!"/>
    </div>
    <div id="form_signup_text">
        <!-- A fantastic notice will be placed here =D -->
    </div>
</form>

Third, echo the results since you are using AJAX to submit the form. return will not have any effects.

<?php

$our_mail =    "[email protected]";
$subject  =    "Wohoo! A new signup!";
$email    =    $_POST['inputEmail1'];

$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;

if(preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)){

    $message = "Yesss!! We receive a new signup!
    E-mail: $email
    ";
    mail($our_mail, $subject, $message);
}
else {
    $return['error'] = true;
    $return['msg'] .= 'Something is wrong... snifff...';
}

echo json_encode($return);exit;

I checked and it's working fine.

Hope this helps :)

Upvotes: 2

Amit Garg
Amit Garg

Reputation: 3907

The problem is in your form.

<form id="form_signup" name="form_signup" method="POST">
    <div>
        <input type="email" id="inputEmail1" name="inputEmail1" placeholder="[email protected]">
    </div>
    <div>
        <input type="submit" name="submit" value="Submit">
    </div>
    <div id="form_signup_text">
        <!-- A fantastic notice will be placed here =D -->
    </div>
</form>

Upvotes: 2

Bene
Bene

Reputation: 1905

$(this) in the "ajax" function is not the form. So just try:

$('#form_signup').submit(function(event) {
    event.preventDefault();
    var $this = $(this);
    $.ajax({
        type: 'POST',
        url: 'signup.php',
        data: $this.serialize(),
        dataType: 'json',
        success: function (data) {
            console.log(data);
            $('#form_signup_text').html(data.msg);
        },
        error: function (data) {
            console.log(data);
            $('#form_signup_text').html(data.msg);
        }
    });
});

I admit i didn't check the rest of the code, im pretty sure thats the problem.

Of course if the problem still goes, just "f12" and check console and network for server request and headers, make sure all the params are there.

Hope that helped

Upvotes: -3

Related Questions