2016-11-22 47 views
-1

我做了一個wordpress插件,其中我有幾個div。 我想用下面的代碼來獲取div的內容。使用Ajax在wordpress數據庫中存儲html內容

var arhive = j("div.page2").html(); 
        console.log(arhive); 

工作正常,問題是當我試圖將它發送到服務器來更新數據庫與新的內容。

j.ajax({ 
    url: "send_data.php", 
    type: "post", 
    data: {html: arhive} , 
    success: function (response) { 
     // you will get response from your php page (what you echo or print)     
     console.log("success"); 
    }, 
    error: function(jqXHR, textStatus, errorThrown) { 
     console.log(textStatus, errorThrown); 
    } 
}); 

這是我的send_data.php文件的內容。

$var = $_POST["html"]; 



$my_post = array(
     'ID'   => 4137, 
     'post_content' => '$var', 
); 

// Update the post into the database 
wp_update_post($my_post); 
echo "success"; 

我不知道爲什麼,但我得到500錯誤,數據不會存儲任何想法可能會導致此?

This is the error I get

+0

什麼問題?你有沒有試過先編碼'archive'?你有沒有試過像'data:{html:archive}'格式正確地發送它? – Justinas

+0

你好,不,我想我設法做這一步,我的問題可能在PHP方面。在它上面工作。 –

+0

以上評論應該幫助您將格式正確的html代碼格式化爲變量「html」。在PHP上,您可以使用$ _POST [「html」]訪問數據。並將其存儲到數據庫中,您可以檢查此:http://www.w3schools.com/php/php_mysql_insert.asp –

回答

1

你可以設置一個WordPress的行動來處理Ajax調用,然後利用這些數據來將它們存儲到數據庫中:

WordPress的插件內的行動,存儲發佈的數據

add_action('wp_ajax_my_plugin_ajax_store', 'my_plugin_ajax_store_callback'); 

function my_plugin_ajax_store_callback() { 
    $whatever_data = $_POST['whatever']; 

    global $wpdb; // this is how you get access to the database 
    $wpdb->insert("wp_plugin_table", array(
     "whatever" => $whatever_data, 
    )); 

    echo 'Stored: '.$whatever_data; 

    wp_die(); // this is required to terminate immediately and return a proper response 
} 

,您可以設置Ajax調用這樣

jQuery(document).ready(function($) { 
    var data = { 
     'action': 'my_plugin_ajax_store', 
     'whatever': 1234 
    }; 

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php 
    jQuery.post(ajaxurl, data, function(response) { 
     alert('Got this from the server: ' + response); 
    }); 
}); 

有關wordpress ajax調用的更多信息,請參見AJAX in Plugins

相關問題