在Wordpress中使用php和Ajax将数据插入mysql数据库 [英] Insert data into mysql database with php and ajax in wordpress

查看:60
本文介绍了在Wordpress中使用php和Ajax将数据插入mysql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

inside my function.php I added new top level admin menu. I added input fields and inside it and put it into html form element.

<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的可能性.因此,我想在提交点击时将输入字段添加到数据库中.

Then I added php where I call ajax via ajax-admin.php and gives user possibility to use ajax. So I want to add input fields into database on submit click.

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请求:

And I made .js file to proccess ajax request:

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

}); 

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

Page reloads and nothing happens...

有任何提示吗?

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

I succeed to call ajax and added 3 echo-s to my php so I can get response via server.

$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,我都会得到其他部分.我尝试了所有3种状态,即php可以返回js,但总是可以执行.

So whatever I enter in my input fields and post to php I got this else part. I tried with all 3 states that php can return to js but always else get executed.

现在有提示吗?

推荐答案

使用html将表单命名为-

Name your form in html as -

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

先尝试 JSON.stringify()数据,然后再使用AJAX发送,如下所示-

Try JSON.stringify() data before sending with the AJAX like below -

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

然后将您的ajax调用替换为以下提交的表单-

And then replace your ajax call on form submit as below-

$('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();
   }
  });

});

希望这会有所帮助.

这篇关于在Wordpress中使用php和Ajax将数据插入mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆