I am looking to streamline my ajax functionality by combining two separate functions. One function is used to post a name, while the other is used to upload an image. I would like to create a single function that can handle both tasks of posting a name and uploading an image.
Below are the codes for uploading an image:
<script>
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#file')[0].files;
// Check if file is selected
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
},
});
}else{
alert("Please select a file.");
}
});
});
</script>
And here are the codes for posting a name:
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
$.ajax({
type:"post",
url:"upload.php",
data:
{
'name' :name
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
I am seeking assistance on how to combine the above codes in order to use only one URL "upload.php". This means that when the save button is clicked, upload.php should insert the name into the database and save the image in a folder. Any help would be greatly appreciated.
Please let me know if anyone can assist with this task.