简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM