2015-02-06 55 views
1

我從AJAX調用一個PHP文件,我也想傳遞一個變量。這是我的代碼:將參數從Ajax傳遞到PHP文件

echo "<h4 style='color:white'>Messages</h4>"; 
echo "<textarea cols='50' rows='10' style='font-size: 24px;'></textarea><br><br>"; 
echo "<button id='sendmessage' style='padding:10px'>Submit</button>"; 
echo "<button id='deletemessage' style='margin-left:5px;padding:10px'>Delete</button>"; 


echo "<script> 
    jQuery('#sendmessage').click(function(){ 
     jQuery.ajax({ 
      data: { content: jQuery('textarea').val() }, 
      url:'wp-content/themes/dt-chocolate/postmessages.php', 
      success:function(data){} 
     }); 
    }); 
    </script>" 

和PHP文件:

<?php 
require_once('/opt/lampp/htdocs/mydomain/wp-config.php'); 

$post = array(
     'post_content' => data.content, 
     'post_title'  => "testing", 
     'post_status' => 'publish', 
     'post_type'  => 'post', 
     'post_category' => array(28) // Default empty. 
    ); 



wp_insert_post($post); 
?> 

不過,帖子的內容是「datacontent」,而不是從文本區域的實際文本。我究竟做錯了什麼?

回答

3
echo "<script> 
jQuery('#sendmessage').click(function(){ 
    jQuery.ajax({ 
     data: { content: jQuery('textarea').val() }, 
     url:'wp-content/themes/dt-chocolate/postmessages.php', 
     type: 'POST', 
     success:function(data){} 
    }); 
}); 
</script>"; 

-

$post = array(
    'post_content' => $_POST['content'], 
    'post_title'  => "testing", 
    'post_status' => 'publish', 
    'post_type'  => 'post', 
    'post_category' => array(28) // Default empty. 
); 

.ajaxtype(方法)'POST',然後可以用PHP從$_POST陣列讀取POST請求的變量。

+0

這是工作。我不知道PHP,我試圖用我在Google上發現的所有東西來做到這一點。再次感謝你。由於SE限制,我會在7分鐘內檢查您的答案。 – Tasos 2015-02-06 17:22:02

+0

很酷,謝謝!我很高興它有幫助。 :) – 2015-02-06 17:27:57

2

首先,您可能想使用POST而不是GET。只需將類型:'POST'添加到ajax參數或使用「post()」函數。

在服務器端,應該檢索值的方式是使用$ _GET(或$ _POST)全局變量。你的內容應該在$ _GET ['content']。