php - 在wordpress中使用php和ajax将数据插入mysql数据库

标签 php mysql ajax wordpress

在我的 function.php 中,我添加了新的顶级管理菜单。我在其中添加了输入字段并将其放入 html 表单元素中。

<form id="prices_form" method="post" action="">
    <div style=font-weight:bold;font-size:16px;>Location 1</div>
    <input id="location1" name="location1" type="text" />
    <input type="hidden" name="count" value="1" />
    <div style=font-weight:bold;font-size:16px;>Location 2</div>

    <input class="input" id="location2" name="location2" type="text" placeholder="Type something"/>
<div style=font-weight:bold;font-size:16px;>Price(KN)</div>
<input type="number" id="price" name="price" min="0" step="0.01"/><br>
<input id="submit" name="submit" type="submit" value="Save prices" />
</form>

然后我添加了 php,通过 ajax-admin.php 调用 ajax,并为用户提供了使用 ajax 的可能性。所以我想在提交点击时将输入字段添加到数据库中。

function ajax_savePrice(){
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $location1 = $_POST['location1'];
    $location2 = $_POST['location2'];
    $price = $_POST['price'];

    $result = $conn->query("SELECT * FROM prices WHERE location1 = '$location1' AND location2='$location2' OR location1 = '$location2' AND location2='$location1'");
    $row_count = $result->num_rows;
    if ($row_count >= 1) {
        echo 'That locations are already inserted. Do you want to update price?';
    } else {
        $query = "INSERT INTO prices (location1, location2, price) VALUES(?, ?, ?)";
        $statement = $conn->prepare($query);

        //bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
        $statement->bind_param('ssi', $location1, $location2, $price);

        if ($statement->execute()) {
            print 'Success! ID of last inserted record is : ' . $statement->insert_id . '<br />';
        } else {
            die('Error : (' . $conn->errno . ') ' . $conn->error);
        }
        $statement->close();
    }

}

function ajax_savePrice_init(){

wp_register_script('ajax-savePrice-script', get_template_directory_uri() . '/ajax-savePrice-script.js', array('jquery') ); 
wp_enqueue_script('ajax-savePrice-script');

wp_localize_script( 'ajax-savePrice-script', 'ajax_savePrice_object', array( 
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending data, please wait...')
));

// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxsavePrice', 'ajaxsavePrice' );
add_action( 'wp_ajax_ajaxsavePrice', 'ajaxsavePrice' );
}
add_action('init', 'ajax_savePrice_init');

我制作了 .js 文件来处理 ajax 请求:

jQuery(document).ready(function($) {

// Perform AJAX login on form submit
$('#prices_form').on('submit', function(e){

$.ajax({
    type: 'POST',
    dataType: 'json',
    url: ajax_savePrice_object.ajaxurl,
    data: { 
        'action': 'ajaxsavePrice', 
        'location1': $('#location1').val(), 
        'location2': $('#location2').val(), 
        'price': $('#price').val() },
    success: function(data){
        $('#prices_form').hide();

    }
});
e.preventDefault();
});

}); 

页面重新加载但没有任何反应...

有什么提示吗?

编辑:

我成功调用了 ajax 并向我的 php 添加了 3 个 echo-s,以便我可以通过服务器获取响应。

$result = $conn->query("SELECT * FROM prices WHERE location1 = '$location1' AND location2='$location2' OR location1 = '$location2' AND location2='$location1'");
        $row_count = $result->num_rows;
        if ($row_count >= 1) {
           // echo 'That locations are already inserted. Do you want to update price?';
            echo 'exist';
        } else {
            $query = "INSERT INTO prices (location1, location2, price) VALUES(?, ?, ?)";
            $statement = $conn->prepare($query);

            //bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
            $statement->bind_param('ssi', $location1, $location2, $price);

            if ($statement->execute()) {
               // print 'Success! ID of last inserted record is : ' . $statement->insert_id . '<br />';
                echo 'yes';
            } else {
                //die('Error : (' . $conn->errno . ') ' . $conn->error);
                echo 'no';
            }
            $statement->close();
        }

现在在我的js中:

    location1=$("#location1").val();
    location2=$("#location2").val();
    price=$("#price").val();
data: "location1="+location1+"location2="+location2+"price="+price,
        success: function(html){
          if(html==='exist')
          {
            $("#prices_form").fadeOut("normal");        
          }
          else
          {
               $("#aaa").fadeOut("normal"); 
          }
        },
        beforeSend:function()
        {

        }
    });
     return false;
    });

所以无论我在输入字段中输入什么并发布到 php,我都会得到这个 else 部分。我尝试了所有 3 个状态,php 可以返回 js,但总是被执行。

现在有什么提示吗?

最佳答案

将您的 html 表单命名为 -

<form id="prices_form" name="pricesForm" method="post" action=""> 

在使用 AJAX 发送数据之前尝试 JSON.stringify() 数据,如下所示 -

var data = JSON.stringify({ 
    action: 'ajaxsavePrice', 
    location1: $('#location1').val(), 
    location2: $('#location2').val(), 
    price: $('#price').val() 
});

然后替换表单提交上的 ajax 调用,如下所示 -

$('form.pricesForm').on('submit', function(e){
  e.preventDefault();
  $.ajax({
   method: 'POST',
   dataType: 'json',
   url: ajax_savePrice_object.ajaxurl, // also check this if it returns the correct url
   data: data,
   success: function(res){
     $('#prices_form').hide();
   }
  });

});

希望这有帮助。

关于php - 在wordpress中使用php和ajax将数据插入mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33986206/

相关文章:

php - 从服务器设置图像后如何刷新 ImageView 在我的情况下,它不更新 ImageView

javascript - 如何在 ajax 上传递带有表单序列化数据的附加数据?

php - 表单不将数据保存到 MySQL 数据库

php - 在 MongoDb 中生成用户友好的 id

javascript - 数据表和ajax数据格式化?

java - 无法通过 SSL 连接使用 JOOQ 和 MySQL 数据库生成代码

php - 2关于更好优化数据库设计的问题

c# - MVC 配置种子方法未插入指定的主键

java - SpringMVC之clientSide view技术处理JsonResponse

php - 如何在php网页中获取iframe的颜色?