简体   繁体   English

尝试将值从Jquery传递到PHP时未定义的索引名称

[英]Undefined Index Name when trying to pass values from Jquery to PHP

So, I'm working on figuring out how to post data from Jquery to PHP, And as much as I follow the examples I've found on the threads here, I keep getting an "Undefined Index Name" error. 因此,我正在研究如何将数据从Jquery发布到PHP,并且按照我在这里的线程中发现的示例进行操作,我一直在收到“未定义的索引名称”错误。

My code thus far for the JQuery side is 到目前为止,我在JQuery端的代码是

<script src="jquery-1.11.1.min.js"></script>
</script>
<script>
$(document).ready(function(){
     $("#div2").text('Hey');
    $("#div1").load('testFile.txt');
    setInterval(function() {
    $.ajax({ url: 'script.php' });
    $("#div1").load('testFile.txt');}
    ,100);



  });
  function sub(){

     var msg = $("#name").val();

     $.post('chat.php',{'name':"1234"},function(){
$("#div2").load('chat.php');
});  
 };

</script>

The html forms and buttons I'm using 我正在使用的HTML表单和按钮

<div id="div1"></div>
<div id="div2">Um</div>

<form name="myForm" id="myForm" action="" method="POST">
<input type="text" name="name" id="name" size="30" value=""/>
</form>
<button id="submission" onclick="javascript:sub();">Errrr</button>

And the PHP side I'm going to 而PHP方面,我要

<?php
echo $_POST['name'];
 $myFile = "testFile.txt";
 $fh = fopen ($myFile, 'a+') or die("Cannot Open File");
 fwrite ($fh, $_POST['name']);
 fclose($fh);

?>

I'm about at a loss from where to do. 我对从哪里做起感到茫然。 All files are within the same folder and filenames are correct as far as I can find. 据我所知,所有文件都在同一个文件夹中,并且文件名正确。

Your issue is most likely that you're doing this: 您的问题很可能是您正在执行此操作:

$.post('chat.php',{'name':"1234"},function(){
    $("#div2").load('chat.php');
});  

You're effectively sending the data {'name': '1234'} to the file and then just loading the file? 您是在有效地将数据{'name': '1234'}发送到文件,然后才加载文件吗? You'll get the error because you load() the file without sending it params. 您将收到错误,因为您在不发送参数的情况下load()了文件load()

Looking at the jQuery.post manual, you'd see that you can get a response with something like this: 查看jQuery.post手册,您会看到类似以下内容的响应:

$.post('chat.php',{'name':"1234"},function(data){
    console.log(data);
}); 

While you use something like echo or print to effectively "return" content to the ajax call. 当您使用echoprint内容有效地将内容“返回”给ajax调用时。

<?php
echo $_POST['name'];
?>

Now check in your console and see if there is a response. 现在,在控制台中检查是否有响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM