【问题标题】:Reload the query after adding the record to mysql database with ajax without reloading the page使用ajax将记录添加到mysql数据库后重新加载查询而不重新加载页面
【发布时间】:2014-10-06 02:26:29
【问题描述】:

我有一个页面,用户可以在其中将记录添加到 mysql 数据库。在同一页面上有一个数据库中现有记录的列表。

我使用ajax将记录添加到数据库,对不起旧版本的mysql,我先让这个东西工作后会更新:

$(document).ready(function(){
//on the click of the submit button 
$("#btn_submit").click(function(){
 //get the form values
 var username = $('#hdn_username').val();     
 var name = $('#txt_name').val();     
 var brand = $('#txt_brand').val(); 

 //make the postdata
 var postData = 'username='+username+'&name='+name+'&brand='+brand;

 //call your input.php script in the background, when it returns it will call the success function if the request was successful or the error one if there was an issue (like a 404, 500 or any other error status)

 $.ajax({
    url : "input.php",
    type: "POST",
    data : postData,
    success: function(data,status, xhr)
    {
        //if success then just output the text to the status div then clear the form inputs to prepare for new data
        $("#status_text").html(data);
        $('#name').val('');
        $('#brand').val('');
    },
    error: function (jqXHR, status, errorThrown)
    {
        //if fail show error and server status
        $("#status_text").html('there was an error ' + errorThrown + ' with status ' + textStatus);
    }
});
}); });

我的html是:

<table class="simplet" width="640" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th width="300" colspan="2">Product Name</th>
<th width="150">Brand</th>
<th width="100">Quantity</th>
<th width="60">Price</th>
<th width="30">Delete</th>
</tr>
</thead>
<tbody>
<tr><td colspan="6"><div id="status_text_list" /></td></tr>

[insert_php]

$current_user= wp_get_current_user();
$username= $current_user->user_login;

mysql_connect("localhost","xxxxx","xxxx");//database connection
mysql_select_db("xxxx");

$query= "SELECT * FROM wp_userdata WHERE username='$username'";
$result= mysql_query($query);
if (!$result) { die("Error db request: <br />". mysql_error()); }

while ($result_row = mysql_fetch_array($result, MYSQL_ASSOC)){ echo '<tr class="odd-row"><td width="30"></td><td>'.$result_row['product_name'].'</td><td>'.$result_row['product_brand'].'</td><td>'.$result_row['product_quantity'].'</td><td>'.$result_row['product_link'].'</td><td><a class="link-delete" href="#" data-delete-id="' . $result_row['id'] . '">X</a></td></tr>';
}


[/insert_php]

</tbody></table>
<br />

<table border="1">
  <tr>
    <td align="center">Add Products</td>
  </tr>
  <tr>
    <td>
         <form onsubmit="return false">
      <table>
<input type="hidden" id="hdn_username" name="username" value="[insert_php]echo $username;[/insert_php]">
        <tr>
          <td>Product Name</td>
          <td><input type="text" id="txt_name" name="name" size="50">
          </td>
        </tr>
        <tr>
          <td>Brand</td>
          <td><input type="text"  id="txt_brand" name="brand" size="50">
          </td>
        </tr>
<tr>
                <td></td>
                <td><div id="status_text" /></td>
            </tr>
        <tr>
          <td></td>
          <td align="right"><input type="submit" id="btn_submit" name="submit" value="Submit"></td>
        </tr>
</form>
        </table>
      </td>
    </tr>
</table>

而我的 input.php 是:

mysql_connect("localhost","xxxx","xxxx");//database connection
mysql_select_db("xxxx");




//inserting data order
$order = "INSERT INTO wp_userdata
            (username, product_name, product_brand)
            VALUES
            ('$_POST[username]',
             '$_POST[name]',
            '$_POST[brand]')";

//declare in the order variable
$result = mysql_query($order);  //order executes
if($result){
    echo ("DATA SAVED SUCCESSFULLY");
} else{
    echo("<br>Input data is fail");
}

当我点击提交按钮时,表单值被发送到 input.php 并显示成功消息,你可以在这里看到它 - http://suppliesprices.com/?page_id=4

我想要实现的是在不重新加载页面的情况下将新的数据行添加到显示的列表中。

我想用 javascript 渲染它并添加到成功的 ajax 调用中,但不确定它是否可以工作。

如何更改我的代码以获得所需的效果?

【问题讨论】:

    标签: javascript php jquery mysql ajax


    【解决方案1】:

    你可以做两件事。

    选项 1:

    只需使用常规按钮 type='button' 而不是提交按钮 type='submit'。默认情况下,提交按钮会更改页面,而常规按钮不会。

    选项 2:

    $("#btn_submit").click(function(event){
      event.preventDefault();
     //get the form values
    

    请参阅event.preventDefault 的文档。提交按钮的默认操作是通过转到表单的action 属性中定义的页面进行提交(或者如果您没有指定action 属性,则返回到同一页面)。此调用会阻止该默认操作,因此您可以改用 Ajax。

    并且在表单上,​​您可以去掉 onsubmit="return false",因为这不起作用。

    编辑:

    我在您的 Ajax 中发现的一个错误。您在 POST 中使用 GET 语法。

    不要在你的 Ajax POST 中使用:var postData = 'username='+username+'&amp;name='+name+'&amp;brand='+brand; 后跟 data : postData,

    相反,在您的 ajax 中使用 data: { username: username, name: name, brand: brand }。对于 POST,不使用 =&amp;

    另外,在 PHP 中:$_POST[username] 是错误的。应该是$_POST['username']

    【讨论】:

    • 我尝试了第二种方法但不起作用,这里 - suppliesprices.com/?page_id=4
    • 结果是什么?对于第一个解决方案,如果失败,您绝对不应该更改页面或刷新此页面。它不会做任何事情,您必须找出代码中还有哪些错误。
    • 我已经更改了 ajax 部分仍然没有运气suppliesprices.com/?page_id=4 ,当我添加它时,php 可以正常工作而没有“'”
    【解决方案2】:

    要向表中添加另一行,您可以使用jQuery append 函数。您可以像这样在成功函数中执行此操作:

    success: function(data,status, xhr)
    {
        //if success then just output the text to the status div then clear the form inputs to prepare for new data
        if (data.status == 'success') {
            $("#status_text").html('DATA SAVED SUCCESSFULLY');
            $('#name').val('');
            $('#brand').val('');
    
            $('.simplet tbody').append('<tr class="odd-row"><td width="30"></td><td>'+data.product.product_name+'</td><td>'+data.product.product_brand+'</td><td>'+data.product.product_quantity+'</td><td>'+data.product.product_link+'</td><td><a class="link-delete" href="#" data-delete-id="' + data.product.id + '">X</a></td></tr>');
        } else {
            $("#status_text").html(data.message);
        }
    },
    

    您将需要更新您的 PHP 代码以返回更多信息。最常见的情况是,您将返回 JSON,其中包含有关事务是否成功的信息以及插入到数据库中的信息的副本(如果失败,则返回错误消息)。您可以执行以下操作:

    if($result){
        $id = mysql_insert_id();
        $retVal = array(
            'status' => 'success',
            'product' => array(
                'id' => $id,
                'product_name' => $_POST['name'],
                'product_brand' => $_POST['brand'],
                'product_quantity' => 0,
                'product_link' => '/?product_id=' . $id // not sure if this is the correct format or not 
            )
        );
    } else {
        $retVal = array(
            'status' => 'error',
            'message' => 'Product could not be inserted'
        );
    }
    
    header('Content-Type: text/json');
    echo json_encode($retVal);
    

    您绝对应该更新数据库代码以遵循更好的安全实践,但这应该可以帮助您入门。

    【讨论】:

    • 当我应用代码时
    • 糟糕,不应该将 $result 传递给 mysql_insert_id()。我编辑了它。试试看。
    • 我的{"status":"success","product":{"id":96,"product_name":"sdf","product_brand":"ffff","product_quantity":0,"product_link":"\/?product_id=96"}} 显示在我的div id="status_text_list" 中,现在将行添加到表中
    • 现在看一下编辑。我从来没有从上面更新你的代码。随意将您想要的任何内容传递到有关成功和失败的状态 DIV 中。以上只是你如何做到这一点的一个例子。
    • 您缺少 if 语句并且没有更改它下面的行。确保您有以“if”开头的行。并确保更新它下面的行以匹配上面的行。
    猜你喜欢
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    相关资源
    最近更新 更多