dongyulan6251 2015-07-09 14:40
浏览 49
已采纳

too long

The code snippet for the jQuery function looks like:

function addMessage() {
    if (textval != "") {
        text_string='<div class="alert-box round"><p class="text-left">' + userName + ':' + textval + '</p></div></br>';
        alert(text_string);
        $.ajax({
            type:"POST",
            url:"process.php",
            data: {'text_string': text_string},
            cache:false,
            success:function(){
                alert("submitted")
            }
        });
        $("input[type=text]:last").val("");
    }
    enterButton = 0;
}

The process.php code looks like:

<body>
    <?php 
        //$host = "localhost";
        $text_string=$_POST['text_string'];
        echo "string submitted is".$text_string;        
    ?>
</body>

I get alerts showing value of text_string and then the "submitted", but when I open the php page, it shows an error:

Undefined index: text_string

I've seen various answers, none of them seem to be the case for mine. Is the problem in PHP code or jQuery code or both?

  • 写回答

1条回答 默认 最新

  • dougu3290 2015-07-09 15:09
    关注

    If you want to save the value passed by the AJAX request for the next time you load "process.php", try saving it in the session. So, you could change your code to:

    <?php
        session_start();
    
        // Store value in session if it is passed
        if (isset($_POST['text_string'])){
            $_SESSION['text_string'] = $_POST['text_string'];
        }
        // Read and echo value from session if it is set
        else if (isset($_SESSION['text_string'])){
            $text_string=$_SESSION['text_string'];
            echo "string submitted is".$text_string;
        }
    ?>
    

    Now, your PHP script will store the passed value in the session, and will echo that stored value should you load the page elsewhere. (Another alternative is to store the value in a database...though I'm not sure if you have one set up at the moment.)

    Hope this helps! Let me know if you have any questions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件