-1

I am trying to access my data being sent through ajax and I am returning my echo statements, but not what I am passing, what am I doing wrong?

$.ajax({
  url: 'http://www.example.php',
  data : { 'foo' : 'bar', 'bar2' : 'foo2' },
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    console.log('success data '+data);
  }
});

 $data = $_POST['foo'];
 $data2 = $_POST['bar2'];
echo('almost');
echo($data);
echo($data2);
echo('almost');

console reads success data almostalmost

Joshua W
  • 1,537
  • 2
  • 12
  • 15

1 Answers1

1

Your ajax request is incorrect, you're telling jQuery.ajax not to process your data and send it as is, which wont work

$.ajax({
  url: 'http://www.example.php',
  data : { 'foo' : 'bar', 'bar2' : 'foo2' },
  type: 'POST',
  success: function(data){
    console.log('success data '+data);
  }
});

Your sever side script is expecting application/x-www-form-urlencoded content type this is what jQuery.ajax does by default, but not if you tell it not to process the data or set a content type.

Musa
  • 96,336
  • 17
  • 118
  • 137
  • File upload use `multipart/form-data` not `application/x-www-form-urlencoded`. If you want to upload a file with ajax you'll have to use a FormData object with process data and content type turned off. – Musa Aug 31 '14 at 23:27