Adam
Adam

Reputation: 455

Sending data using Ajax data not sending to PHP

I'm trying to use Ajax to send some form data, but on the PHP page it's not echoing. I'm new to Ajax so not sure if I have done something wrong with it.

Here's what I have:

$(function () {

    $('form').on('submit', function (e) {

      e.preventDefault();

      $.ajax({
        type: 'post',
        url: 'two.php',
        data: $('form').serialize(),
        success: function () {
          alert('form was submitted');
        }
      });

    });

  });

One of the form fields has a name="selection" and id="selection" but in two.php all I'm trying to do is simply:

echo $_POST['selection'];

But nothing is set.
Any ideas?

Upvotes: 0

Views: 43

Answers (1)

Michael Doye
Michael Doye

Reputation: 8171

You should be passing your response (from two.php) to your success callback:

    success: function ( response ) {
      alert( 'Submitted data: ' + response );
    }

Which should work provided selection is actually set. (check in your console under network requests to confirm this)

Also, consider adding an error callback:

  error: function( response, errorThrown ){
      alert( 'request failed: ' + errorThrown );
  }

to report back any ajax errors.

Upvotes: 1

Related Questions