0

I'm trying to test this out with my code, and it's grabbing it as undefined.

I'm posting this because my reputation isn't at 50. I'm trying to test what this person was saying: https://stackoverflow.com/a/24310507/11852136 .

As summarized, it clearly echos it out, but when I try grabbing the value, it comes back as undefined.

file bin/A.php:

<?php
$fname = $_POST["fname"];
$SomethingElse = '';
$TestGrab = 'MEHOY MENOY!';

echo "Hi ".$fname."!";
echo nl2br ("\n");
?>
<input type="hidden" id="Error" value="<?php echo $TestGrab ?>" />

file B.js:

$.ajax({ type:'POST',
   url: 'location/bin/A.php',
   data:{fname:fname},
   success: function(data){
      console.log(data);
      var grabbing = $("#Error").val();
      console.log("Error: " + grabbing);
   }
});

What I expected it to do was for console.log("Error: " + grabbing); to output to the console Error: MEHOY MENOY!, but instead it gives me Error: undefined. Can I have some instructional help?

karel
  • 5,489
  • 46
  • 45
  • 50
  • Sorry, typo. I fixed that. – ThatDummyOverThere Aug 09 '19 at 15:54
  • 1
    you need to put response from ajax to some `
    ` then get value of `#Error`
    – Swati Aug 09 '19 at 15:55
  • Please check with `var grabbing = $(data).find("#Error").val();` or `var grabbing = $(data).val();` – Wang Liang Aug 09 '19 at 15:57
  • You also need a `;` in your `echo` part else PHP will error. So change `` to `` – GBWDev Mar 02 '20 at 15:11
  • @GBWDev No, it's not necessary if the php tags contain only one command (generally, the last command in between php tags does not need the terminator), which is the case here. – El_Vanja Mar 02 '20 at 15:27
  • @El_Vanja you are right, but as far as you know its the last one.. but it might not be – GBWDev Mar 02 '20 at 15:31
  • @GBWDev I'm going by the posted example. It's clearly the only command between the tags. It's not a bad practice to add it, I just wanted to point out that it will not error. – El_Vanja Mar 02 '20 at 15:33
  • @ThatDummyOverThere Have you linked to the proper answer in that other question? Because you're saying you want to test what that person said, but the linked answer didn't use ajax. – El_Vanja Mar 02 '20 at 15:34
  • Use your browser debugger to see exactly what PHP is sending. You'll get the exact string back in `data` but that will not have anything to do with subsequent attempts to find `$("#Error")` because the contents of `data` are not part of the DOM. Traditionally, you send the response back JSON-encoded. – Mike Robinson Mar 02 '20 at 16:31

0 Answers0