I am working on PHP and AJAX to upload image in a folder and message value(any textbox and textarea value). The code is working for image upload by ajax and PHP but I don't know how to pass message variable value.
<!DOCTYPE html>
<body>
<span id="msg" style="color:red"></span><br/>
<textarea name="message" class="form-control" id="message"></textarea>
<input type="file" id="photo"><br/>
<button class="btn btn-success" id="save">Save</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click", "#save", function () {
var message = $("#message").val();
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'insert2.php?'+message,
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
</html>
The image is uploading in a folder but the message is undefined when I click save button .
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'testimg/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
echo $message = $_POST['message'];
}
?>
It's giving me undefine message value on the PHP page. Screenshot
What is the best way to pass file and box values using ajax for PHP file?