php codeigniter Video Upload Not Uploaded Video file - javascript

When uploading image files, the upload is complete and successful, but when uploading the video file, it is not uploaded and it does not show where the error is
HTML Code:
<div class="row mb-5">
<div class="col-md-12">
<input type="file" name="slider_image" id="" class="form-control mb-5" onchange="homeSliderUpload(this)">
<div class="progress mb-5" style="--sa-progress--value: 0%">
<div class="progress-bar progress-bar-sa-primary" role="progressbar" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
function homeSliderUpload(form) {
alert("First");
var file_data = $("input[name='slider_image']").prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "<?php echo base_url(); ?>/Path/VedioUploader",
dataType: 'text',
method: "post",
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data) {
var rJson = $.parseJSON(data);
if (rJson.status == true) {
$(".progress").attr("style", "--sa-progress--value: 100%");
$("input[name='slider_image']").val('');
setInterval(() => {
location.reload();
}, 1000);
} else {
alert("Error");
}
}
});
}
php Code ( Ajax Code):
public function VedioUploader()
{
$validateImage = $this->validate([
'file' => [
'uploaded[file]',
'mime_in[file, video/mp4, image/png, image/jpg,image/jpeg, image/gif]',
'max_size[file, 1000000000]',
],
]);
if ($validateImage) {
$imageFile = $this->request->getFile('file');
$folder = "Vedio/";
$fileName = rand(10005, 100005) . time() . ".mp4";
$imageFile->move($folder, $fileName);
$data = [
'img_name' => $imageFile->getClientName(),
'file' => $imageFile->getClientMimeType(),
'type' => $imageFile->getClientExtension(),
];
if ($fileName) {
$homeSliderModel = new VedioUplaod();
$home_slider["slider_file_url"] = $folder . "/" . $fileName;
$home_slider["slider_show"] = 1;
$home_slider["slider_order"] = 0;
$homeSliderModel->insert($home_slider);
if (!$homeSliderModel->errors()) {
echo json_encode([
"status" => true,
"slider_id" => $homeSliderModel->getInsertID(),
"file_url" => $folder . "/" . $fileName,
"order" => 0
]);
}
}
}
}
I tried removing the image types and retrying to upload the images, but it didn't work. It was similar to uploading the video. I thought it was because of the type, but nothing happened.
'mime_in[file, video/mp4]',

Related

Submitting two DropZones together with Ajax

I have a form that I need to submit, as well as two drop zones, I am having no problem submitting them separately but I would like to submit them all as one.
HTML:
<form id="add-product-form">
<div class="form-group row">
<label for="add-product-visible" class="col-4 col-form-label">Visibility</label>
<div class="col-8">
<select class="form-control" id="add-product-visible" required>
<option value="1">Shown</option>
<option value="0">Hidden</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="add-product-brand" class="col-4 col-form-label">Brand</label>
<div class="col-8">
<input class="form-control" type="text" value="" id="add-product-brand" maxlength="50" required>
</div>
</div>
<h4>Product Image Upload</h4>
<div id="photo_upload_primary" action="/file-upload" class="dropzone m-b-15"></div>
<div id="photo_upload_secondary" action="/file-upload" class="dropzone"></div>
<!-- Preview -->
<div class="mt-3" id="formfiles"></div>
<!-- File preview template -->
<div class="d-none" id="formtemplate">
<div class="card mb-3">
<div class="p-2">
<div class="row align-items-start">
<div class="col-auto">
<img data-dz-thumbnail src="#" class="avatar border rounded">
</div>
<div class="col pl-0">
<a href="#" class="text-muted font-weight-bold" data-dz-name></a>
<a href="#" class="text-muted font-weight-bold dz-id" data-dz-id></a>
<p class="mb-0"><small data-dz-size></small>
<small class="d-block text-danger" data-dz-errormessage></small></p>
</div>
<div class="col-auto pt-2">
<a class="btn-lg text-danger" href="#" data-dz-remove><i class="icon-trash-2"></i></a>
</div>
</div>
</div>
</div>
</div>
</form>
<button type="button" class="btn btn-light btn-shadow" onclick="upload()">Upload Images</button>
<button type="submit" form="add-product-form" class="btn btn-light btn-shadow">Submit Form</button>
Javascript:
dropzone.autoDiscover = false;
var image_width = 380, image_height = 507;
var photo_upload_primary = new Dropzone("#photo_upload_primary",{
maxFilesize: 1,
maxFiles: 1,
acceptedFiles: "image/*",
autoProcessQueue: false,
url: "upload.php",
previewsContainer: "#formfiles",
previewTemplate: $("#formtemplate").html(),
dictFileTooBig: "Image is too large ({{filesize}}MiB). Max file size is {{maxFilesize}}MiB.",
dictInvalidFileType: "This file is not an image.",
dictMaxFilesExceeded: "You have already uploaded a primary product image.",
dictDefaultMessage: "Click or drop primary product image here",
success: function (file, response) {
console.log(response);
},
error: function (file, response) {
$.notify({
message: response
},{
type: "danger"
});
this.removeFile(file);
},
init: function() {
this.on("thumbnail", function(file) {
if (file.width !== image_width || file.height !== image_height) {
file.rejectDimensions();
}
else {
file.acceptDimensions();
}
});
},
accept: function(file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function() {
done("Product image resolution outside of specifications. Resolution must be "+image_width+"px x "+image_height+"px");
};
},
renameFile: function (file) {
var ext = file.name.substring(file.name.lastIndexOf('.')+1);
var newName = 'primary.' + ext;
return newName;
},
});
var photo_upload_secondary = new Dropzone("#photo_upload_secondary",{
maxFilesize: 1,
maxFiles: 1,
acceptedFiles: "image/*",
autoProcessQueue: false,
url: "upload.php",
previewsContainer: "#formfiles",
previewTemplate: $("#formtemplate").html(),
dictFileTooBig: "Image is too large ({{filesize}}MiB). Max file size is {{maxFilesize}}MiB.",
dictInvalidFileType: "This file is not an image.",
dictMaxFilesExceeded: "You have already uploaded a secondary product image.",
dictDefaultMessage: "Click or drop secondary product image here",
success: function (file, response) {
console.log(response);
},
error: function (file, response) {
$.notify({
message: response
},{
type: "danger"
});
this.removeFile(file);
},
init: function() {
this.on("thumbnail", function(file) {
if (file.width !== image_width || file.height !== image_height) {
file.rejectDimensions();
}
else {
file.acceptDimensions();
}
});
},
accept: function(file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function() {
done("Product image resolution outside of specifications. Resolution must be "+image_width+"px x "+image_height+"px");
};
},
renameFile: function (file) {
var ext = file.name.substring(file.name.lastIndexOf('.')+1);
var newName = 'secondary.' + ext;
return newName;
}
});
function upload(){
photo_upload_primary.processQueue();
photo_upload_secondary.processQueue();
}
$('#add-product-form').submit(function (e) {
e.preventDefault();
var $form = $(this);
if (!$form.valid) return false;
if (photo_upload_primary.getQueuedFiles().length == 0) {
$.notify({
message: "Please upload a primary product photo."
},{
type: "danger"
});
return false;
}
if (photo_upload_secondary.getQueuedFiles().length == 0) {
$.notify({
message: "Please upload a secondary product photo."
},{
type: "danger"
});
return false;
}
addproduct();
});
function addproduct(){
var datafeilds = Array.from(document.querySelectorAll("[id^='add-product-']"));
var data = {};
datafeilds.forEach(function(field){
let replace = field.id.replace("add-product-", "");
data[replace] = field.value;
});
$.ajax({
type: 'POST',
url: 'addproduct-pdo.php',
data: {data: data},
dataType: 'json',
success: function(data) {
$.notify({
message: data.message
},{
type: data.response
});
if (data.response == "success"){
$("#add-product-form").trigger('reset');
photo_upload_primary.removeAllFiles();
photo_upload_secondary.removeAllFiles();
}
}
});
}
PHP (upload.php):
$ds = DIRECTORY_SEPARATOR;
$foldername = "./uploads";
if (!empty($_FILES)) {
$fileupload = basename( $_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
$targetFile = $targetPath.$fileupload;
move_uploaded_file($tempFile,$targetFile);
echo "File uploaded";
}
PHP (addproduct-pdo.php):
try {
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:charset=utf8mb4;host=$servername;dbname=$dbname", $username, $password);
function escape_mysql_identifier($field){
return "`".str_replace("`", "``", $field)."`";
}
function prepared_insert($pdo, $table, $data) {
$keys = array_keys($data);
$keys = array_map('escape_mysql_identifier', $keys);
$fields = implode(",", $keys);
$table = escape_mysql_identifier($table);
$placeholders = str_repeat('?,', count($keys) - 1) . '?';
$sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
$pdo->prepare($sql)->execute(array_values($data));
}
$data = array_filter($data);
prepared_insert($conn, 'products', $data);
$id = $conn->lastInsertId();
if ($id > 1) {
echo json_encode(array('response'=>'success','message'=>'Product successfully added as ID # '.$id));
}else{
echo json_encode(array('response'=>'danger','message'=>'Product not successfully added'));
}
}catch(PDOException $e){
echo json_encode(array('response'=>'danger','message'=>$e->getMessage()));
}
$conn = null;
I am having trouble on two things:
How can I submit both DropZone's as one?
How can I submit the DropZone(s) with the Ajax? I am going to need to pass off the $id from addproduct-pdo.php to either the DropZone Javascript or upload.php for it to name the file correctly.
Thanks!

Ajax not working in codeigniter 3

when i click in the button btnSalvar, ajax need to send data to my controller, but not working.
my ajax:
$("#btnSalvar").on('click', function(){
$.ajax({
url: '<?= base_url(); ?>' + 'grupoProduto/cadastro',
type: 'POST',
data: {Nome: $("#txtNome").val(), Ativo: $("#cbxAtivo").val()},
dataType: 'json',
cache: false,
success:
function(data){
alert(data.Nome); //as a debugging message.
}
});
return false;
});
My controller:
public function cadastro() {
$this->load->view('grupoproduto_view');
}
my alert(data.Nome) showing nothing
here's my full php code:
`
<div class="row">
<div class="form-group">
<label for="txtNome" class="col-md-3 control-label">Nome</label>
<div class="col-md-6">
<?php echo form_input(['name' => 'txtNome', 'class' => 'form-control',
'value' => set_value('txtNome'), 'required' => 'true', 'maxlength' => '50', 'required' => 'true', 'id' => 'txtNome']); ?>
</div>
</div>
<div class="form-group">
<label for="cbxAtivo" class="col-md-3 control-label">Ativo</label>
<div class="col-md-1">
<?php echo form_checkbox(['name' => 'cbxAtivo', 'class' => 'form-control', 'required' => 'true', 'id' => 'cbxAtivo']); ?>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<div class="modal-footer">
<?php echo anchor(NULL, "<i class='glyphicon glyphicon-remove'></i> Sair", ['class' => 'btn btn-default', 'id' => 'btnSair', 'role' => 'button', 'data-dismiss' => 'modal']); ?>
<?php echo form_button(NULL, "<i class='glyphicon glyphicon-ok'></i> Salvar", ['class' => 'btn btn-success', 'id' => 'btnSalvar', 'role' => 'button']); ?>
</div>
</div>
</div>
</div>
</fieldset>
new edit!
`$("#btnSalvar").on('click', function(){
var nome = $("#txtNome").val();
var ativo = $("#cbxAtivo").val();
var url = '<?= base_url(); ?>grupoProduto/cadastro';
$.ajax({
url: url,
type: 'POST',
data: {Nome: nome, Ativo: ativo},
dataType: 'json',
cache: false,
success:
function(data){
alert(data.Nome); //as a debugging message.
},
error: function() {
alert(url);
}
});
return false;
});`
return error in the ajax and show this url: http://localhost/admin/grupoProduto/cadastro. It's correct, but why not success?
Your PHP '<?= base_url(); ?>' + 'grupoProduto/cadastro' is not getting evaluated
$.ajax({
url: '+<?= base_url(); ?>+'+ 'grupoProduto/cadastro',
....
Problem is in your base_url()
In order to use base_url(), you must first have the URL Helper loaded. This can be done either in application/config/autoload.php (on or around line 67):
$autoload['helper'] = array('url');
Or,
manually:
$this->load->helper('url');
checkout this answer
maybe the problem as Nadir says that base_url not evaluated ,
you can try something like this
var link = "<?php echo base_url(); ?>";
var Nome = $("#txtNome").val();
var Ativo = $("#cbxAtivo").val();
$.post(link + "grupoProduto/cadastro", {Nome : Nome ,Ativo :Ativo},function(data){
alert("something")
});

"You did not select a file to upload. " get this error while uploading image using ajax

I am working with CodeIgniter and jQuery ajax. I want to upload image using ajax. But it shows an error like You did not select a file to upload.
Here,I have write jQuery :
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = jQuery(this).serialize();
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
<form id="signup_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-3">Upload Photo</div>
<div class="col-md-4">
<input type="file" name="pic" accept="image/*">
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
And My function looks like this :
function ajax_register()
{
if($this->input->post())
{
$this->form_validation->set_rules('pass', 'Password', 'required|matches[cpass]');
$this->form_validation->set_rules('cpass', 'Password Confirmation', 'required');
if($this->form_validation->run() == true)
{
$img = "";
$config['upload_path'] = './uploads/user/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('pic'))
{
$data['error'] = array('error' => $this->upload->display_errors());
print_r($data['error']);exit;
$data['flash_message'] = "Record is not inserted";
}
else
{
$upload = $this->upload->data();
//print_r($upload);exit;
$data = array(
'ip_address' =>$this->input->ip_address(),
'first_name' =>$this->input->post('firstname'),
'last_name' =>$this->input->post('lastname'),
'phone' =>$this->input->post('phone'),
'email' =>$this->input->post('email'),
'group_id' =>$this->input->post('role'),
'password' =>$this->input->post('password'),
'image' =>$upload['file_name'],
'date_of_registration' =>date('Y-m-d')
);
print_r($data);exit;
$user_id = $this->admin_model->insert_user($data);
$user_group = array(
'user_id' => $user_id,
'group_id' => $this->input->post('role')
);
$this->admin_model->insert_group_user($user_group);
echo "<p style='color:red;'>You are successfully registerd.</p>";
}
}
else
{
echo "<p style='color:red;'>".validation_errors()."</p>";
}
}
}
So how to resolve this issue?What should I have to change in my code?
As I said, the problem is probably in the data you send to backend. If you want to submit AJAX with input file, use FormData.
Try this:
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = new FormData($('#signup_form')[0]);
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
processData: false,
contentType: false,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
Try this:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php :
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
This will upload the file.
P.S.: Change the code as per CI method.
var data = jQuery(this).serialize();
this refers to document

Image not getting posted with ajax(without submitting the form)

My form is -
<form id="fileupload" method="post" enctype="multipart/form-data">
<input type="file" id="headerimage" spellcheck="true" class="typography" name="headerimage">
</form>
My ajax code is -
var fileData = new FormData($('#fileupload'));
fileData.append('imagefile', $('#headerimage')[0].files);
$.ajax({
type : 'post',
data : fileData,
url : 'UploadImage.php',
dataType: 'json',
processData: false,
success : function(data)
{
alert("done");
},
});
Php code -
<?php
# Data Base Connection
require_once('conn/dbConn.php');
var_dump($_REQUEST);
if (!empty($_FILES)) {
var_dump($_FILES);
}
Please Help. On the php page i am not getting file data.
HTML CODE:
<form id="fileupload" method="post" enctype="multipart/form-data">
<input name="userImage" id="uploadForm" type="file" class="inputFile" />
</form>
AJAX :
<script type="text/javascript">
$(document).ready(function (e){
$("#fileupload").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "UploadImage.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#targetLayer").html(data);
},
error: function(){}
});
}));
});
</script>
Use this javascript
$(document).on("submit", "#fileupload", function(event)
{
event.preventDefault();
$.ajax({
url: 'UploadImage.php',
type: 'POST',
data: new FormData(this),
dataType: 'json',
processData: false,
contentType: false,
success: function (data, status)
{
}
});
});
Try this...
//Image will upload without submit form
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
</div>
</form>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('change',(function(e) {
e.preventDefault();
$.ajax({
url: "UploadImage.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
{
}
});
}));
});
</script>
UploadImage.php
<?php
if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
JS code -
var form = document.getElementById('fileupload');
var fileInput = document.getElementById('headerimage');
var file = fileInput.files[0];
var formData = new FormData();
var filename = '';
formData.append('file', file);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
filaname = xhr.responseText;
}
}
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.send(formData);
PHP code -
<?php
# Data Base Connection
require_once('conn/dbConn.php');
if (!empty($_FILES)) {
$file = $_FILES;
if ($file['file']['error'] == 0) {
$name = explode('.', $file['file']['name']);
$newName = "header.".$name[count($name)-1];
if (move_uploaded_file($file['file']['tmp_name'], "../assets/Themes/Default/".$newName)) {
echo $newName;
exit;
}
} else {
echo "";
exit;
}
} else {
echo "";
exit;
}

Modal Pop Up not saving to db when button inside is clicked

I am new with jquery and ajax, so please be patient.
I have this link:
<a href="#message" style="text-decoration:none" class="common2 simple3" >Message</a>
that shows this pop up when clicked:
<div id="message" class="modalDialog">
<div>
<h3>Create A Message</h3>
<form id="msgForm" name="msgForm" action="#" method="post">
<textarea id = 'msgContent' cols="48" rows="10" ></textarea>
<br>
<div id="create_btn">
<a href='' id = 'send' class="common simple2" style='margin-left:50px;text-decoration: none;'>Send</a>
</div>
<div id="cancel_btn">
<a href="#close" class="common simple2" style='margin-left:40px;text-decoration: none;'>cancel</a>
</div>
</form>
</div>
</div>
when I entered text in the textarea and show its content by alert(msgContent) in the script below, it shows
$(document).ready(function()
{
$("#send").click(function(e)
{
e.preventDefault();
var msgContent = $("#msgContent").val();
alert(msgContent);
$.ajax({
url: 'message.php?message='+ msgContent,
type: 'GET',
dataType: 'json',
context: this,
success: function(result)
{
//if (result == true)
$(this).html('Send');
}
});
})
})
but when I try to pass it to a php page through ajax, it won't pass. What could be wrong?
this is message.php
$message = $_POST['message'];
$result = false;
$sql="INSERT INTO MESSAGE_LOG (sender,recepient, message)
VALUES($viewer,$viewed,$message)";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
You need to read the value from $_GET:
$message = $_GET['message'];
Or use the post method, with data attribute:
$(document).ready(function()
{
$("#send").click(function(e)
{
e.preventDefault();
var msgContent = $("#msgContent").val();
alert(msgContent);
$.ajax({
url: 'subscribe.php',
type: 'POST',
data: {message: msgContent},
//dataType: 'json', from your php I don't that that you are looking for json response...
context: this,
success: function(result)
{
//if (result == true)
$(this).html('Send');
}
});
})
})
Your JS should be this:
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
var msgContent = $("#msgContent").val();
$.ajax({
url: 'message.php',
type: 'POST',
dataType: 'json',
data: {message: msgContent},
context: this,
success: function(result) {
alert('Message has been sent');
}
});
});
});
And your PHP this:
$message = $_POST['message'];
$result = false;
$sql="INSERT INTO MESSAGE_LOG (sender,recepient, message)
VALUES($viewer,$viewed,'$message')";
if (!mysqli_query($connection,$sql)) {
die('Error: ' . mysqli_error($connection));
}

Categories