file upload is not working with ajax and codeigniter - ajax

i have a add form.added data using ajax and codeigniter.there is a file upload in that form.but file is not uploaded.other datas are added.but the file is not uploaded to the specified folder.
View file
<div class="row">
<div class="col-xs-6">
<label for="txtname">Title of Quotation Request :</label>
<input type="text" name="txtTitle" class="form-control" id="txtname" value="<?php
if (!empty($service)) {
echo $service;
}
?>" required>
</div>
<div class="col-xs-6">
<label for="txtcustomer">Select Customer :</label>
<select class="form-control" name="customer" id="customer" required="required">
<option value="">----Select------</option>
<?php
foreach ($customers as $customer) {
echo ' <option value="' . $customer->usr_id . '">' . $customer->usr_name . '</option>';
}
?>
</select>
<input type="hidden" name="" value="sbMerchant">
</div>
<div class="col-xs-12">
<label for="txtattachments">Drawing Attachments :</label>
<input name="txtattachments" type="file" id="txtattachments">
</div>
Ajax function
<script type="text/javascript">
$('#rfqsubmit').click(function () {
//var title = $('#title').val();
alert($('#txtattachments').val());
var form_data = {
title: $('#txtname').val(),
merid: $('#mermerchant').val(),
userid: $('#customer').val(),
description: $('#txtrequirement').val(),
reqid: $('#requirementid').val(),
shipmethod: $('#shipmethod').val(),
shiplocation: $('#shiplocation').val(),
txtattachments: $('#txtattachments').val(),
bidclose: $('#txtbidclose').val(),
shipcurrency:$('#shipcurrency').val(),
txtproduct:$('#txtproduct').val(),
txtunit:$('#txtunit').val(),
txtquantity:$('#txtquantity').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo base_url() ?>moderator/RFQ/addoffline",
type: 'POST',
data: form_data,
dataType:"Json",
success: function(data) {
var last_inserted_id = data.id;
window.location.href ="<?php echo base_url() ?>moderator/RFQ/viewrfq/"+last_inserted_id;
// window.location.href ="<?php //echo base_url() ?>moderator/RFQ/viewrfq/"+ form_data.reqid;
// alert('added Successfully');
}
});
return false;
});
</script>
Controller
public function addoffline() {
$this->load->helper(array('form', 'url'));
$this->load->helper('file');
$ip = $_SERVER['REMOTE_ADDR'];
$config['upload_path'] = 'assets/images/rfqimages';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '2024';
$config['max_height'] = '1768';
$config['width'] = 75;
$config['height'] = 50;
if (isset($_FILES['txtattachments']['name'])) {
$filename = "-" . $_FILES['txtattachments']['name'];
$config['file_name'] = substr(md5(time()), 0, 28) . $filename;
}
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$field_name = "txtattachments";
$this->load->library('upload', $config);
if (!$this->upload->do_upload('txtattachments')) {
//no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
} else {
$dat = array('upload_data' => $this->upload->data());
$this->resize($dat['upload_data']['full_path'], $dat['upload_data']['file_name']);
}
$data7 = array(
'rfq_title' => $this->input->post('title'),
'rfq_detail' => $this->input->post('description'),
'rfq_merchantid' => $this->input->post('merid'),
'rfq_userid' => $this->input->post('userid'),
'rfq_requirementid'=>$this->input->post('reqid'),
'rfq_shipmethod'=>$this->input->post('shipmethod'),
'rfq_shiplocation'=>$this->input->post('shiplocation'),
'rfq_bidclosing'=>strtotime($this->input->post('bidclose')),
'rfq_shipcurrency'=>$this->input->post('shipcurrency'),
'rfq_productid'=>$this->input->post('txtproduct'),
'rfq_unit'=>$this->input->post('txtunit'),
'rfq_quantity'=>$this->input->post('txtquantity'),
'rfq_resource'=>2,
'rfq_dated'=>time(),
'rfq_status'=>0,
'rfq_ipadd'=>$ip
);
$inserted_id= $this->requirement_model->forminsert($data7);
$response=array('id'=>$inserted_id,'message'=>"inserted successfully");
echo json_encode($response);
die();
}

Instead of taking fields like that, do like this
var form_data = new FormData("id of the foem");
Then pass this in ajax like this,
data: form_data,
Make sure, enctype is set for form
enctype="multipart/form-data"
In codeingiter,
<?php echo form_open_multipart('moderator/RFQ/addoffline');?>

Try This:
var formData = new FormData($(this)[0]);
$.ajax({
url: "<?php echo base_url() ?>moderator/RFQ/addoffline",
type: "POST",
data: formData,
async: false,
success:function(data){
var last_inserted_id = data.id;
window.location.href ="<?php echo base_url() ?>moderator/RFQ/viewrfq/"+last_inserted_id;
}
},
cache: false,
contentType: false,
processData: false
});
Check what data is coming inside addoffline() action using
print_r($this->input->post()) and print_r($_FILES) functions. According to your output you can implement your code.
Your problem will be solved.

Related

I am send dropzone file through ajax but it show ERROR : "You did not select a file to upload" in Codeigniter 3

View
Image
<!------------------------ Bootstarp Source File ------------------------>
<link rel="stylesheet" href="<?php echo base_url('assets/source_files/bootstrap.min.css');?>" >
<!------------------------ Dropzone Source File ------------------------>
<link rel="stylesheet" href="<?php echo base_url('assets/source_files/dropzone.min.css');?>" >
<label class="form_lable">Select Image </label>
<div class="dropzone-container col-md-6" id="demo-dropzone" >
`your text`
<p >
<div class="dz-default dz-message" >
<div class="dz-icon">
<i class="demo-pli-upload-to-cloud icon-5x"></i>
</div>
<div>
<span class="dz-text">Drop files to upload</span>
<p class="text-sm text-muted">or click to pick manually</p>
</div>
</div>
<div class="fallback">
<input type="file" name="userfile" id="userfile" />
</div>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="submit_btn">Submit</button>
</div>
</form>
">
">
">
$('#demo-dropzone').dropzone({
url:"",
autoProcessQueue: false,
addRemoveLinks: true,
multiple:false,
uploadMultiple:true, // uplaod files in a single request
parallelUploads: 1,
maxFiles: 1,
maxFilesize: 500,
acceptedFiles: ".jpg, .png, .jpeg",
init: function() {
var myDropzone = this;
myDropzone.on('maxfilesexceeded', function(file) {
this.removeAllFiles();
this.addFile(file);
});
this.on("removedfile", function(file) {
});
// Update selector to match your button
$("#submit_btn").click(function(e) {
e.preventDefault();
myDropzone.processQueue();
});
this.on("successmultiple", function(file, response) {
if (response && file) {
console.log(response);
}
});
}
});
# Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Image_upload extends CI_Controller
{
public function index(){
$this->load->view('image_send');
}
`File upload funxction`
public function do_upload(){
$image_name = $_FILES['file']['name'][0];
$target= $_FILES['file']['tmp_name'][0];
$target_file = basename($image_name);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$custom_file=basename(uniqid().'.'.$imageFileType);
if(is_dir('upload_image')){
echo "is present";
}
else{
mkdir('upload_image');
}
$config['upload_path'] = 'upload_image/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $image_name;
$this->upload->initialize($config);
$this->load->library('upload',$config);
if ($this->upload->do_upload('userfile'))
{
$data = array('upload_data' => $this->upload->data());
print_r($data);
}
else
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
}
?>
First of all you need to fix your view to have tag to warp out your input.
<form role="form" id="yourFormId" action="#" method="post" enctype='multipart/form-data'></form>
Second, get your form id and set the ajax like this
var frm = $('#yourFormId');
frm.submit(function (e) {
e.preventDefault();
var form_data = new FormData();
var file_data = $('#yourFileInputID').prop('files')[0];
form_data.append('file', file_data);
$.ajax({
type : "POST",
url : TheUrl,
processData : false,
contentType : false,
cache : false,
data : form_data,
dataType : 'json',
success: function (data) {
//Your Code Goes Here..//
}, error: function () {
// Your Code Goes Here //
}
});
});

Image is not uploading in CI

I am new in CI and I am trying to upload image but dont know why its not uploading,
Here is my view,
<form action="<?php echo site_url('admin/test/'.$param2.'/add'); ?>" enctype="multipart/form-data" method="post" id = 'mcq_form'>
<input type="hidden" name="question_type" value="mcq">
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="attachment" name="attachment" onchange="changeTitleOfImageUploader(this)">
<label class="custom-file-label" for="attachment"><?php echo get_phrase('attachment'); ?></label>
</div>
</div>
<div class="text-center">
<button class = "btn btn-success" id = "submitButton" type="button" name="button" data-dismiss="modal"><?php echo get_phrase('submit'); ?></button>
</div>
</form>
<script>
$('#submitButton').click( function(event) {
$.ajax({
url: '<?php echo site_url('admin/test/'.$param2.'/add'); ?>',
type: 'post',
data: $('form#mcq_form').serialize(),
success: function(response) {
if (response == 1) {
success_notify('<?php echo get_phrase('question_has_been_added'); ?>');
}else {
error_notify('<?php echo get_phrase('no_options_can_be_blank_and_there_has_to_be_atleast_one_answer'); ?>');
}
}
});
showLargeModal('<?php echo site_url('modal/popup/test/'.$param2); ?>', '<?php echo get_phrase('test'); ?>');
});
</script>
on Controller I am trying to get image data but dont know why its not fetching,
print_r($_FILES['attachment']['name']);
die();
I don't understand, what I am missing. Please help me out.
You can try it like this
<input type="file" name="logo" class="form-control" value="">
in your controller
$logo = '';
if (!empty($_FILES['logo']['name'])) {
/* Conf Image */
$file_name = 'profile_' . time() . rand(100, 999);
$configImg['upload_path'] = './uploads/profile/';
$configImg['file_name'] = $file_name;
$configImg['allowed_types'] = 'png|jpg|jpeg';
$configImg['max_size'] = 2000;
$configImg['max_width'] = 2000;
$configImg['max_height'] = 2000;
$configImg['file_ext_tolower'] = TRUE;
$configImg['remove_spaces'] = TRUE;
$this->load->library('upload', $configImg, 'logo');
if ($this->logo->do_upload('logo')) {
$uploadData = $this->logo->data();
$logo = 'uploads/profile/' . $uploadData['file_name'];
} else {
$this->custom_errors['logo'] = $this->logo->display_errors('', '');
}
}

ajax form request from a while - confuse variable

I want to send a form with a button from a while, but I have a problem. If post the button, the form confuse the variable. E.g: i post the button with id 1, and the script get the variable from the last input.
Code:
index:
<?php
$res = getProdus();
foreach($res as $row) { ?>
<form action="addtocart.php" method="POST">
<div class="col-12 col-sm-6 col-md-4 single_gallery_item women wow fadeInUpBig" data-wow-delay="0.2s">
<div class="product-img">
<img src="img/product-img/product-1.jpg" alt="">
<div class="product-quicview">
<i class="ti-plus"></i>
</div>
</div>
<div class="product-description">
<h4 class="product-price">$39.90</h4>
<p>Jeans midi cocktail dress</p>
<input type="hidden" name="addtcart" value="<?=$row['ID'];?>">
<button type="submit" class="add-to-cart-btn">ADD TO CART</button>
</div>
</div>
</form>
<?php } ?>
the ajax request:
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'addtcart' : $('input[name=addtcart]').val()
};
$.ajax({
type : 'POST',
url : 'addtocart.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
and the addtocart.php
<?php
include("includes/functions.php");
session_start();
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if (empty($_POST['addtcart']))
$errors['addtcart'] = 'Este necesar produsul id-ului.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$ok = AddToCart(filtrare($_POST['addtcart']), getSpec("username", "users", "email", $_SESSION['magazin-user']));
if($ok == 1) {
$data['success'] = true;
$data['message'] = 'Success!';
} else {
$data['success'] = false;
$errors['mysqli'] = "Nu s-a realizat bine query-ul.";
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
Replace your button code with this
<button type="submit" value="<?=$row['ID'];?>" class="add-to-cart-btn">ADD TO CART</button>
and after that replace you
make changes to your script code
$(".add-to-cart-btn").click(function() {
var formData = {
'addtcart' : $(this).val()
};
.
.
.
and your rest of the code.

codeigniter dependent dropdown error

This is my code. It does not work with codeigniter 3.0 and jquery. I need to use dropdown dependent so I made that but it will be display "Error occur..." by alert() after choosing any item in first dropdown.
Please have a look to my source code. I don't know what is wrong. Thanks everyone
VIEW:
<script type="text/javascript">
$(document).ready(function(){
$('#senf').on('change', function(){
var senf_id = $(this).val();
if(senf_id == '')
{
$('#raste').prop('disabled', true);
}
else
{
$('#raste').prop('disabled', false);
$.ajax({
url:"<?php echo base_url() ?>index.php/shoppings/get_subgroup/",
type: "POST",
data: {'senf_id' : senf_id},
dataType: 'json',
success: function(data){
alert('okkk');
},
error: function(){
alert('Error occur...!!');
}
});
}
});
});
</script>
<div class="form-group ">
<label for="group_name" class="control-label col-lg-2">group 1</label>
<select id="senf" name="group">
<option value="" selected="selected">select</option>
<?php
foreach ($get_groups as $value) {
$group_id = $value['group_shop_id'];
$group_name = $value['group_shop_name'];
?>
<option value="<?php echo $group_id; ?>"> <?php echo $group_name; ?> </option>
<?php } ?>
</select>
<label for="raste" >group 2</label>
<select id="raste" name="raste">
<option value="">select</option>
</select>
</div>
CONTROLLER:
public function get_subgroup(){
$id = $this->input->post('senf_id');
$ajax_get_subgroup = $this->shopping_model->ajax_get_subgroup($id);
$pro_select_box = '';
$pro_select_box .= '<option value="">Select Province</option>';
foreach($ajax_get_subgroup as $ajax_get_subgroup_value){
$pro_select_box .= '<option>'. $ajax_get_subgroup_value->cat_shop_name .'</option>';
}
echo json_encode($pro_select_box);
}
MODEL:
public function ajax_get_subgroup($id){
$query = $this->db->get_where('cat_shopping_group', array('group_shop_id' => $id));
return $query->result();
}
try this
Controller
public function ajax_get_subgroup()
{
extract($_POST);
$tmp='';
$sql = "SELECT * FROM cat_shopping_group where group_shop_id=$id";
$data = $this->db->query($sql)->result_array();
$tmp .="<option value=''>-- Select --</option>";
foreach($data as $row)
{
$tmp .="<option value='".$row['your_id']."'>".$row['cat_shop_name ']."</option>";
}
die($tmp);
}`
AJAX
function get_data()
{
var id = $('#senf').val()
datana= 'id='+id
$.ajax({
type: 'POST',
url: '<?=base_url()?>your_controller/ajax_get_subgroup',
data: datana,
error: function(data) {
alert('Failed');
},
success: function(data)
{
$('#raste').html(data)
}
})
}
Views
<select id="senf" name="group" onchange='ajax_get_subgroup();'>
<option value="" selected="selected">select</option>
<?php
your code
?>
</select>
<select id="raste">
</select>
Hope this help.

Form submission using AJAX and handling response in Wordpress Website

I have a wordpress website. I have made a contact form and it is POSTed by AJAX.
Here's the code:
<script type="text/javascript">
jQuery(document).ready(function(){
$("#error_box").hide();
$('#contact_form').submit(function(e){
// prevent the form from submitting normally
e.preventDefault();
var na=$("#1").val();
var email2=$("#2").val();
var subject2 = $("#3").val();
var message2 = $("#4").val();
var mydata = "pn2="+na+"&email="+email2+"&subject="+subject2+"&msg="+message2;
alert(mydata);
$("#contact_form").css({"opacity":"0.1"});
$.ajax ({
type: 'POST',
url: $(this).attr.action, // Relative paths work fine
data: mydata,
success: function(){
$("#contact_form").css({"opacity":"1"});
$('#error_box').fadeIn('fast').css({"height": "auto"});
}
});
});
});
</script>
When the form is submitted, I want the error box (#error_box) to display a message according to the data submitted, for example if one of the fields is empty it should display an error, or display a success message if the processing is successful and the form has been mailed. Is there any way I can do this?
[UPDATE]
Here's my contact-form.php file(the action)
<?php if(isset($_POST['pn2']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['msg']))
{
if(empty($_POST['pn2']) || empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['msg'])){
echo 'EMPTY ERROR';
}
else
{
$name = $_POST['pn2'];
$email = $_POST['email'];
$subj = $_POST['subject'];
$msg = $_POST['msg'];
$to = "ankushverma61#gmail.com";
$mail_cont = "FROM: $person_name. \n Email: $email. \n Msg: $msg";
echo "success";
mail($recipient, $subj, $mail_cont) or die("UNABLE TO SEND!!!");
}
}
?>
Form submission using Ajax call
Contact Form
<form action="#" id="contactForm" method="post">
<input class="require" type="text" placeholder="First Name" name="firstName">
<span class="fieldError"></span>
<input class="require" type="text" placeholder="Last Name" name="lastName">
<span class="fieldError"></span>
.
.
.
<input type="submit" value="Submit">
</form>
client side validation with ajax call
jQuery('#contactForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newContactForm = jQuery(this).serialize();
var flag = 0;
jQuery('.require', '#contactForm').each(function(){
var inputVal = jQuery(this).val();
if(jQuery.trim(inputVal) === ""){
flag = 1;
jQuery(this).next().html("Can't be blank");
jQuery(this).next().show();
}
else{
jQuery(this).next().hide();
}
});
if(flag){
return false;
}
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php?action=contactForm",
data: newContactForm,
success:function(data){
jQuery(':input','#contactForm')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
jQuery("#feedback").html(data);
jQuery("#feedback").fadeOut(10000);
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
}
store form data in db and send mail
add the following code in functions.php
wp_enqueue_script('jquery');
add_action('wp_ajax_addContactForm', 'addContactForm');
add_action('wp_ajax_nopriv_addContactForm', 'addContactForm');
function addContactForm(){
global $wpdb;
$first_name = $_POST['firstName']; $last_name = $_POST['lastName'];
$email = $_POST['email'];
.
.
.
if($wpdb->insert('table_name',array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
.
.
.
))===FALSE){
echo "Error";
}
else {
$headers = 'From: xyz <xyz#xyz.com>';
$subject = "Thank you";
$body = "<p>Thank you</p><p>.........</p>";
wp_mail( $email, $subject, $body, $headers);
echo "<div class='success'>Thank you for filling out your information, we will be in contact shortly.</div>";
}
exit;
}
You should use:
$.ajax ({
type: 'POST',
url: $(this).attr.action,
data: mydata,
success: function(response) { // here you receive response from you serverside
$("#contact_form").css({"opacity":"1"});
$('#error_box').html(response).fadeIn('fast').css({"height": "auto"});
}
});
Your server action url: $(this).attr.action, should return message which be inserted in #error_box
First create form like this
<p class="register-message"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register">
</fieldset>
</form>
then bind the click and send ajax call
<script type="text/javascript">
jQuery('#test').on('click', function(e) {
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") {
jQuery('#email-error').show();
return false;
} else {
jQuery('#email-error').hide();
}
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test", // redirect function in function.php
firstname: firstname,
email: email
},
success: function(results) {
//console.log(results);
if (results == "1") {
jQuery('.register-message').text("Email already exist");
} else {
jQuery('.register-message').text("Register successfu");
}
},
error: function(results) {}
});
});
</script>
In function.php add the below code to insert data in table
<?php
//
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test()
{
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='" . $email . "' ");
$res = $wpdb->get_results($q);
if (count($res) > 0) {
echo "1";
} else {
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix . 'test';
$user_id = $wpdb->insert($tablename, $user_data);
echo "0";
}
die;
}

Resources