Home > Net >  Ajax not passing correct data to $_POST on responding php page
Ajax not passing correct data to $_POST on responding php page

Time:12-22

I've got an ajax function:

$('#addSiteButton').on('click',function() {
  let addSiteOption = $('#enterNewWebsiteLink').val();
  const form = new FormData();

 form.append('addSiteOption', addSiteOption);

 $.ajax({
  url: "includes/submit_site.php",
  data: { 'data': form },
  method: "POST",
  contentType: false,
  processData: false,
  enctype: false,
  cache: false,
  datatype: "text",

 success: function (response, data) {
  }
});

My PHP file looks just like this:

if (isset($_POST['data'])) {
 $websitelink = $_POST['addSiteOption'];
}

my HTML looks like this:

<input type="url" form="addsite"  
  id="enterNewWebsiteLink"
  name="enterwebsitelink"
  placeholder="Enter A New Website">

The error that I am getting is: Warning: Undefined array key "data" I've tried outputting the variable addSiteOption and it outputs the URL correctly.

The frustrating thing, I've been checking/copying this against a previous project I did that I got it working in, and I can't make any difference between them now.

I get a 200 response from the server for the page.

CodePudding user response:

You can't serialize FormData, and processData: false tells jQuery not to try to serialize the data: option.

You should just pass the FormData as the data: option. Then the keys of the FormData will become the $_POST keys.

JS:

$('#addSiteButton').on('click',function() {
  let addSiteOption = $('#enterNewWebsiteLink').val();
  const form = new FormData();

 form.append('addSiteOption', addSiteOption);

 $.ajax({
  url: "includes/submit_site.php",
  data: form,
  method: "POST",
  contentType: false,
  processData: false,
  enctype: false,
  cache: false,
  dataType: "text",

 success: function (response, data) {
  }
});

PHP:

if (isset($_POST['addSiteOption'])) {
 $websitelink = $_POST['addSiteOption'];
}

You also had a typo: datatype: should be dataType:

  • Related