Devraj Devraj - 6 months ago 7
HTML Question

Undefined index in php when using ajax

My Form page :

<body>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function val()
{
var name=document.getElementById("name").value;
if(name == '')
{
alert(name+" is empty");
}
else
{
var dataString = "name = "+name;
$.ajax({
type:"POST",
url:"hi.php",
data:dataString,
cache:false,
success:function(html){
$('#msg').html(html);
}
});
}
return false;
}
</script>

</head>
<body>
<form>
<input type="text" id="name" >
<br/><br/>
<input type="submit" value ="submit" onclick="return val()">
</form>
<p id="msg"></p>
</body>


Here is my hi.php file

<?php
$name = $_POST["name"];
echo "Response : ".$name;
?>


When clicking on submit button it show an error
Notice: Undefined index: name in C:\wamp\www\SendEmailAjaxJquery\hi.php on line 2


I don't know where is the error plz help me to find out the error...

Thanks in advance

Answer

Use this in place of this

var dataString = "name = "+name;

change into this

var dataString = 'name='+ name;

i have the same case here you will be guided from it.

 <html>
 <head>
  <script type="text/javascript" src="jquery-1.12.3.min.js"></script>
 </head>
 <body>
 <div class="content">
    <input type="text" class="search" id="searchid" placeholder="Search for    people" />
    <div id="result"></div>
 </div>  
 </body> 
 </html>
 <script type="text/javascript">
 $(function(){
  $(".search").keyup(function() 
  { 
    var searchid = $(this).val();
    var dataString = 'search='+ searchid;
    if(searchid!='')
    {
      $.ajax({
      type: "POST",
      url: "result.php",
      data: dataString,
      cache: false,
      success: function(html)
      {
         $("#result").html(html).show();
      }
     });
   }return false;    
   });
Comments