How to send file and input field using JavaScript and Ajax to send PHP script

Please someone should show me how to do this using javascript. because I use javascript and ajax to load the page that will load, and then after using javascript and ajax to send the form to a PHP script

function AddMultipleContact(){ var xmlhttp; if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } var url = "url.php"; var group = document.getElementById("select-input").value; var file = document.getElementById('file-name').files; var variables = "select-input="+group+"&file-name="+file; xmlhttp.open("POST", url, true); // Set content type header information for sending url encoded variables in the request xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // Access the onreadystatechange event for the XMLHttpRequest object xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { var data = xmlhttp.responseText; document.getElementById("flash-message").innerHTML = data; } } xmlhttp.send(variables); // Actually execute the request 

}

+6
source share
1 answer

Files, as a rule, are data, like binary or anything at all, it cannot simply be sent as a query string and concatenation to a string.

To upload files using ajax, you must use a FormData object , which is only supported with IE10 and higher, for older ajax upload isn browsers it is possible, and workarounds with iframes, etc. must be implanted

 function AddMultipleContact() { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } var url = "url.php"; var group = document.getElementById("select-input").value; var files = document.getElementById('file-name').files; var formData = new FormData(); for (var i = 0; i < files.length; i++) { var file = files[i]; formData.append('files[]', file, file.name); } formData.append('select_input', group); xmlhttp.open("POST", url, true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var data = xmlhttp.responseText; document.getElementById("flash-message").innerHTML = data; } } xmlhttp.send(formData); } 
+1
source

Source: https://habr.com/ru/post/988004/


All Articles