weixin_33698823 2014-12-11 14:17 采纳率: 0%
浏览 30

使用PHP和MySQL的Ajax Post


Im trying to post data to mysql by using PHP and Ajax, the only thing problem that data does not enter into database it so the problem seems in the javascript which i think ajax please help me.

Please there some one can fix it if there any error on code?

FORM:

<form id="contactForm" action="ajax.php" method="post">
<input name="name" id="name" type="text"/>
<input name="email" id="email" type="text"/>
<input type="button" value="Send" name="submit" id="submit" /> 
<span id="error" class="warning">Message</span></p>
</form>
<p id="sent-form-msg" class="success">Thanks for your comments.We will update you within 24 hours. </p>

JS:

jQuery(document).ready(function($){
    // hide messages 
    $("#error").hide();
    $("#sent-form-msg").hide();

    // on submit...
    $("#contactForm #submit").click(function() {
        $("#error").hide();

        var name = $("input#name").val();
        if(name == ""){
            $("#error").fadeIn().text("Name required.");
            $("input#name").focus();
            return false;
        }

        var email = $("input#email").val();
        if(email == ""){
            $("#error").fadeIn().text("Email required");
            $("input#email").focus();
            return false;
        }

        var dataString = 'name=' + name + '&email=' + email;

        $.ajax({
            type:"POST",
            data: dataString,
            success: success()
        });
    });  

    // on success...
     function success(){
        $("#sent-form-msg").fadeIn();
        $("#contactForm").fadeOut();
     }
    return false;
});

AJAX.php

$con=mysqli_connect("localhost","admin","admin","test");
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO test (name, email) VALUES ('$name', '$email')";
if (!mysqli_query($con,$sql)) {
  die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);

Thank you in Advance.

  • 写回答

2条回答 默认 最新

  • H_MZ 2014-12-11 14:21
    关注

    You must include the URL you want to POST to in the AJAX call.

    $.ajax({
        url: "ajax.php",
        type:"POST",
        data: dataString,
        success: success()
    });
    
    评论

报告相同问题?