简体   繁体   English

如何将javascript变量传递给php以存储在wordpress数据库中?

[英]How to pass javascript variable to php to store in the database of wordpress?

I am building a star rating system in wordpress and so want to store rating data to wordpress database. 我正在wordpress中建立星级评分系统,因此想将评分数据存储到wordpress数据库中。 I am storing star rating php as a template in wordpress theme folder.Here is the part of the code. 我将星级PHP作为模板存储在wordpress主题文件夹中。这是代码的一部分。

<?php 
/* Template Name: RatingSystem */   
?>

<html>for displaying the stars</html>

<css>for hover and other star rating effects</css>

<script>
var r1;
var r2;
function submitForm() {
$.ajax({
         type: "POST",
         url: 'submit-rating.php',
         data: { r1 : r1 },
         success: function(data)
          {
            alert("success!");
           }
           });
                         }
function RatingValue(rating) 
{r1=rating;}    

function RatingValue1(rating1)
{r2=rating1;}   
</script>

submit-rating.php(PHP file). Submit-rating.php(PHP文件)。

<?php
if(isset($_POST['r1']))
{
$rating = $_POST['r1'];
echo $rating;
}
?>

But when i do echo $rating no output is displayed.Why?Also please explain how to store in wordpress database.Thanks in advance. 但是当我做echo $ rating时没有显示输出。为什么?还请解释如何存储在wordpress数据库中。

Your output isn't displayed because JS doesn't "know" it should display it. 您的输出未显示,因为JS不“知道”它应该显示它。 Instead of 代替

function submitForm() {
    $.ajax({
         type: "POST",
         url: 'submit-rating.php',
         data: { r1 : r1 },
         success: function(data)
         {
            alert("success!");
         }
    });                        
}

try 尝试

function submitForm() {
    $.ajax({
         type: "POST",
         url: 'submit-rating.php',
         data: { r1 : r1 },
         success: function(data)
         {
            alert(data);
         }
    });                        
}

The data in function(data) is the response the JS gets. datafunction(data)是JS获得响应。 In order to show it in a div, you could use $('#divID').html(data) where the alert is. 为了将其显示在div中,您可以使用$('#divID').html(data) alert所在的位置。

-- Edit: forgot the second part of your question. -编辑:忘记了问题的第二部分。

I recommend you use WPDB for posting your data in your wordpress database. 我建议您使用WPDB将数据发布到wordpress数据库中。 This is possible if this PHP file is part of the template, or if you have turned off the template engine for that file and required the wp_load.php. 如果此PHP文件是模板的一部分,或者您已关闭该文件的模板引擎并需要wp_load.php,则可以这样做。 If neither of these apply, I recommend you do the latter by including this at the top of your php file 如果以上两种方法均不适用,我建议您通过在php文件顶部包含此内容来进行后者

// Include WordPress
define('WP_USE_THEMES', false);
require_once('PATH/TO/wp-load.php');

Information on WPDB and how to use it can be found here . 有关WPDB及其使用方法的信息, WPDB参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM