【问题标题】:I want to get $username variable from another page using ajax我想使用 ajax 从另一个页面获取 $username 变量
【发布时间】:2017-09-13 05:10:39
【问题描述】:

这是我的 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 并将其分配给senpost.php 页面中的$user_posted_to 变量,然后使用javascript 插入到数据库中,如果有任何专家可以提供帮助,我会非常感激我尝试过@ 987654328@ 但那也不起作用 this.value 也不起作用 我无法从该页面获取用户名 谁能帮我解决这个问题 我要获取的用户名变量是我要分配给的用户配置文件的用户名$user_poste_to

【问题讨论】:

  • 请在您点击“发送”的地方修改 HTML
  • 好的,我一会儿贴出来

标签: javascript php mysql ajax fetch


【解决方案1】:

我相信,访问 $username 值的最佳方法是将其存储到 cookie,一旦您在 senpost.php 中,您所需要做的就是获取您存储的 cookie 并将其分配给$user_posted_to 变量。使用 $(input[type="text"]).val() 获取文本框/表单元素值的正确方法

【讨论】:

  • 感谢您的回答我发现了问题我可以将该变量存储到一个会话中,就像我为登录会话所做的一样感谢您让我知道。非常感谢
【解决方案2】:

更新您的 AJax 调用。

data: {username:username},

这里第一个用户名是索引,第二个用户名是你使用$(this).val()得到的变量

【讨论】:

  • 我更新了它,但它说未定义索引,因为它不是从文本字段中获取的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-22
  • 2013-02-13
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多