admin管理员组

文章数量:1399925

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.

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.

Share Improve this question edited Apr 30, 2018 at 5:38 Cœur 38.8k25 gold badges205 silver badges277 bronze badges asked Mar 4, 2014 at 18:50 Paulo CoghiPaulo Coghi 15k15 gold badges70 silver badges92 bronze badges 4
  • 2 How are you submitting the form? – Kevin B Commented Mar 4, 2014 at 18:54
  • 1 <input type="email" id="inputEmail1" name="inputEmail1" placeholder="[email protected]"> name attribute must be there in order to get the value on server. – Amit Garg Commented Mar 4, 2014 at 18:57
  • Kevin B, you were right from the start. The correct way is to use a submit button. – Paulo Coghi Commented Mar 4, 2014 at 19:11
  • Amit, you are right. I corrected it. – Paulo Coghi Commented Mar 4, 2014 at 19:12
Add a ment  | 

6 Answers 6

Reset to default 2

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 :)

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>

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(){
     //[...]
 }); 

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

I am trying to call webmethod in a ajax using jquery in asp, 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

$(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

本文标签: javascriptjQuery ajax form doesn39t workStack Overflow