how to send images file to the url? - javascript

Here is my code:
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "LiveUpdate.php";
var sb = document.getElementById("LiveUpdate").value;
var FirstName = document.getElementById("FirstName").value;
var images = document.getElementById("images").value;
var vars = "update="+sb+"&FirstName="+FirstName+"&images="+images;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("success_insert").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("success_insert").innerHTML = "processing...";
}
I just want to send all the basic details like First name, Middle name, Last name, and the image. The problem is, I can send the First name, Middle name, and Last name, but I can't pass the image to the LiveUpdate.php endpoint.
What's going on?

<input type="file"> element stores FileList of File objects selected by user at .files property, the .value of element is set as a string. You can set Content-Type to multipart/form-data, use FormData(), set name property of elements to query string keys, .value or .files property of <form> elements will be set at values of FormData object.
Call event.preventDefault() at submit event of <form>, pass form reference to FormData() constructor to set key, value pairs at FormData object.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form1" name="form1" enctype="multipart/form-data">
<div>
First Name
<input type="text" name="FirstName" id="FirstName">
<br>Live Update
<input type="text" name="LiveUpdate" id="LiveUpdate">
<br>Image
<input type="file" id="images" name="images" accept="image/*">
</div>
<input type="submit">
</form>
<script>
var form = document.getElementById("form1");
form.onsubmit = function(e) {
e.preventDefault();
function ajax_post(form) {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "/dev/null";
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "multipart/form-data");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
//document.getElementById("success_insert").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(new FormData(form)); // Actually execute the request
// document.getElementById("success_insert").innerHTML = "processing...";
}
ajax_post(this)
}
</script>
</body>
</html>

Related

$_FILES not receiving input after AJAX with vanilla Javascript

I have a form that passes various types of input to an ajax call, which opens a php script. The script will do various things including processing the file, before echoing an array of variables.
All inputs go through $_POST regularly, and the file data is passed, too, but the file itself is not accessible from $_FILES.
I am not using jQuery, so most posts are hard to translate to my case.
I have seen a similar issue here,https://stackoverflow.com/questions/56878395/files-empty-after-ajax-upload but that solution doesn't seem to apply.
Here are the key excerpts from the code, thank you in advance for any tips!
var ajaxResponse = "";
var qForm = document.getElementById('myForm');
qForm.addEventListener("submit", function(e) {
e.preventDefault();
var formData = new FormData(qForm);
checkForm(formData);
console.log(ajaxResponse); //this shows the $_FILES var_dump
});
function checkForm(formData) {
var vars = "startDate=" + formData.get('startDate') +
"&qInvited=" + formData.get('qInvited');
ajaxRequestReturn("checkForm.php", vars);
}
function ajaxRequestReturn(phpRequest, vars) {
var req = new XMLHttpRequest();
req.open("POST", phpRequest, false); //not asynchronous, because I pass results to a global variable
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //removing the setRequestHeader doesn't seem to make any difference.
req.onload = function() {
ajaxResponse = this.responseText;
}
req.onerror = function() {
throw new Error("Bad request.");
}
req.send(vars);
// form.submit();
}
<form class="loginForm" id="myForm" method="post" enctype="multipart/form-data" action="thisPage.php">
<div>
<input type="date" id="startDateInput" name="startDate">
</div>
<div>
<input type="file" name="qInvited" required>
</div>
<input type="submit" id="submitBtn">
</form>
and the checkForm.php file is currently simply:
<?php
echo var_dump($_FILES);
?>
the var_dump($_FILES) should show the qInvited file in it, but it prints
array(0) {
}
instead.
To upload a file via ajax you have to pass a FormData object in your call to XMLHttpRequest.send.
Get rid of the checkForm function and call ajaxRequestReturn with formData as the second parameter.
Also, application/x-www-form-urlencoded is not the correct content type(its multipart/form-data), remove that line. The correct content type will be set automatically when you use the FormData object.

Passing multiple parameters by POST using XMLHttpRequest and HTML

I'm trying to pass multiple parameters via HTML form into a XMLHttpRequest. The request takes a network SSID and PSK and passes it to the /connect endpoint.
It works when I hardcode the SSID and PSK using:
var data = '{"ssid":"homenetwork", "psk":"mypassword"}';
xhr.send(data);
When I try to pull the data from the HTML form I get net::ERR_EMPTY_RESPONSE in Chrome.
<!DOCTYPE html>
<html>
<br>
<label for="network">Network Name (SSID):</label>
<input type="text" id="network" name="network" required size="15">
<label for="presharedkey">Network Password (PSK): </label>
<input type="text" id="presharedkey" name="presharedkey" required size="15">
<button onclick="connectWifi()">Save</button> <br>
<script>
function connectWifi() {
var network = document.getElementById("network") .value;
var presharedkey = document.getElementById("presharedkey") .value;
var url = "http://192.168.0.236:8080/connect";
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
// var data = '{"ssid":"homenetwork", "psk":"mypassword"}';
var data = 'ssid='+network+'&psk='+presharedkey;
xhr.send(data);
}
</script>
</html>
The var data = line I pulled from this StackOverflow question.
Thanks in advance.
The data variable you are using needs to be a JSON object. In your example here it is a string, so the individual values are not passed, just one single string.
Try:
var data = `{"ssid": "${network}", "psk": "${presharedkey}"}`;
[EDIT]
I misunderstood the original question it seems. OP is trying to send the data as a JSON object but doesn't know how to format it (they claim manually passing the string of variables works).

Submit a form obtained via XMLHttpRequest?

I am trying to a download a html page via javascript, parse it and submit the form with the following code. Everything seems to work perfectly in this function, yet I am unable to see the desired server side changes. Could someone point me if there's something wrong in this approach ?
function get_page(url){
var xhr = new XMLHttpRequest();
xhr.responseType = "document"; //parse html
xhr.open("GET", url);
xhr.send(null);
xhr.onload = function(){
// get form here
var dom = xhr.responseXML;
var form = dom.forms[0];
// set values in fields
form[0].value='hello';
form[1].value=form[0].value;
//change action from # to url
form.action = url;
//EDIT: attach form to body
document.getElementsByTagName('body')[0].appendChild(form);
//form submit
form.submit();
//print form last value
console.log(form[3].value);
}
}

Access XMLHttpRequest data in CakePhp controller

I have this piece of code:
var form = document.querySelector('form');
var request = new XMLHttpRequest();
var formData = new FormData(form);
request.open('POST','/leandwell/processData', true);
request.send(formData);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
// OK
alert(request.responseText);
} else {
// not OK
alert('failure!');
}
}
};
With this function in my controller:
public function processData(){
$this->autoRender = false;
$data = $this->request->data;
return json_encode($data['address']);
}
But it's just alerting Undefined index address meanwhile I have <input type="text" name="address"> inside my form. Is their another way I can access this data correctly in my controller method.
I am actually using XMLHttpRequest because the form has input type file, because I need to upload a file along with it.
Any suggestion will be appreciated.
Thanks.
I'm pretty sure your formData doesn't match what Cake expects. Make sure the form data you send equals that HTML attribute name="data[address]" instead of name="address".
Also instead of doing return json_encode($data['address']); read XML and Json Views in CakePHP.

On ajax success set variable and use the variable in jquery outside ajax

Aim is to set (change) html hidden input field value to 0 after successful execution of ajax.
At first decided on ajax success to define variable and latter to use outside ajax.
But read (JQuery - How to use the return value of an ajax call outside that ajax call) that it is impossible.
Need to find some solution.
Below is code
Ajax (as an example)
<script language="JavaScript" type="text/javascript">
function ajax_post(){
if (window.XMLHttpRequest)
{
var hr = new XMLHttpRequest();
}
else
{
var hr = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "_autosave.php";
var sabt = document.getElementById("date_day1").value;
var prao = document.getElementById("amount1").value;
var vars = "date_day1="+sabt+"&amount1="+prao;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
Here I decided to define variable to use it outside ajax. As read this does not work because script runs over the variable and reaches outside ajax variable before the ajax variable is set.
var ajax_post_success = 1;
Remaining part of code
}
}
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
Then latter (if ajax success set value to 0)
<input type="hidden" name="is_row_changed1" id="is_row_changed1" value="" >
<script>
$(document).ready(function() {
if(ajax_post_success == 1) {
document.getElementById('is_row_changed1').value = 0;
}
});
</script>
Aim of all this is following.
I plan to use table with 10 rows and 19 input fields in each row.
If user enters something in any of fields, value of hidden input field changes to 1 (this is ok).
Then with ajax insert/update user input.
After successful insert/update set hidden field value to 0.
On each php insert/update execution check if hidden field value is 1. If value is 1 insert/update the row. If value is 0 do nothing with the row. Insert/update only rows which hidden field value is 1.
That is the aim of the question.
What would be solution?
I don't think you need to have that variable, you can change the value of the hidden field is_row_changed1 to zero in the onreadystatechange callback of the ajax method
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
document.getElementById('is_row_changed1').value = 0;
}
}
I would suggest using jQuery ajax like
function ajax_post() {
var sabt = $('#date_day1').val();
var prao = $('#amount1').val();
$.ajax({
url : "_autosave.php",
data : {
date_day1 : sabt,
amount1 : prao
}
}).done(function(html) {
$('#status').html(html);
$('#is_row_changed1').val(0);
});
}

Categories