0

I know how to use jQuery:

$.ajax({
  method: 'POST',
  url: 'send-data-to.php',
  data: {data:"data"}
})

but how do I send data accessible via $_POST with pure JS? The reason I'm asking this is because I followed a YouTube tutorial for an Ajax file upload but I also want to send more data along with it (and I don't know how to do it with pure JS).

Here's the main part of it.

JS

function uploadFile(e) {
    e.preventDefault();
    var file = document.getElementById('upload-btn').files[0];
    var formdata = new FormData();
    formdata.append("file1",file);
    ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress",progressHandler,false);
    ajax.addEventListener("load",completeHandler,false);
    ajax.addEventListener("error",errorHandler,false);
    ajax.addEventListener("abort",abortHandler,false);
    ajax.open("POST","upload_file.php");
    ajax.send(formdata);
}

HTML

<form method="post" enctype="multipart/form-data" onsubmit="uploadFile(event);">
    <input class="next-btn" type="submit" value="Upload!">
    <input type="file" name="file1" id="upload-btn" onchange="showImage(this);">
</form>

The data I want to send would be like this using using jQuery:

data: {var1:var1,var2:var2,var3:var3} etc

1 Answer 1

1

See this example

var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

From Send POST data using XMLHttpRequest

Sign up to request clarification or add additional context in comments.

3 Comments

Ah, I see. I can just keep appending it on to the formdata variable.
Okay, though the real answer was the second one for me (in that link, not the one you pasted) :D
@frosty anyway this act would be appreciated :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.