2017-09-13 71 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

感谢您的答案我想出了问题,我可以将该变量存储到会话相同,我为登录会话谢谢让我知道。谢谢 –