view:
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
product_name = $("#product_name").val();
color = $("#colorWell").val();
$.ajax({
type:"POST",
data:{"product_name":product_name, "color":color},
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
alert(data);
}
});
});
});
</script>
<input type="text" class="form-control" id="product_name" name="product_name">
<input type="color" id="colorWell" name="color">
<input type="file" id="product_image" name="product_image[]" multiple>
<input type="submit" class="btn btn-primary" id="submit" name="submit">
controller:
public function products()
{
$product_name = $this->input->post('product_name');
$color = $this->input->post('color');
$dataInfo = array();
$files = $_FILES;
$cpt = count($_FILES['product_image']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['product_image']['name']= $files['product_image']['name'][$i];
$_FILES['product_image']['type']= $files['product_image']['type'][$i];
$_FILES['product_image']['tmp_name']= $files['product_image']['tmp_name'][$i];
$_FILES['product_image']['error']= $files['product_image']['error'][$i];
$_FILES['product_image']['size']= $files['product_image']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$dataInfo[] = $this->upload->data();
}
$data = array(
'product_name' => $product_name,
'color' => $color,
'product_image' => implode(",",$dataInfo['product_image']),
);
$result_set = $this->db->insert('add_product',$data);
if($sql == true)
{
echo 'New Product Added';
}
else
{
echo 'Unable to Proceed!';
}
}
private function set_upload_options()
{
$config = array();
$config['upload_path'] = ''.base_url().'resource/product/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
In this code I am trying to insert and wants to move an image into a folder. But Now, problem is that when I click on submit button it throw an error as show in below:
Message: Undefined index: product_image
and query looks:
INSERT INTO `product` (`product_name`, `color`, `product_image`) VALUES ('men hoodies','#004080', NULL)
I don't know where am I doing wrong. So, How can I solve this issue? Please help me.
Thank You
Send all formdata with file in your ajax.
HTML code like this...
<form method="POST" id="YourFormID" enctype="multipart/form-data">
<input type="text" class="form-control" id="product_name" name="product_name">
<input type="color" id="colorWell" name="color">
<input type="file" id="product_image" name="product_image[]" multiple>
<input type="submit" class="btn btn-primary" id="submit" name="submit">
</form>
Ajax code here....
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var formData = new FormData($('form#YourFormID')[0]);
$.ajax({
type:"POST",
data:formData,
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
alert(data);
}
});
});
});
</script>
You are not send file in your ajax request. therefore not found index product_image
You didn't submit the files data.
Use formData to upload files data, and append any other input you like to add to formData :
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
product_name = $("#product_name").val();
color = $("#colorWell").val();
var formData = new FormData();
$.each($("#product_image"), function (i, obj) {
$.each(obj.files, function (j, file) {
formData.append('product_image[' + i + ']', file);
});
});
formData.append('product_name', product_name);
formData.append('color', color);
$.ajax({
type:"POST",
data:formData,
processData: false,
contentType: false,
url:"<?php echo base_url(); ?>admin/products",
success:function(data){
alert(data);
}
});
});
});
</script>
use array_column like below to add get all product_image values
implode(",",array_column($dataInfo, 'product_image'))
Related
I´m using an image uploading jQuery script and a short php script. They´re both included inside of the mainsite.php file.
Everything is working fine expect the transfer of the php variable $usr_id.
How can I send the php variable $usr_id via AJAX to my server sided script correctly?
php code
$user = JFactory::getUser();
$usr_id = $user->get('id');
This is my try:
jQuery(function ($) {
$(document).ready(function () {
$("#but_upload").click(function () {
var fd = new FormData();
var files = $('#file')[0].files;
var userid = <?php echo $usr_id ?>;
if (files.length > 0) {
fd.append('file', files[0]);
fd.append('userid', userid);
$.ajax({
url: 'imageupload/upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function (response) {
if (response != 0) {
$("#img").attr("src", response);
} else {
alert('file not uploaded');
}
},
});
} else {
alert("Please select a file.");
}
});
});
})
Edit: this is the form field code
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div >
<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
After I've uploaded an image my page refreshes and I'm not sure how to stop that from happening. I do have e.preventDefault().
I do know that it might have to do with this line
if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
Here is my code
$(document).ready(function(){
var dropZone = document.getElementById('drop-zone');
$(".upload-area").on('drop', function(e){
e.preventDefault();
var files_list = e.originalEvent.dataTransfer.files;
var formData = new FormData();
for(i = 0; i < files_list.length; i++){
formData.append('file[]', files_list[i]);
}
uploadData(formData);
dropZone.ondragover = function(e){
return false;
}
dropZone.ondragleave = function(e){
return false;
}
});
function uploadData(formdata){
$.ajax({
url: 'upload.php',
type: 'post',
data: formdata,
contentType: false,
processData: false,
dataType: 'json',
success: function(response){
addThumbnail(response);
}
});
}
function addThumbnail(data){
var len = $("#uploadfile div.thumbnail").length;
var num = Number(len);
num = num + 1;
var src = data.src;
// console.log(len);
$("#thumbnail_"+num).append('<img src="'+src+'" width="100%" height="78%">');
}
my upload.php
$allowed = ['png', 'jpg'];
foreach($_FILES['file']['name'] as $key => $name)
{
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
if(in_array($ext, $allowed) && move_uploaded_file($temp, 'uploads/'.$name))
{
$return_arr = array("name" => $filename,"size" => $filesize);
}
echo json_encode($return_arr);
}
my index.php
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" id="file" multiple>
<!-- Drag and Drop container-->
<div class="upload-area" id="drop-zone">
<h1>Drag and Drop file here<br/>Or<br/>Click to select file</h1>
</div>
</form>
Put submit button in hidden format. Follow below steps.
In HTML,
<input type="submit" id="submitBtn" style="display:none;">
In Javascript,
function submitMe() {
$("#submitBtn").trigger("click");
}
$(".upload-area").on('drop', function(e){
----
----
submitMe();
});
I have this view
<div class="w3-row w3-padding-64">
<div class="w3-twothird w3-container">
<form id='create_delivery' method="post" class="form-horizontal"
enctype="multipart/form-data">
from <input type="text" name="first_address"><br>
To <input type="text" name="second_address" ><br>
<label>weight</label>
<input type="number" name="weight" ><br>
<label>price</label>
<input type="number" name="price" ><br>
<label>description</label><br>
<textarea name="description"></textarea>
<br>
<input type="submit" value="Submit">
</form>
</div>
</div>
and I sent a post request by ajax to the controller method
$(document).ready(function(){
$("#create_delivery").submit(function(evt){
var postData = $(this).serialize();
$.ajax({
url: baseURL + "deliverys/create_delivery",
type:'post',
data:postData,
dataType:'json',
success:function(data){
alert('delivery created');
}
});
evt.preventDefault();
});
});
this is the controller
public function create_delivery(){
if(isset($_POST)):
$first_address= $this->input->post('first_address');
$second_address= $this->input->post('second_address');
$description= $this->input->post('description');
$Weight= $this->input->post('Weight');
$price= $this->input->post('price');
$data = array(
"first_address"=>$first_address,
"second_address"=>$second_address,
"description"=>$description,
"Weight"=>$Weight,
"price"=>$price
);
$this->deliverys_model->create_delivery($data);
endif;
}
the problem that all the values are coming null,
it works when I send the post request without ajax
but with ajax the values are NULL
Error Number: 1048
INSERT INTO deliverys (first_address, second_address, description, ready_to_buy, Weight, price) VALUES (NULL, NULL, NULL, NULL, NULL, NULL)
I think you not getting form data with var postData = $(this).serialize().
Try like this $("#create_delivery").serialize()
If there is no <input type="file"> in form don't use enctype="multipart/form-data"
$(document).ready(function(){
$("#create_delivery").submit(function(evt){
evt.preventDefault();
$.ajax({
url: baseURL + "deliverys/create_delivery",
type:'POST',
data:$("#create_delivery").serialize(),
dataType:'json',
success:function(data){
alert('delivery created');
}
});
evt.preventDefault();
});
});
Try these
$first_address = $_POST['first_address'];
$second_address = $_POST['second_address'];
$description = $_POST['description'];
$Weight = $_POST['weight'];
$price = $_POST['price'];
Instead of
$first_address= $this->input->post('first_address');
$second_address= $this->input->post('second_address');
$description= $this->input->post('description');
$Weight= $this->input->post('Weight');
$price= $this->input->post('price');
I didn't know the context of $this->input in your code, maybe you could show more of your code, but above code should be work.
you need change 'type' to 'method'
$.ajax({
url: baseURL + "Trips/create_trip",
method:'POST',
data:postData,
dataType:'json',
success:function(data){
alert('Trip created');
}
});
.serialize(); is used to create get method string ... if you want to post data use ajax change your js with
$("#create_delivery").submit(function(evt){
evt.preventDefault();
var first_address = $( "input[name='first_address']" ).val();
var second_address = $( "input[name='second_address']" ).val();
var weight = $( "input[name='weight']" ).val();
var price = $( "input[name='price']" ).val();
var description = $( "input[name='description']" ).val();
$.ajax({
url: baseURL + "deliverys/create_delivery",
type:'post',
data : {first_address:first_address,second_address:second_address,weight:weight,price:price,description:description},
dataType:'json',
success:function(data){
alert('delivery created');
}
});
});
I select an image, write something and then click submit. Once I click submit it posts to the DB, shows progress bar of upload successfully BUT the upload.php file is never called.
Question: What is wrong with my code, that is preventing the upload.php file from being called in the action="".
It was working at one point in time but I can't remember what changes I made for it.
UPDATED SCRIPT:
$('#feed_form').submit(function(e) {
var data = new FormData(this);
var url = $(this).attr("action");
if($('#file12').val()) {
$("#progress-div").show("slow");
e.preventDefault();
$.ajax({
type: "POST",
url: "scripts/universal/upload.php",
data: data,
processData: false,
contentType: false,
success: function() {
$("#success_post").slideDown();
setTimeout(function() {
$('#success_post').slideUp();
}, 3000);
},
uploadProgress: function (event, position, total, percentComplete){
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").html('<div id="progress-status">' + percentComplete +' %</div>')
},
resetForm: true
});
return false;
}
});
<form name="feed_form" id="feed_form" method="post" enctype="multipart/form-data">
<textarea class="list-group-item p-x-md" id="textarea_writing" name="textarea_writing" style="resize:none;padding:5px;width:100%;" placeholder="What's going on....."></textarea>
<script type="text/javascript">
var textarea = document.getElementById("textarea_writing");
textarea.oninput = function() {
textarea.style.height = "";
textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px";
};
</script>
<span id="show_error_message"></span>
<br>
<label class="custom-file" style="width:100%;">
<input type="file" name="file12" id="file12" class="custom-file-input" onchange="setfilename(this.value);" accept=".jpg, .jpeg, .gif, .png, .mp4" required>
<span class="custom-file-control">Select photo, video or gif...</span>
</label>
<br><br>
<button type="submit" id="btnSubmitFormClick">Post</button>
</form>
PHP:
if(!empty($_FILES)) {
if(is_uploaded_file($_FILES['file12']['tmp_name'])) {
$sourcePath = $_FILES['file12']['tmp_name'];
$targetPath = "images/uploads/".$_FILES['file12']['name'];
move_uploaded_file($sourcePath,$targetPath);
shell_exec("ffmpeg -f mp4 -i images/uploads/".$_FILES['file12']['name']." -ss 00:00:5.000 -vframes 1 images/uploads/".basename($_FILES['file12']['name'], ".mp4").".png");
//This line does not affect the code, it works perfectly fine when I try it with some different JS
}
}
You've not specified the url in $.ajax(). Maybe that's the only problem
Below is the corrected code, try it and let me know if it worked or not
<script type="text/javascript">
$(document).ready(function () {
$('#feed_form').submit(function (e) {
var url = $(this).attr("action");
var data = new FormData(this);
if ($('#file12').val()) {
if (!$("#btnSubmitFormClick").val()) {
$("#show_error_message").innerHTML = "Please write something before clicking submit";
} else {
$("#progress-div").show("slow");
e.preventDefault();
$.ajax({
url: url,
data: data,
cache: false,
processData: false,
contentType: false,
success: function () {
$("#success_post").show();
},
uploadProgress: function (event, position, total, percentComplete) {
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").html('<div id="progress-status">' + percentComplete + ' %</div>')
},
resetForm: true
});
return false;
}
}
});
$("#btnSubmitFormClick").click(function () {
document.getElementById("close_status_modal").click();
});
$("#feed_form").submit(function (e) {
$.ajax({
type: "POST",
url: "scripts/universal/post.php",
data: $("#feed_form").serialize(), // serializes the form's elements.
success: function (data) {
$('#textarea_writing').val('');
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
</script>
<form name="feed_form" id="feed_form" action="upload.php" method="post" enctype="multipart/form-data">
<textarea class="list-group-item p-x-md" id="textarea_writing" name="textarea_writing" style="resize:none;padding:5px;width:100%;" placeholder="What's going on....."></textarea>
<script type="text/javascript">
var textarea = document.getElementById("textarea_writing");
textarea.oninput = function () {
textarea.style.height = "";
textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px";
};
</script>
<span id="show_error_message"></span>
<br>
<label class="custom-file" style="width:100%;">
<input type="file" name="file12" id="file12" class="custom-file-input" onchange="setfilename(this.value);" accept=".jpg, .jpeg, .gif, .png, .mp4" required>
<span class="custom-file-control">Select photo, video or gif...</span>
</label>
<br><br>
<button type="submit" id="btnSubmitFormClick" style="display:none;">Post</button>
</form>
I ended up using the following code to solve my problem:
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file12").files[0];
var formdata = new FormData();
formdata.append("file12", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.open("POST", "scripts/universal/upload.php");
ajax.send(formdata);
}
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
$("#progress-div").show();
_("progressBar").value = Math.round(percent);
}
function completeHandler(event) {
_("progressBar").value = 0;
$("#progress-div").hide();
}
I have a html form with 2 input filed and a file upload form and i want to send these data to some index.php file using ajax what i did so far is
<form class="col-md-3" id="form" name="reg" method="post" action="index.php" enctype="multipart/form-data">
<label>Name</label>
<input type="text" name="name" class="form-control" id="name">
<label>Address</label>
<input type="text" name="address" class="form-control">
<div id="sugg">
</div>
<input type="file" name="file">
<input type="button" name="submit" class="btn-default" id="btn" value="submit">
</form>
jquery for send data using ajax is
$("#btn").click(function() {
$.ajax({
url: "index.php",
type: "POST",
data: new FormData($('form')[0]),
cache: false,
conentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
php file has just this
echo $_POST["name"];
but in my browser window i am undefined index
I found similar questions but all that doesn't solved my problem that's why i asking your help please help me to find my error
I am create below code according to my need and you can make changes according to your requirement:
when you click upload/select file button use this function :
$('input[type=file]').on('change', function(e){
e.preventDefault();
$this = $(this);
if($this.prop("files")){
if(setImagestoUpload(e, $this.prop("files"), $this.attr("name"))){
var reader = new FileReader();
reader.onload = function(e){
$('.brandLogo img').attr("src", e.target.result);
$this.parent().prev("img.imageSelection").attr("src", e.target.result);
};
reader.readAsDataURL(this.files[0]);
}
}
});
function setImagestoUpload(e, $file, name){
e.preventDefault();
var type = [];
var isSize = [];
$($file).each(function(i, v){
type[i] = isImage(v);
isSize[i] = isValidSize(2, v.size);
});
if($.inArray(false, type) === -1){
if($.inArray(false, isSize) === -1){
/*if(checkTotalFileInputs() > 1 && files.length>0){
$.each($file, function(ind, val){
files[name] = val;
});
files[name] = $file[0];
}else{
files = $file;
}*/
formData.append(name, $file[0]);
console.log(files);
return true;
}else{
alert("Error: Upload max size limit 2MB");
}
}else{
alert("Please select only image file format to upload !");
return false;
}
}
function isImage(file){
var type = file.type.split("/");
if(type[0] === "image"){
return true;
}else{
return false;
}
}
and when you submit form then use below function:
function fileAndFormSubmit(ev, $this, get, options){
var defaults = {
redirect : false,
redirectTo : "#",
redirectAfter : 5000
};
var settings = $.extend({}, defaults, options);
removeErrorAndSuccess();
var $form = $($this).parent('form');
/*var formData = new FormData();
if(files.length > 0){
$.each(files, function(key, val){
formData.append(key, val);
});
}*/
var doc = {
data : $form.serialize()
};
formData.append("doc", doc.data);
/*Call to ajax here*/
}