I have a working php code to upload image in the database. Is it Possible to transform it to jquery? If so, what do I need to do? I am new to jquery btw. Thanks
This code works just fine. But I need to do it in jquery.
<form action = 'upload.php' method = 'post' enctype="multipart/form-data">
<input type="file" name="image" > <br>
<input type= 'submit' value = 'Add' id = 'Add' name = 'Add'>
</form>
<?php
if(isset($_FILES['image']))
{
$target_Path = "images/";
$target_Path = $target_Path.basename($_FILES['image']['name'] );
move_uploaded_file( $_FILES['image']['tmp_name'], $target_Path );
$name = $_FILES['image']['name'];
}
if(isset($_POST['Add']))
{
if($_POST["Add"] == "Add")
{
$add = "Insert Into img(path) Values('$name')";
$up = mysql_query($add);
$status = "Upload success!";
print '<script type="text/javascript">';
print 'alert(" '.$status.' ")';
print '</script>';
}
}
You can make an ajax call instead to submit a form. You can use something like this as well:
Although, you still need to have your php code in order to store the file in your server
<form action='upload.php' method='post' enctype="multipart/form-data" id="formupload">
<input type="file" name="image"/> <br>
<input type='submit' value='Add' id='Add' name='Add/>
</form>
You need to first setup a callback for the submit event of the form.
$("#formupload").on("submit", upload_image);
$("#formupload")
selects the element whose id is formupload
.on
is used to register a handler for an event.submit
event of the element whose id is formupload
.Make an AJAX call to the php script.
function upload_image(event){
event = event || window.event;
// Prevent the default form action i.e. loading of a new page
if(event.preventDefault){ // W3C Variant
event.preventDefault();
}
else{ // IE < 9
event.returnValue = false;
}
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData($('#formupload')[0]),
success : function(data){
// Show success message
},
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false
});
}
$.ajax
which is the jQuery utility for performing an AJAX call.url
property is to be filled by that of your PHP script.data
property is the payload of the POST request, which is the content of the file you are trying to upload.success
property, which is the function that will be called on completion of the file upload.