Sending image and other data in PHP by Ajax
In this blog you will learn that how you can send image as well as other data together in PHP page using Ajax method .
Example - You want to send input field data of file type as well as some other data which is not in form tag by using FormData method of Ajax .
1 - This is your HTML code
<form class="header-showcase-form">
<h6>Select an image </h6>
<input type="file" name="" id="header-image">
<input type="submit" value="send">
</form>
<h1 class="title target title-h1" style="color:#000;font-size:46px">TITLE</h1>
2 - This is JavaScript code(AJAX)
var form = document.querySelector(".header-showcase-form");
form.addEventListener('submit',function(e){
e.preventDefault();
var title_image = document.querySelector("#header-image").files[0];
var showcase_title_h1 = document.querySelector(".title-h1");
var title_color = showcase_title_h1.style.color;
var title_size = showcase_title_h1.style.fontSize;
var css_data = {
title_size : title_size,
title_color : title_color,
}
var formdata = new FormData();
formdata.append("file_data",title_image);
formdata.append("css_data",JSON.stringify(css_data));
$.ajax({
type: 'POST',
url: 'result.php',
data : formdata,
contentType:false,
processData:false,
success:function(response){
alert(response);
}
})
});
3 -This is the PHP code
print_r($_FILES['file_data']);
// print_r($_POST['css_data']); it wiil print data in object format and we cannot access it
$json_data = json_encode($_POST['css_data']);
$tmp_name = json_decode($json_data,true);
$all_data = json_decode($tmp_name,true);
print_r($all_data); // now it will print associative data
4 - RESULT
0 Comments
Please do not enter any spam link in comment box.