1

I am trying to send both form data and a POST variable and I have no idea how to do it. I've tried to do this below:

const formthing = document.getElementById("theform");

function submitfunc(e){
e.preventDefault();
const thing = new XMLHttpRequest();
thing.open("POST", "edit.inc.php", true);

thing.onreadystatechange = function(){

if (thing.readyState == 4 && thing.status == 200){
var message = thing.responseText;

 $("#theform").html(message);

}

}

var videoid = "watever";

thing.send(new FormData(formthing), "videoid="+videoid);

}

But it does not work as the php script returns "jo"

<?php
if (isset($_POST['videoid']){

}
else{
echo "jo"
}
?>

When I take a look in network it only looks like it is passing the form: what I see

If anyone has any ideas, feel free to let me know! If anything needs to be made clear, please ask.

SirSpeciam
  • 169
  • 10
  • I would use jquery for everything. This isn't really a PHP question. Probably related thread https://stackoverflow.com/questions/30133599/send-a-form-with-serialize-function-and-extra-data-in-ajax – user3783243 May 16 '20 at 01:47
  • If you want to add data to the FormData object dont pass the creation of it directly to the send call. Meaning save it to a variable, then use FormData's append() method to add your data and pass the variable to send() – Patrick Evans May 16 '20 at 01:56

1 Answers1

0

HTML:

<form id="my-form" action="/" method="post">

  <input type="text" name="videoid"><input type="submit" value="Submit">

</form>

<div id="output"></div>

JS:

let myForm = document.querySelector( "#my-form" );
let output = document.querySelector( "#output" );

myForm.addEventListener( "submit", function(e) {

  e.preventDefault();

  let formData = new FormData( myForm );
  let xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {

    if( this.readyState == 4 && this.status == 200 ) {

      output.innerHTML = this.responseText;

    }

  }

  xhr.open( "POST", "edit.inc.php" );
  xhr.send( formData );

});
DannyXCII
  • 888
  • 4
  • 12
  • This is not OP's issue, and using the variable's name instead of the function's `this` is fine as it is still in scope of the function expression and is not modified to be something else. OP is trying to add post data in the wrong way which your answer does not address – Patrick Evans May 16 '20 at 02:03
  • I was thinking of something else thinking that it would be more secure, but I realized that it doesn't actually matter. I'll use this aproach, thanks! – SirSpeciam May 16 '20 at 02:04
  • 1
    @PatrickEvans This method isn't very clean, but it would give the same outcome. – SirSpeciam May 16 '20 at 02:06
  • @PatrickEvans you are right, I was incorrect in my reasoning, but the code should/does work to perform the expected result as per OP's question – DannyXCII May 16 '20 at 02:07