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;
    }

?>
1

1 Answer 1

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;
    }

?>
Sign up to request clarification or add additional context in comments.

5 Comments

hmm... I'm retired from php. It worked. Can you explain where I overlook? Because, the name that I got in input is fieldText
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.
which is data: {field: $("input[name=fieldText]").val()},. not data: {fieldText: $("input[name=fieldText]").val()}, Notice the key of your value has changed.
Oh man, you're right! I forgot completely about this. Thank you man
No problem, have a nice day !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.