2017-09-13 73 views
-3

這是我的Ajax代碼從另一個頁面獲取$ username變量:我想用ajax

$(document).ready (function() { 
    $("#send").click (function() { 
    var username = $(this).val(); 
    alert (username); 
    $.ajax({ 
     url : "sendpost.php", 
     type: 'POST', 
     async: false, 
     data: {username}, 
     success: function(datat){} 
     }) 
    }); 
}); 

這是我的PHP代碼

include ('connection_socio.php'); 
if(isset($_POST['body'])) 
{ 
    $body=mysqli_real_escape_string($db, $_POST['body']); 
    $date_added="123"; 
    $added_by="123"; 
    $username = mysqli_real_escape_string($db, $_POST['username']); 
    $check = "SELECT * FROM users"; 
    $result_profile = mysqli_query($db, $check);  
    //check whether the no of rows in users table is more than 0 

    //get username from database 
    $getusername = mysqli_fetch_assoc($result_profile); 
    $user_posted_to = $username; 
    echo $user_posted_to; 
    $query_post = "INSERT INTO posts VALUES ('', '$user_poste_to',)";     
    mysqli_query($db, $query_post); 
    echo "POSTED SUUCESSFULLY"; 
} 

這是我的profile.php代碼:

if (isset($_GET['u'])) 
{ 
    $username = mysqli_real_escape_string($db, $_GET['u']); 
    //checks and remove symbols like # , ' etc 
    if(ctype_alnum($username)) 
    { 
     //check user existance 
     $check = "SELECT * FROM users WHERE username='$username'"; 
     $result_profile = mysqli_query($db, $check);  
     //check whether the no of rows in users table is more than 0 
     if(mysqli_num_rows($result_profile) == 1) 
     { 
      //get username from database 
      $getusername = mysqli_fetch_assoc($result_profile); 
      $username = $getusername['username']; 
     } 
     else 
     { 
      echo "User dont exist"; 
      exit(); 
     } 
    } 
} 

我想要的是從profile.php頁獲取變量$username並將其分配給$user_posted_to變量在senpost.php頁面,並插入到數據庫使用JavaScript,如果任何專家可以幫助將真正感激它,我已經嘗試this.attr()但那不工作也也無法正常工作我無法從該頁面獲取用戶名可以任何人都可以幫助我這個我想要獲取的用戶名變量是我想要分配的用戶個人資料的用戶名$user_poste_to

+1

請點擊「發送」的psot HTML – mplungjan

+0

Ok I將在一段時間後發佈它 –

回答

-1

更新您的AJax呼叫。

data: {username:username}, 

在這裏第一次用戶名將會是指數和2名會是你得到了使用$(this).val()

+0

我更新了它,但它說未定義的索引,因爲它不是從文本字段獲取 –

2

我認爲,最好的方式來訪問$用戶名的值,將其存儲到cookie變量,一旦你在senpost.php中,你所需要做的就是獲得你存儲的cookie並將它分配給$ user_posted_to變量。通過使用這個$(input [type =「text」])來獲取文本框/表單元素的值的正確方法:val()

+0

感謝您的答案我想出了問題,我可以將該變量存儲到會話相同,我爲登錄會話謝謝讓我知道。謝謝 –