2

I have no idea why I am getting this weird error!

PHP Notice: Undefined index: refId in /var/www/echo.php on line 5

I am getting Console output, but cant echo refId. Have I done anything wrong here?

<?php
    $rollUrl = 34;
    $refId = $_POST['refId'];
    echo $refId;
?>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $.ajax({
        url:'echo.php',
        type: 'POST',
        data: { 'refId': "<?php echo $rollUrl ?>" },
        success: function(response){
            console.log('Getting response');
        }
    }); 
</script>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Abhishek Kaushik
  • 1,121
  • 1
  • 13
  • 17
  • If that's all one file, then the `$_POST` is getting referenced before a POST is sent. Add a conditional around that block to check `if (count($_POST) > 0)` –  Jun 23 '14 at 06:56

2 Answers2

1

Please see the comments in the code below:

<?php
$rollUrl = 34;

//Only try to process POST if there is something posted *and* refId exists
if (count($_POST) > 0 && isset($_POST['refId'])) { 
  $refId = $_POST['refId'];
  echo $refId;
  //Exit after echoing out the refId so that the HTML below does not also get returned.
  exit();
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $.ajax({
        url:'echo.php',
        type: 'POST',
        data: { 'refId': "<?php echo $rollUrl ?>" },
        success: function(response) {
            //Updated log to show the actual response received.
            console.log('Getting response of "' + response + '"');
        }
    }); 
</script>

That works for me when I tested without any errors being thrown and the Ajax being executed.

  • Miller..! I ran the same code u suggested..! Infact copied pasted it..! But not getting echo. :( – Abhishek Kaushik Jun 23 '14 at 07:40
  • If it was from before my edit, try again. I had the file named diff on my system. If it was after, be sure you're in the console or change it to an alert. –  Jun 23 '14 at 07:42
  • yeah..! i changed the file name..! that is ovious. Were u getting echo value?? – Abhishek Kaushik Jun 23 '14 at 08:37
  • "Not working" is the only explanation which "never works" The script *does* "work" as you have requested, it *does* return the POST'ed refId. If you are having difficulty experiencing that, then more detail is needed. BTW: exclamation points are rarely needed on SO to make your point... no one can hear you scream in cyberspace. ;) –  Jun 23 '14 at 13:00
  • Dude..! chill..! its fine now..! I hv fixed it. Thanks anyways..! – Abhishek Kaushik Jun 23 '14 at 13:06
0

This is happening because your variable is not set. Use isset

<?php

$rollUrl=34;
if(isset($_POST['refId'])) {
$refId=$_POST['refId'];
echo $refId;
}

?>

Update: You should assign the refId as a name attribute to any input field to revive the input from user.

<input type="text" name="refId" />
Moeed Farooqui
  • 3,604
  • 1
  • 18
  • 23