Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在使用ajax将记录添加到mysql数据库后重新加载查询,而不重新加载页面_Javascript_Php_Jquery_Mysql_Ajax - Fatal编程技术网

Javascript 在使用ajax将记录添加到mysql数据库后重新加载查询,而不重新加载页面

Javascript 在使用ajax将记录添加到mysql数据库后重新加载查询,而不重新加载页面,javascript,php,jquery,mysql,ajax,Javascript,Php,Jquery,Mysql,Ajax,我有一个页面,用户可以在其中向mysql数据库添加记录。在同一页上,有数据库中现有记录的列表 我使用ajax将记录添加到数据库中,很抱歉,mysql的旧版本会在我首先完成这项工作后更新: $(document).ready(function(){ //on the click of the submit button $("#btn_submit").click(function(){ //get the form values var username = $('#hdn_usernam

我有一个页面,用户可以在其中向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>

品名
烙印
量
价格
删除
[插入]
$current_user=wp_get_current_user();
$username=$current\u user->user\u login;
mysql_connect(“本地主机”、“xxxxx”、“xxxx”)//数据库连接
mysql_选择_数据库(“xxxx”);
$query=“从wp_userdata中选择*,其中username='$username';
$result=mysql\u query($query);
if(!$result){die(“错误数据库请求:
”.mysql_Error());} 而($result_row=mysql_fetch_array($result,mysql_ASSOC)){echo'.$result_row['product_name'.'.'.'.$result_row['product_brand'.].$result_row['product_link'.]; } [/insert_php]
添加产品 品名 烙印
我的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");
}
mysql\u connect(“localhost”、“xxxx”、“xxxx”)//数据库连接
mysql_选择_数据库(“xxxx”);
//插入数据顺序
$order=“插入wp\u用户数据
(用户名、产品名称、产品品牌)
价值观
(“$”发布[用户名]”,
“$”发布[名称],
"(品牌)",;
//在order变量中声明
$result=mysql\u查询($order)//执行命令
如果($结果){
echo(“数据保存成功”);
}否则{
回波(
输入数据失败); }
当我单击Submit按钮,表单值发送到input.php并显示成功消息时,您可以在此处看到它-

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

我想用javascript呈现它并添加到一个成功的ajax调用中,但不确定它是否能工作

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

您可以做两件事

备选案文1:

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

备选案文2:

$("#btn_submit").click(function(event){
  event.preventDefault();
 //get the form values
有关详细信息,请参阅文档。提交按钮的默认操作是转到表单的
操作
属性中定义的页面进行提交(如果未指定
操作
属性,则返回到同一页面)。此调用阻止该默认操作,因此您可以改用Ajax

在表单上,您可以去掉
onsubmit=“return false”
,因为这不起作用

编辑:

我在你的Ajax中发现了一个bug。您正在对POST使用GET语法

不要使用:
var postData='username='+username+'&name='+name+'&brand='+brand
后接
data:postData,
在带有POST的Ajax中

相反,在ajax
数据中使用:{username:username,name:name,brand:brand}
。使用POST时,不使用
=
&


另外,在PHP中:
$\u POST[username]
是错误的。应该是
$\u POST['username']
要向表中添加另一行,可以使用该函数。您可以在成功函数中这样做:

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);
    }
},

您当然应该更新数据库代码,以遵循更好的安全实践,但这应该让您开始。

我尝试了第二种方法,但在这里不起作用-结果是什么?对于第一个解决方案,如果失败,您绝对不应该更改页面或刷新此页面。它不会做任何事情,你必须找出你的代码中还有什么地方有错误。我已经更改了ajax部分,但仍然不走运,当我添加它时,没有“'”php工作正常。当我应用代码时,它会断开。<我收到一些mysql错误提示,不应该将$result传递到mysql\u insert\u id()。我编辑了它。试试看。我的
divid=“status\u text\u list”
中显示了
{“status”:“success”,“product”:{“id”:96,“product\u name”:“sdf”,“product\u brand”:“ffff”,“product\u quantity”:0,“product\u link”:“\/?product\u id=96”}}
,现在添加到表中的行现在查看编辑。我从未从上面更新过你的代码。无论你想要什么,都可以自由地进入成功和失败状态栏。上面只是一个例子,说明了如何做到这一点。您缺少if语句,并且没有更改它下面的行。确保你有以“如果”开头的行。并确保更新它下面的行以匹配上面的行。
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);