Passing an Image with Ajax
HTML form for uploading an Image:
<form method="post" enctype="multipart/form-data">
<div>
<input type="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>
Javascript/Ajax for sending the data.
var RequestObject = false;
if (window.XMLHttpRequest) {
RequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
RequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function uploadImages() {
if (RequestObject) {
var formData = new FormData();
var myfile = document.getElementById('image').files[0];
formData.append('file', myfile);
RequestObject.open("POST", "processFileA.php");
RequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById('err').innerHTML = RequestObject.responseText;
}
}
RequestObject.send("data=" + formData);
}
return false;
}
PHP is simple just to check if the data is set.
if(isset($_POST['data'])){
echo $_POST['data'];
echo "data is set";
} else {
echo "data is not set";
}
I've checked 3 header requests.
First:the data isn't set.
RequestObject.setRequestHeader('Content-Type','multipart/form-data');
Second:the data isn't set.
RequestObject.setRequestHeader('Content-Type', "multipart/form-data; charset=utf-8; boundary=" + Math.random().toString().substr(2));
Third:returns this [object FormData].
RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
I have also tried no header requests and data isn't set.
I know how to safely process the form through regular form submit with PHP, but not sure how to handle [object FormData] as it is passed via Ajax. If their is a better method or something I'm doing wrong please let me know. My question is how do I properly send the image file Via Ajax to process it as you would in a regular form submit to properly process it in PHP.
Please no JQuery.
javascript php ajax ajaxform
add a comment |
HTML form for uploading an Image:
<form method="post" enctype="multipart/form-data">
<div>
<input type="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>
Javascript/Ajax for sending the data.
var RequestObject = false;
if (window.XMLHttpRequest) {
RequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
RequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function uploadImages() {
if (RequestObject) {
var formData = new FormData();
var myfile = document.getElementById('image').files[0];
formData.append('file', myfile);
RequestObject.open("POST", "processFileA.php");
RequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById('err').innerHTML = RequestObject.responseText;
}
}
RequestObject.send("data=" + formData);
}
return false;
}
PHP is simple just to check if the data is set.
if(isset($_POST['data'])){
echo $_POST['data'];
echo "data is set";
} else {
echo "data is not set";
}
I've checked 3 header requests.
First:the data isn't set.
RequestObject.setRequestHeader('Content-Type','multipart/form-data');
Second:the data isn't set.
RequestObject.setRequestHeader('Content-Type', "multipart/form-data; charset=utf-8; boundary=" + Math.random().toString().substr(2));
Third:returns this [object FormData].
RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
I have also tried no header requests and data isn't set.
I know how to safely process the form through regular form submit with PHP, but not sure how to handle [object FormData] as it is passed via Ajax. If their is a better method or something I'm doing wrong please let me know. My question is how do I properly send the image file Via Ajax to process it as you would in a regular form submit to properly process it in PHP.
Please no JQuery.
javascript php ajax ajaxform
try use print_r($_FILES) and see if you file image received
– HamzaNig
Jan 1 at 8:33
I get Array ( ) 1 with print_r($_FILES) using this RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); Still isnt set with the other 2 header requests
– Jonny
Jan 1 at 8:34
add a comment |
HTML form for uploading an Image:
<form method="post" enctype="multipart/form-data">
<div>
<input type="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>
Javascript/Ajax for sending the data.
var RequestObject = false;
if (window.XMLHttpRequest) {
RequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
RequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function uploadImages() {
if (RequestObject) {
var formData = new FormData();
var myfile = document.getElementById('image').files[0];
formData.append('file', myfile);
RequestObject.open("POST", "processFileA.php");
RequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById('err').innerHTML = RequestObject.responseText;
}
}
RequestObject.send("data=" + formData);
}
return false;
}
PHP is simple just to check if the data is set.
if(isset($_POST['data'])){
echo $_POST['data'];
echo "data is set";
} else {
echo "data is not set";
}
I've checked 3 header requests.
First:the data isn't set.
RequestObject.setRequestHeader('Content-Type','multipart/form-data');
Second:the data isn't set.
RequestObject.setRequestHeader('Content-Type', "multipart/form-data; charset=utf-8; boundary=" + Math.random().toString().substr(2));
Third:returns this [object FormData].
RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
I have also tried no header requests and data isn't set.
I know how to safely process the form through regular form submit with PHP, but not sure how to handle [object FormData] as it is passed via Ajax. If their is a better method or something I'm doing wrong please let me know. My question is how do I properly send the image file Via Ajax to process it as you would in a regular form submit to properly process it in PHP.
Please no JQuery.
javascript php ajax ajaxform
HTML form for uploading an Image:
<form method="post" enctype="multipart/form-data">
<div>
<input type="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>
Javascript/Ajax for sending the data.
var RequestObject = false;
if (window.XMLHttpRequest) {
RequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
RequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function uploadImages() {
if (RequestObject) {
var formData = new FormData();
var myfile = document.getElementById('image').files[0];
formData.append('file', myfile);
RequestObject.open("POST", "processFileA.php");
RequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById('err').innerHTML = RequestObject.responseText;
}
}
RequestObject.send("data=" + formData);
}
return false;
}
PHP is simple just to check if the data is set.
if(isset($_POST['data'])){
echo $_POST['data'];
echo "data is set";
} else {
echo "data is not set";
}
I've checked 3 header requests.
First:the data isn't set.
RequestObject.setRequestHeader('Content-Type','multipart/form-data');
Second:the data isn't set.
RequestObject.setRequestHeader('Content-Type', "multipart/form-data; charset=utf-8; boundary=" + Math.random().toString().substr(2));
Third:returns this [object FormData].
RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
I have also tried no header requests and data isn't set.
I know how to safely process the form through regular form submit with PHP, but not sure how to handle [object FormData] as it is passed via Ajax. If their is a better method or something I'm doing wrong please let me know. My question is how do I properly send the image file Via Ajax to process it as you would in a regular form submit to properly process it in PHP.
Please no JQuery.
javascript php ajax ajaxform
javascript php ajax ajaxform
edited Jan 1 at 8:31


adiga
10.7k62444
10.7k62444
asked Jan 1 at 8:25
JonnyJonny
9301720
9301720
try use print_r($_FILES) and see if you file image received
– HamzaNig
Jan 1 at 8:33
I get Array ( ) 1 with print_r($_FILES) using this RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); Still isnt set with the other 2 header requests
– Jonny
Jan 1 at 8:34
add a comment |
try use print_r($_FILES) and see if you file image received
– HamzaNig
Jan 1 at 8:33
I get Array ( ) 1 with print_r($_FILES) using this RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); Still isnt set with the other 2 header requests
– Jonny
Jan 1 at 8:34
try use print_r($_FILES) and see if you file image received
– HamzaNig
Jan 1 at 8:33
try use print_r($_FILES) and see if you file image received
– HamzaNig
Jan 1 at 8:33
I get Array ( ) 1 with print_r($_FILES) using this RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); Still isnt set with the other 2 header requests
– Jonny
Jan 1 at 8:34
I get Array ( ) 1 with print_r($_FILES) using this RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); Still isnt set with the other 2 header requests
– Jonny
Jan 1 at 8:34
add a comment |
2 Answers
2
active
oldest
votes
your problem in this string:
RequestObject.send("data=" + formData);
when you try String + formData
, you did concatenation, and formData convert to String to, as we know formData
it's object.
this is correct approach to send data:
RequestObject.send(formData);
just send a data like in this examples: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
I get this Warning: Unknown: Input variables exceeded 2500. To increase the limit change max_input_vars in php.ini. in Unknown on line 0 and it returned data is not set.
– Jonny
Jan 1 at 8:44
can you try with small image
– Vadim Hulevich
Jan 1 at 8:46
try in php var_dump($_POST) and see what inside
– Vadim Hulevich
Jan 1 at 8:47
yes i just did no warning but it returned data is not set
– Jonny
Jan 1 at 8:47
ok, what inside var_dump($_POST) and var_dump($_FILES)
– Vadim Hulevich
Jan 1 at 8:49
|
show 6 more comments
You can use diffrent way by ajax see example bellow :
THIS ANSWER WITH JUST JAVASCRIPT AJAX
<html>
<head>
<script >
function uploadImages(){
var xhr = new XMLHttpRequest();
var url = "processFileA.php";
xhr.open("POST", url, true);
//xhr.setRequestHeader("Content-Type", "application/json");
//xhr.setRequestHeader("accept", "application/json, text/plain, */*");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var content= xhr.responseText;
console.log(content);
}
};
var datae=document.getElementById('uploadimage');
var data = new FormData(datae);
xhr.send(data);
}
</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>
</body>
</html>
THIS ANSWER USING JQUERY AJAX
<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed|Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script >
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "processFileA.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert('done')
}
});
}));
});
</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="submit" class="ImgSubmitButton" >UPLOAD
IMAGE</button>
</div>
</form>
</body>
</html>
PHP FILE : processFileA.php
<?php
if(isset($_FILES["file"]["type"]))
{
$file=(file_get_contents($_FILES["file"]['tmp_name']));
file_put_contents('tmp_name.'.str_replace('image/','',$_FILES["file"]["type"]),$file);
}
?>
cant use jquery
– Jonny
Jan 1 at 9:24
@Jonny ah you using just javascript ok i updated my code check it
– HamzaNig
Jan 1 at 9:49
I get data not set with this solution.
– Jonny
Jan 1 at 23:35
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994042%2fpassing-an-image-with-ajax%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
your problem in this string:
RequestObject.send("data=" + formData);
when you try String + formData
, you did concatenation, and formData convert to String to, as we know formData
it's object.
this is correct approach to send data:
RequestObject.send(formData);
just send a data like in this examples: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
I get this Warning: Unknown: Input variables exceeded 2500. To increase the limit change max_input_vars in php.ini. in Unknown on line 0 and it returned data is not set.
– Jonny
Jan 1 at 8:44
can you try with small image
– Vadim Hulevich
Jan 1 at 8:46
try in php var_dump($_POST) and see what inside
– Vadim Hulevich
Jan 1 at 8:47
yes i just did no warning but it returned data is not set
– Jonny
Jan 1 at 8:47
ok, what inside var_dump($_POST) and var_dump($_FILES)
– Vadim Hulevich
Jan 1 at 8:49
|
show 6 more comments
your problem in this string:
RequestObject.send("data=" + formData);
when you try String + formData
, you did concatenation, and formData convert to String to, as we know formData
it's object.
this is correct approach to send data:
RequestObject.send(formData);
just send a data like in this examples: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
I get this Warning: Unknown: Input variables exceeded 2500. To increase the limit change max_input_vars in php.ini. in Unknown on line 0 and it returned data is not set.
– Jonny
Jan 1 at 8:44
can you try with small image
– Vadim Hulevich
Jan 1 at 8:46
try in php var_dump($_POST) and see what inside
– Vadim Hulevich
Jan 1 at 8:47
yes i just did no warning but it returned data is not set
– Jonny
Jan 1 at 8:47
ok, what inside var_dump($_POST) and var_dump($_FILES)
– Vadim Hulevich
Jan 1 at 8:49
|
show 6 more comments
your problem in this string:
RequestObject.send("data=" + formData);
when you try String + formData
, you did concatenation, and formData convert to String to, as we know formData
it's object.
this is correct approach to send data:
RequestObject.send(formData);
just send a data like in this examples: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
your problem in this string:
RequestObject.send("data=" + formData);
when you try String + formData
, you did concatenation, and formData convert to String to, as we know formData
it's object.
this is correct approach to send data:
RequestObject.send(formData);
just send a data like in this examples: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
answered Jan 1 at 8:41
Vadim HulevichVadim Hulevich
775111
775111
I get this Warning: Unknown: Input variables exceeded 2500. To increase the limit change max_input_vars in php.ini. in Unknown on line 0 and it returned data is not set.
– Jonny
Jan 1 at 8:44
can you try with small image
– Vadim Hulevich
Jan 1 at 8:46
try in php var_dump($_POST) and see what inside
– Vadim Hulevich
Jan 1 at 8:47
yes i just did no warning but it returned data is not set
– Jonny
Jan 1 at 8:47
ok, what inside var_dump($_POST) and var_dump($_FILES)
– Vadim Hulevich
Jan 1 at 8:49
|
show 6 more comments
I get this Warning: Unknown: Input variables exceeded 2500. To increase the limit change max_input_vars in php.ini. in Unknown on line 0 and it returned data is not set.
– Jonny
Jan 1 at 8:44
can you try with small image
– Vadim Hulevich
Jan 1 at 8:46
try in php var_dump($_POST) and see what inside
– Vadim Hulevich
Jan 1 at 8:47
yes i just did no warning but it returned data is not set
– Jonny
Jan 1 at 8:47
ok, what inside var_dump($_POST) and var_dump($_FILES)
– Vadim Hulevich
Jan 1 at 8:49
I get this Warning: Unknown: Input variables exceeded 2500. To increase the limit change max_input_vars in php.ini. in Unknown on line 0 and it returned data is not set.
– Jonny
Jan 1 at 8:44
I get this Warning: Unknown: Input variables exceeded 2500. To increase the limit change max_input_vars in php.ini. in Unknown on line 0 and it returned data is not set.
– Jonny
Jan 1 at 8:44
can you try with small image
– Vadim Hulevich
Jan 1 at 8:46
can you try with small image
– Vadim Hulevich
Jan 1 at 8:46
try in php var_dump($_POST) and see what inside
– Vadim Hulevich
Jan 1 at 8:47
try in php var_dump($_POST) and see what inside
– Vadim Hulevich
Jan 1 at 8:47
yes i just did no warning but it returned data is not set
– Jonny
Jan 1 at 8:47
yes i just did no warning but it returned data is not set
– Jonny
Jan 1 at 8:47
ok, what inside var_dump($_POST) and var_dump($_FILES)
– Vadim Hulevich
Jan 1 at 8:49
ok, what inside var_dump($_POST) and var_dump($_FILES)
– Vadim Hulevich
Jan 1 at 8:49
|
show 6 more comments
You can use diffrent way by ajax see example bellow :
THIS ANSWER WITH JUST JAVASCRIPT AJAX
<html>
<head>
<script >
function uploadImages(){
var xhr = new XMLHttpRequest();
var url = "processFileA.php";
xhr.open("POST", url, true);
//xhr.setRequestHeader("Content-Type", "application/json");
//xhr.setRequestHeader("accept", "application/json, text/plain, */*");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var content= xhr.responseText;
console.log(content);
}
};
var datae=document.getElementById('uploadimage');
var data = new FormData(datae);
xhr.send(data);
}
</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>
</body>
</html>
THIS ANSWER USING JQUERY AJAX
<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed|Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script >
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "processFileA.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert('done')
}
});
}));
});
</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="submit" class="ImgSubmitButton" >UPLOAD
IMAGE</button>
</div>
</form>
</body>
</html>
PHP FILE : processFileA.php
<?php
if(isset($_FILES["file"]["type"]))
{
$file=(file_get_contents($_FILES["file"]['tmp_name']));
file_put_contents('tmp_name.'.str_replace('image/','',$_FILES["file"]["type"]),$file);
}
?>
cant use jquery
– Jonny
Jan 1 at 9:24
@Jonny ah you using just javascript ok i updated my code check it
– HamzaNig
Jan 1 at 9:49
I get data not set with this solution.
– Jonny
Jan 1 at 23:35
add a comment |
You can use diffrent way by ajax see example bellow :
THIS ANSWER WITH JUST JAVASCRIPT AJAX
<html>
<head>
<script >
function uploadImages(){
var xhr = new XMLHttpRequest();
var url = "processFileA.php";
xhr.open("POST", url, true);
//xhr.setRequestHeader("Content-Type", "application/json");
//xhr.setRequestHeader("accept", "application/json, text/plain, */*");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var content= xhr.responseText;
console.log(content);
}
};
var datae=document.getElementById('uploadimage');
var data = new FormData(datae);
xhr.send(data);
}
</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>
</body>
</html>
THIS ANSWER USING JQUERY AJAX
<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed|Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script >
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "processFileA.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert('done')
}
});
}));
});
</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="submit" class="ImgSubmitButton" >UPLOAD
IMAGE</button>
</div>
</form>
</body>
</html>
PHP FILE : processFileA.php
<?php
if(isset($_FILES["file"]["type"]))
{
$file=(file_get_contents($_FILES["file"]['tmp_name']));
file_put_contents('tmp_name.'.str_replace('image/','',$_FILES["file"]["type"]),$file);
}
?>
cant use jquery
– Jonny
Jan 1 at 9:24
@Jonny ah you using just javascript ok i updated my code check it
– HamzaNig
Jan 1 at 9:49
I get data not set with this solution.
– Jonny
Jan 1 at 23:35
add a comment |
You can use diffrent way by ajax see example bellow :
THIS ANSWER WITH JUST JAVASCRIPT AJAX
<html>
<head>
<script >
function uploadImages(){
var xhr = new XMLHttpRequest();
var url = "processFileA.php";
xhr.open("POST", url, true);
//xhr.setRequestHeader("Content-Type", "application/json");
//xhr.setRequestHeader("accept", "application/json, text/plain, */*");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var content= xhr.responseText;
console.log(content);
}
};
var datae=document.getElementById('uploadimage');
var data = new FormData(datae);
xhr.send(data);
}
</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>
</body>
</html>
THIS ANSWER USING JQUERY AJAX
<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed|Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script >
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "processFileA.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert('done')
}
});
}));
});
</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="submit" class="ImgSubmitButton" >UPLOAD
IMAGE</button>
</div>
</form>
</body>
</html>
PHP FILE : processFileA.php
<?php
if(isset($_FILES["file"]["type"]))
{
$file=(file_get_contents($_FILES["file"]['tmp_name']));
file_put_contents('tmp_name.'.str_replace('image/','',$_FILES["file"]["type"]),$file);
}
?>
You can use diffrent way by ajax see example bellow :
THIS ANSWER WITH JUST JAVASCRIPT AJAX
<html>
<head>
<script >
function uploadImages(){
var xhr = new XMLHttpRequest();
var url = "processFileA.php";
xhr.open("POST", url, true);
//xhr.setRequestHeader("Content-Type", "application/json");
//xhr.setRequestHeader("accept", "application/json, text/plain, */*");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var content= xhr.responseText;
console.log(content);
}
};
var datae=document.getElementById('uploadimage');
var data = new FormData(datae);
xhr.send(data);
}
</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="button" class="ImgSubmitButton" onclick="uploadImages();">UPLOAD IMAGE</button>
</div>
</form>
</body>
</html>
THIS ANSWER USING JQUERY AJAX
<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed|Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script >
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "processFileA.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert('done')
}
});
}));
});
</script>
</head>
<body>
<form id="uploadimage" method="post" enctype="multipart/form-data">
<div>
<input type="file" name="file" id="image">
<button type="submit" class="ImgSubmitButton" >UPLOAD
IMAGE</button>
</div>
</form>
</body>
</html>
PHP FILE : processFileA.php
<?php
if(isset($_FILES["file"]["type"]))
{
$file=(file_get_contents($_FILES["file"]['tmp_name']));
file_put_contents('tmp_name.'.str_replace('image/','',$_FILES["file"]["type"]),$file);
}
?>
edited Jan 1 at 9:48
answered Jan 1 at 9:23
HamzaNigHamzaNig
810531
810531
cant use jquery
– Jonny
Jan 1 at 9:24
@Jonny ah you using just javascript ok i updated my code check it
– HamzaNig
Jan 1 at 9:49
I get data not set with this solution.
– Jonny
Jan 1 at 23:35
add a comment |
cant use jquery
– Jonny
Jan 1 at 9:24
@Jonny ah you using just javascript ok i updated my code check it
– HamzaNig
Jan 1 at 9:49
I get data not set with this solution.
– Jonny
Jan 1 at 23:35
cant use jquery
– Jonny
Jan 1 at 9:24
cant use jquery
– Jonny
Jan 1 at 9:24
@Jonny ah you using just javascript ok i updated my code check it
– HamzaNig
Jan 1 at 9:49
@Jonny ah you using just javascript ok i updated my code check it
– HamzaNig
Jan 1 at 9:49
I get data not set with this solution.
– Jonny
Jan 1 at 23:35
I get data not set with this solution.
– Jonny
Jan 1 at 23:35
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994042%2fpassing-an-image-with-ajax%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
try use print_r($_FILES) and see if you file image received
– HamzaNig
Jan 1 at 8:33
I get Array ( ) 1 with print_r($_FILES) using this RequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); Still isnt set with the other 2 header requests
– Jonny
Jan 1 at 8:34