Alexander Langanke
Alexander Langanke

Reputation: 71

Transmitting Form Data via Json

I believe I am making a very basic mistake somewhere.

I have a Form I want to transmit to a PHP page. I also want to send a parameter with that information so I have created a basic 2D array: $fd['api'] -> contaning the parameter as a string $fd['body'] -> containing the form data

I am struggling to transmit this array "$fd" as a json string and believe I am using the javascript syntax incorrectly somewhere as I do not often use Javascript.

Any Help would be appreciated.

function admin_statistics_form_send(){
  var fd = []
  fd['api'] = "refresh_all"
  fd['body'] = new FormData(document.getElementById("admin_statistics_form"))
  var jsonstring = fd
  console.log(jsonstring)
  $.ajax({
    async: true,
    beforeSend: function(){
    },
    url: "admin_statistics_api.php",
    type: "POST",
    data: jsonstring,
    dataType: "json",
    processData: false,  // tell jQuery not to process the data
    contentType: false,   // tell jQuery not to set contentType
    success: function (data) {
        console.log(data)
    },
    error: function(data) {
        console.log(data)
    }
  })
}

Upvotes: 1

Views: 39

Answers (1)

charlietfl
charlietfl

Reputation: 171698

You only want to send the FormData object. To add other key/value pairs you append to that object:

function admin_statistics_form_send(){
  var fd = new FormData($("#admin_statistics_form")[0]);
  fd.append('api',"refresh_all");


  $.ajax({
    //async: true, // redundant since it is default and should never use `false`
    beforeSend: function(){
    },
    url: "admin_statistics_api.php",
    type: "POST",
    data: fd,
    dataType: "json",
    processData: false,  // tell jQuery not to process the data
    contentType: false,   // tell jQuery not to set contentType
    success: function (data) {
        console.log(data)
    },
    error: function(data) {
        console.log(data)
    }
  })
}

Upvotes: 2

Related Questions