使用Ajax将PHP的响应返回给Jquery

时间:2016-01-20 11:46:34

标签: javascript php jquery mysql ajax

我使用Jquery / AJAX和PHP提交要保存在MySQL数据库中的信息。 这是我到目前为止所做的:

function Addinfo() {
    var ew = document.getElementById("ew").value;
    var mw = document.getElementById("mw").value;
    var dataString = 'ew1=' + ew + '&mw=' + mw;
    if (ew == '' || mw == '') {
        alert("Please Fill All Fields");
    } else {
        $.ajax({
            type : "POST",
            url : "ajaxadd.php",
            data : dataString,
            dataType : 'text',
            cache : false,
        })
        .done(function (data) {
            $('#message1').html(data);
        })
    }
    return false;
}

和我的PHP代码:

<?php
$ew2 = $_POST['ew1'];
$mw2 = $_POST['mw1'];
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("tp", $connection);
if (isset($_POST['ew1'])) {
    $query = mysql_query("insert into table(ew, mw) values ('$ew2', '$mw2')");
    $addresult = mysql_query("SELECT * FROM `table` WHERE `ew` = '" . $_POST['ew1'] . "' ORDER BY `id` DESC LIMIT 1");
    $aircraft = mysql_fetch_assoc($addresult);
    echo $aircraft;
}
mysql_close($connection); // Connection Closed
?>

它成功地将信息保存到数据库中,但我甚至无法获得成功消息,更不用说来自PHP的变量了。我已经阅读了关于异步调用,回调函数和承诺的无数帖子,但我不知道怎么能让它工作。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:0)

 $.ajax({
        type: "POST",
        url: "ajaxadd.php",
        ew1:ew,
        mw1:mw,
        data: dataString,
        dataType: 'text',
        cache: false,
    })

答案 1 :(得分:0)

你应该修改你的php代码,而不是直接返回mysql_fetch_assoc,因为它只返回你SQL结果的第一行。

<?php
$ew2 = $_POST['ew1'];
$mw2 = $_POST['mw1'];
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("tp", $connection);

if (isset($_POST['ew1']))
{
    $result = array();
    $query = mysql_query("insert into table(ew, mw) values ('$ew2', '$mw2')");
    $addresult = mysql_query("SELECT * FROM `table` WHERE `ew` = '" . $_POST['ew1'] . "' ORDER BY `id` DESC LIMIT 1");
    while($aircraft = mysql_fetch_assoc($addresult))
    {
        $result[] = $aircraft;
    }
    #echo $aircraft; // wait until whole result is collected
    echo json_encode($result);
}

mysql_close($connection); // Connection Closed

?>

此外,您应该编辑您的javascript代码,如下所示;

function Addinfo() {
    var ew = document.getElementById("ew").value;
    var mw = document.getElementById("mw").value;
    var dataString = 'ew1=' + ew + '&mw=' + mw;
    if (ew == '' || mw == '') {
        alert("Please Fill All Fields");
    } else {
        $.ajax({
            type : "POST",
            url : "ajaxadd.php",
            data : dataString,
            dataType : 'text',
            cache : false,
            success: function(data)
            {
                //$('#message1').html(data);
                alert(data);
            },
            error: function(data)
            {
                alert("Error");
            }
        });
    }
    return false;
}

另外建议您可以检查$ connection和$ db以成功初始化数据库连接和数据库选择,并再次建议您的php代码应该使用mysqli扩展而不是不推荐使用的mysql扩展。您可以使用mysqli替换调用方法的mysql部分。 @ RakhalImming的建议也非常有利于代码的安全性。

答案 2 :(得分:0)

末尾的PHP代码中

echo $aircraft将其更改为echo json_encode($aircraft);以及您提及的AJAX功能

cache:false包括success:function(response){alert response;}

它将为您的飞机提供AJAX功能的变量值。 祝你好运!

答案 3 :(得分:0)

Jquery :( main.js文件)

$(document).ready(function(){

    $('.ajaxform').on('submit', function(e){
        e.preventDefault();

        $.ajax({
            // give your form the method POST
            type: $(this).attr('method'),
            // give your action attribute the value ajaxadd.php
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: 'json',
            cache: false,
        })
        .success(function(response) {
            // remove all errors
            $('input').removeClass('error').next('.errormessage').html('');

            // if there are no errors and there is a result
            if(!response.errors && response.result) {
                // success
                // loop through result and append values in message1 div
                $.each(response.result, function( index, value) {
                    $('#message1').append(index + ': ' + value + '<br/>');
                });

            } else {

                // append the error to the form
                $.each(response.errors, function( index, value) {
                    // add error classes
                    $('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
                });

            }
        });

    });

});

PHP(ajaxadd.php文件)

<?php
    // assign your post value
    $inputvalues = $_POST;

    // assign result vars
    $errors = false;
    $returnResult = false;

    $mysqli = new mysqli('host', "db_name", "password", "database");

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    // escape your values
    foreach ($inputvalues as $key => $value) {
        if(isset($value) && !empty($value)) {
            $inputvalues[$key] = htmlspecialchars( $mysqli->real_escape_string( $value ) );
        } else {
            $errors[$key] = 'The field '.$key.' is empty';
        }
    }

    if( !$errors ) {

        // insert your query
        $mysqli->query("
            INSERT INTO `table`(`ew`, `mw`) 
            values ('".$inputvalues['ew1']."', '".$inputvalues['mw']."')
        ");

        // select your query
        // this is for only one row result
        $addresult = "
            SELECT * 
            FROM `table` 
            WHERE `ew` = '".$inputvalues['ew1']."' 
            ORDER BY `id` DESC
            LIMIT 1
        ";

        if( $result = $mysqli->query($addresult) ) {
            // collect results
            while($row = $result->fetch_assoc())
            {
                // assign to new array
                // make returnResult an array for multiple results
                $returnResult = $row;
            }
        }
    }

    // close connection
    mysqli_close($mysqli);

    // print result for ajax request
    echo json_encode(['result' => $returnResult, 'errors' => $errors]);

    exit;
?>

HTML:

<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Ajax form submit</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>


        <form class="ajaxform" action="ajaxadd.php" method="POST">

            <input type="text" name="ew1" />
            <input type="text" name="mw" />

            <button type="submit">Submit via ajax</button>

        </form>

        <div id="message1"></div>

        <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.12.0.min.js"><\/script>')</script>
        <script src="main.js"></script>
    </body>
</html>