-1

can anyone help me with this simple code. I get this error:

"Notice: Undefined index: name in C:\xampp\htdocs\test.php on line 2

The id you have entered is "

I would also like to know how to pass multiple values in the ajax statement like:

data: {name: "john", country: "UK"}

Retrieve it on Server side and finally post it back to the initial page.

Client side:

<script>
    $(document).ready(function(){

        $("#btn").click(function(){

            $.ajax({
                type: "POST",
                url: "test.php",
                data: {name: "John"}
            })

            .done(function() {
                $("#output").load("test.php");
           });
        });

     });
 </script>


<form>
    <input type="button" value="Test" id="btn" />
</form>

<div id="output"> </div>

Server side:

<?php
    $student =(string) $_POST['name']; 
    //$student = isset($_POST['name'])?$_POST['name']:'err';
    $message = "Name: ".$student;
    echo ($message);
?>
0

3 Answers 3

5

You are loading the test.php file twice: Once with your POST request, which returns the correct data... but then you are ignoring that data and requesting it again with a GET request, which of course has no POSTdata attached.

Try:

.done(function(data) {
    $("#output").html(data);
});
Sign up to request clarification or add additional context in comments.

Comments

1

Try something like this:

   $("#btn").click(function(){
        $.ajax({
            type: "POST",
            url: "test.php",
            data: {name: "John"},
            success: function(data) {
                $("#output").html(data);
            }
        })

You can also add more data just as you said:

data: {name: "John", country:"UK"}

And in PHP, you'll get them as $_POST['country'].

Comments

1

To pass multiple data items over Ajax from a form you can do this for example which takes the values from the input fields and passes them through:

data: 
    'forename=' + $('#forename').val() +
    '&surname=' + $('#surname').val() +
    '&addressLine1=' + $('#addressLine1').val(),

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.