dongyan3853 2014-03-28 06:15
浏览 9
已采纳

将数据发送到DB并通过AJAX返回

The following code works properly and I am using it 'cause I need to update some notes in DB without refreshing a page. But what have to do when I need in the same event get some data back?

index.php where change should occur

<?php
$s = $GET['...']
$p = $GET['...']
print '
 <form id="notesForm">
  <textarea name="c">'.$note.'</textarea>
  <input type="text" value="LAST_CHANGE_NEED_GIVE_BACK_FROM_DB">
  <input type="hidden" name="s" value="'.$s.'">
  <input type="hidden" name="p" value="'.$p.'">
  <input type="submit" value="save note">
  <div id="response"></div>
</form>
';
?>

script which is posting data to live_notes.php and probably should be changed because of the goal

$(document).ready(function(){
    $('#notesForm').submit(function(){
        event.preventDefault();
        $('#response').html("<b>saving...</b>");
        $.ajax({
            type: 'POST',
            url: 'notes/live_notes.php',
            data: $(this).serialize()
        })
        .done(function(data){
            $('#response').html(data);
        })
        .fail(function() {
            alert("bad luck");
        });
        return false;
    });
});

notes/live_notes.php

<?php
$s = $_POST['s'];
$p = $_POST['p'];
$c = $_POST['c'];

// connecting DB

mysql_query("
UPDATE `poznamky`
SET
    last_change = now(),
    page = '$p',
    content = '$c'
WHERE
    page = '$p';
");

any idea?

  • 写回答

3条回答 默认 最新

  • dongping8572 2014-03-28 06:22
    关注
    <?php
    $s = $_POST['s'];
    $p = $_POST['p'];
    $c = $_POST['c'];
    
    // connecting DB
    
    $blnSuccess = mysql_query("
    UPDATE `poznamky`
    SET
        last_change = now(),
        page = '$p',
        content = '$c'
    WHERE
        page = '$p';
    ");
    
    if($blnSuccess){
    echo "success";
    }
    else {
    echo "not success!";
    }
    

    in your jquery :

    .done(function(data){
                $('#response').html(data); 
    }
    

    data have success or not success! which return as ajax response.

    Update
    If you want to return some data from database then:

    $result = mysql_query("
       select * 
          from `poznamky`
    ");
    
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        echo $row['content'];
    }
    

    Then it will return all content field from poznamky table into data in ajax.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算