user2406852
user2406852

Reputation: 13

How to ajax POST to php page and return output of PHP page?

I have the following code to ajax a POST request to my test.php file. I then want to load the output of the test.php into <div id="here"></div>.

My test.php file has the following:

var_dump($_POST);
die();

Here's the jQuery:

<script type="text/javascript">
$(document).ready(function(e)
{
    $('#here').find('a').on('click', function(e) // listens for <a href> click
    {
        e.preventDefault();
        $.ajax({
              type: "POST",
              url: "test.php",
              data: { foo: "bar", working: "yes" }
            })
        $('#here').load('test.php');    // get the output of test.php
    });
});
</script>

I'm getting an empty $_POST array back from the test.php page. What am I doing wrong?

Upvotes: 0

Views: 750

Answers (2)

chofer
chofer

Reputation: 357

$('#here').find('a').on('click', function(e) // listens for <a href> click
{
    e.preventDefault();
    $.ajax({
          type: "POST",
          url: "test.php",
          data: { foo: "bar", working: "yes" },
          success: function(result){
                    $('#here').html(result);
             }
        })  
});

You need to add success function in your ajax to get the result

Upvotes: 0

Yang
Yang

Reputation: 8701

You should write it this way:

    $.ajax({
          type: "POST",
          url: "test.php",
          data: { foo: "bar", working: "yes" },
          success : function(response) {
               $('#here').html(response);
          }
        });

Because $.load() method invokes a GET query by default. And also there's no point of calling ajax twice.

Upvotes: 1

Related Questions