0

It's a very simple code, I was trying to do an ajax submit to work. Until here, ajax is working correct, but Why cannot print out $_POST data?

console.log

<br /> <b>Notice</b>: Undefined index: fieldText in <b>C:\xampp\htdocs\rajax.php</b> on line <b>4</b><br />

sendajax.php

<form method="POST">
    <input type="text" name="fieldText" value="">
      <button type="submit" id="save">Send</button>     
</form>

<script type="text/javascript">
    $(document).ready(function(){
        //alert("Jquery's Working");
        $("#save").click(function(e){
            e.preventDefault();
            //alert("Click Event is working");
            $.ajax({
                type:"POST",
                url:'rajax.php',
                data: {field: $("input[name=fieldText]").val()},
                success: function(result){
                    console.log(result);
                    //alert($("input[name=fieldText]").val()); #Print Value is working
                },
                error: function(result){
                    console.log(result);
                }
            });
        });

    });
</script>

recajax.php

<?php 

    if($_SERVER["REQUEST_METHOD"]=="POST"){
        $test = $_POST['fieldText'];
        echo $test;
    }

?>
Shinomoto Asakura
  • 1,473
  • 7
  • 25
  • 45
  • 4
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – Scuzzy Jul 01 '18 at 23:25

1 Answers1

2

That's because your variable name isn't fieldText, it's field. try changing it in your PHP.

<?php 

    if($_SERVER["REQUEST_METHOD"]=="POST"){
       $test = $_POST['field'];
       echo $test;
    }

?>
Nicolas
  • 8,077
  • 4
  • 21
  • 51
  • hmm... I'm retired from php. It worked. Can you explain where I overlook? Because, the name that I got in input is `fieldText` – Shinomoto Asakura Jul 01 '18 at 23:16
  • 1
    Yea but you passed it as `field` in your data attribute. the `$_POST` variable is an associative array (in your case), and it reflect the value of the `data` attribute of your AJAX call. – Nicolas Jul 01 '18 at 23:17
  • which is `data: {field: $("input[name=fieldText]").val()},`. not `data: {fieldText: $("input[name=fieldText]").val()},` Notice the key of your value has changed. – Nicolas Jul 01 '18 at 23:17
  • Oh man, you're right! I forgot completely about this. Thank you man – Shinomoto Asakura Jul 01 '18 at 23:35
  • 1
    No problem, have a nice day ! – Nicolas Jul 01 '18 at 23:37