我可以从html获取文本并将其放入php中的变量而无需提交表单吗?

时间:2014-03-17 08:54:10

标签: javascript php jquery html forms

我在html中有一个表单:

<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>

我希望在php中获取此输入的值,而无需在表单中提交。

这是我的javascript:

var pName= null;
$(document).ready(function(){
    $('img').click(function(){
        pName= $(this).attr("name");
        console.log(pName);
    });
});

我的php:

$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';

我想要的是什么。你点击图片,

1.图片名称属性的值将保存到变量pName(javascript)中,

2.然后进入表单并将表单的值更改为变量pName(javascript),

3.php获取表单的值(现在应该等于pName),

4.然后将其存储到变量$pName(php)中。

5.我还希望$pName(php)在网站的所有页面中全局使用。

修改

这是我的索引页面:

<?php
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
    die('Failed to connect to MySql:'.mysql_error());
}
$query="SELECT * FROM project limit 5 ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
?>
<!DOCTYPE HTML>
<html>
<head>
    <title>Project planner online</title>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script type="text/javascript" src="ppo.js"></script>
    <link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="bgNav">
    <div id="login">
        <a href="register.php">Register</a>
        <a href="login.php">Log in</a>
    </div>

    <nav id="nav">
        <a href="index.php">Home</a>
    </nav>
</div>
<h2 class="titlePage">Home</h2>
<div id="bgTile">
    <?php

    while($row = mysqli_fetch_array($results))
    {
        $project = $row["name"];
        echo nl2br("<a href='project.php'>" ."<img name=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>". "</a>");
    }
    ?>

    <a href="allprojects.php"><div class="tile" id="tileM"><h2>Meer</h2></div></a>

</div>
    <form>
        <label><input type="hidden" name="pNameChange" value=""></label>
    </form>
</body>
</html>

我想要的:点击图片然后你会被发送到项目页面,其中(php)$pName等于(javascript)pName

的值

项目页面:

<?php
$newRecord = null;
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
    die('Failed to connect to MySql:'.mysql_error());
}

//insert into database
if(isset($_POST['insertComments'])){
    include('connect-mysql.php');
    $username = $_POST['username'];
    $comment = $_POST['comment'];
    $sqlinsert = "INSERT INTO user_comments (username, comment, project) VALUES ('$username', '$comment', '$pName')";
        if (!mysqli_query($db_connection, $sqlinsert)){
            die('error inserting new record');
        }
        else{
            $newRecord = "1 record added";
        }//end nested statement

}

//text from database
$query="SELECT * FROM user_comments where project = '$pName' ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);

$query2="SELECT * FROM project where name = '$pName' ";
$results2 = mysqli_query($db_connection,$query2);
$intro2=mysqli_fetch_assoc($results2);


?>
<!DOCTYPE HTML>
<html>
<head>
    <title>Project planner online</title>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script type="text/javascript" src="ppo.js"></script>
    <link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="intro">

</div>
<div id="bgNav">
    <nav id="nav">
        <a href="index.php">Home</a>
        <a class="rightNav" href="register.php">Register</a>
        <a class="rightNav" href="login.php">Log in</a>
    </nav>
</div>

<div id="projectTile">
    <span id="statusCheck"><?php print_r($intro2["status"]); ?></span>
    <h2 id="prTitle"><?php print_r($intro2["name"]); ?></h2>
<div id="prPic"><img width="300" height="200" src="<?php print_r($intro2["image"]); ?>"></div>
<div id="prDescription"><?php print_r($intro2["description"]); ?></div>
</div>
<div id="comments">
    <?php
    while($row = mysqli_fetch_array($results))
    {
        echo nl2br("<div class='profile_comments'>" . $row['username'] . "</div>");
        echo nl2br("<div class='comment_comments'>" . $row['comment'] . "</div>");
    }
    ?>

</div>

<div id="uploadComments">
    <form method="post" action="project.php">
        <label for="name"><input type="hidden" name="insertComments" value="true"></label>
        <fieldset>
            <legend>comment</legend>
        <label>Name:<input type="text" id="name" name="username" value=""></label><br/>
        <label>Comments: <textarea name="comment" id="comment"></textarea></label>
        <input type="submit" value="Submit" id="submitComment">
        </fieldset>
    </form>
</div>
<?php
echo $newRecord;
?>
<form>
    <label><input type="hidden" name="pNameChange" value=""></label>
</form>

</body>
</html>

4 个答案:

答案 0 :(得分:3)

HTML:

你在页面上有超过1张图片吗?如果你在图像中添加ID,它会更好。不需要表单和隐藏字段来完成你想要的工作。

确保您的img具有<img id="imageID"...

之类的ID

JavaScript的:

var pName= null;
$(document).ready(function(){
    $('#imageID').click(function(){
        pName= $(this).attr("name");
        $.post("project.php", { pNameChange: pName },
        function(data) {
            // do something here.
         });
    });
});

上面的代码应该按预期工作。现在在project.php&gt; $ _POST ['pNameChange']应该接收pName的值(图像的名称attr)。

当你在所有页面上全局提供$ pName时,我不明白你想要什么。请进一步详细说明,可以考虑将其存储为cookie / session吗?


编辑:

考虑使用session to pName value ...通过在文件开头简单的启动/恢复会话:

<?PHP
  session_start();

然后......

设置/更新值:

if(isset($_POST["pNameChange"]))
$_SESSION["pName"] = $_POST["pNameChange"];

然后在所有网页上使用$_SESSION["pName"]代替$pName

答案 1 :(得分:0)

在jQuery中尝试Ajax方法,希望它能解决你的问题

https://api.jquery.com/jQuery.ajax/

https://api.jquery.com/jQuery.post/

答案 2 :(得分:0)

实际上,您不需要使用AJAX,index.php所有name都会将图片的project.php传递给index.php,所以请尝试:

<form name='form1' method="post" action='project.php'> <!-- form attributes given --> <label><input type="hidden" name="pNameChange" value=""></label> </form>

var pName= null;
$(document).ready(function(){
    $('img').click(function(){
        //onclick of image, we will save the image name into the hidden input
        //and submit the form so that it goes to project.php
        $('input[name="pNameChange"]').val($(this).attr("name")); 
        $('form1').submit()
    });
});

使用Javascript:

project.php

在您的//now project.php can get the posted value of 'pNameChange' //There is no input field with `name`->`value`, so $_POST['value'] is invalid. $pName = isset($_POST['pNameChange']) ? $_POST['pNameChange'] : '';

{{1}}

如果您需要跨多个页面使用此值,则全局将无效,请使用会话。

答案 3 :(得分:0)

好的,&#34;额外&#34;回答是只关注会话。使用我之前的答案中的客户端代码,并在服务器端尝试此操作。

index.php页面:

<?php
session_start();
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : '';

project.php页面:

<?php
session_start();
$newRecord = null;
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : null;
if(is_null($pName) && isset($_POST['pNameChange'])) {
   $_SESSION['pNameChange'] = $_POST['pNameChange'];
   $pName = $_POST['pNameChange'];
}

希望有所帮助