Upload an excel in my view to display it in the controller - javascript

I want...
Upload an excel file to my server in my view (only temporary because I will only read it, get its data and save it to a DB), then use fopen () on my controller, and open that file that the user uploaded in the view . (I am using CI)
Issue...
When I try to open the file in my controller it does not exist.
What I have...
view
<?php
print_r($_FILES);
$archivo = fopen($_FILES["csv"]["tmp_name"], 'r');
?>
<?php echo form_open_multipart('',array('id' => 'envio', 'role'=>'form')); ?>
<legend>Importar Datos</legend>
<?php if (isset($alerta) && $alerta): ?>
<div class="alert alert-danger">
<?=$alerta ?>
</div>
<?php endif; ?>
<div class="form-group">
<label for="">Archivo CSV</label>
<input type="file" class="form-control" id="csv" name="csv" placeholder="Archivo CSV">
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="1" name="has_header" checked>
El archivo contiene cabeceras
</label>
</div>
<input type="hidden" name="key" value="1">
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
<script type="text/javascript">
function al_inicio()
{
console.log("on submit set");
$( '#envio-t' )
.submit( function( e ) {
console.log('submitting');
e.preventDefault();
$.ajax( {
// url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
dataType: 'script'
} );
} );
}
</script>
Controller_api
function dev_get(){
print_r($_FILES);
$archivo = fopen($_FILES["csv"]["tmp_name"], 'r');
}
Images
This is in View
This is in Controller

Related

Woocommerce - wc_print_notices returns two messages instead of one, what's wrong?

I'm editing woocommerce form-edit-account.php, in this template there is a form that allows users to change name, surname, address etc. I added ajax requests to save the data without reloading the page. The data is saved correctly, so the ajax request works fine. The only step I can't get to work properly are handling error messages.
The problem
when click on submit button and the data is saved successfully, two messages appear.
The first message is the original woocommerce message: "Account details changed successfully", and can be found at https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-form-handler.html#source-view.346. The second message is what I wrote in my functions.php with wc_add_notice.
Expectations
I should only get the message I added to functions.php with wc_add_notice, why am I getting the original message as well? What am I doing wrong ?
Hope someone can help me with this, I can't figure out where the mistake is. I appreciate any help and thank you for any replies.
Js which handles updating fields and error / success message
$(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax Handling Error msg
var $form = $(this);
$.post(
$form.attr('action'),
$form.serialize(),
function(data) {
$('.newdiv').html(data);
}, 'json'
);
//Ajax Save settings
$.ajax({
type: "POST",
data: $(".mts-edit-account").serialize(),
beforeSend: function() {
$(".container_loader").show();
},
success: function(data) {
$(".container_loader").hide();
}
});
});
});
Handling error in functions.php
// Validate - my account
add_action( 'woocommerce_save_account_details_errors', array( &$user, 'save_account_details' ), 10, 1);
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
function save_account_details( &$user ) {
if (isset( $_POST['account_first_name'] ) == '') {
wc_add_notice("<b>Nome</b> è un campo obbligatorio", "error");
$response = wc_print_notices(true);
} else if (isset($_POST['account_first_name']) ) {
wc_add_notice("Modifiche salvate con successo", "success");
$response = wc_print_notices(true);
}
echo json_encode($response);
exit();
}
Example of my form html
<form name="Form" class="mts-edit-account" method="post" action="<?php echo admin_url('admin-ajax.php'); ?>" enctype="multipart/form-data" <?php add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );?> >
<?php do_action( 'woocommerce_edit_account_form_start' ); ?>
<!-- Fist & Last Name Field -->
<div class="row name_surname">
<div class="form-row">
<label class="t3" for="account_first_name">Nome *</label>
<input type="text" placeholder="Inserisci il tuo nome" class="field-settings" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
</div>
<div class="form-row">
<label class="t3" for="account_last_name">Cognome *</label>
<input type="text" placeholder="Inserisci il tuo cognome" class="field-settings" name="account_last_name" id="account_last_name" value="<?php echo esc_attr( $user->last_name ); ?>" />
</div>
</div>
<!-- Other fields -->
<!-- Save Info Settings -->
<div style="margin-bottom: 0px!important;">
<?php wp_nonce_field( 'save_account_details', 'save-account-details-nonce' ); ?>
<button type="submit" class="edit-account-button" name="save_account_details" value="<?php esc_attr_e( 'Save changes', 'woocommerce' ); ?>"><?php esc_html_e( 'Salva modifiche', 'woocommerce' ); ?></button>
<input type="hidden" name="action" value="save_account_details" />
</div>
</form>

How to submit a form using AJAX?

I am trying to submit a form using ajax. However, it is not showing the message that the code is wrong. I push errors the same way on the entire website so that part works.
This is my code:
<script type="text/javascript" src="jquery.js"></script>
<div id="showerrors"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#showerrors').load('errors2.php')
}, 1000);
});
</script>
<form id="formoid" method="post" action="data/newpass.php">
<div class="row2">
<input type="email" class="form-control2" placeholder="email adres" aria-describedby="basic-addon1" name="email" required>
</div>
<div class="row2">
<input type="text" class="form-control2 pull-left" placeholder="Enter code" aria-describedby="basic-addon1" name="captcha" style="width: 70%;" required>
<div class="capbg1">
<input type="text" class="disable1b pull-right" value="<?php echo $capcode3;?>" name="captcha" style="width: 29%;" disabled>
</div>
</div>
<div class="row2"></div>
<div class="row2">
<button type="submit" class="w3-black pull-left" name="req_new_pw">Request new password</button>
</div>
</form>
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : { email: $('#email').val(), captcha: $('#captcha').val() },
});
});
</script>
// newpass.php - action in the form
<?php
error_reporting(E_ALL);
session_start();
ob_start();
$db = mysqli_connect(***);
if (isset($_POST['req_new_pw']))
{
$captcha = mysqli_real_escape_string($db, $_POST['captcha']);
$email = mysqli_real_escape_string($db, $_POST['email']);
if(isset($_SESSION['capcode3']))
{
if($_SESSION['capcode3'] != $captcha)
{
array_push($errors, "- Code is incorrect.");
}
}
}
?>
//errors.php
<?php if (count($errors) > 0) : ?>
<div class="isa_error">
<i class="fa fa-times-circle"></i>
<b>Oops..</b><br>
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
//errors2.php - display errors above form
<?php
include('errors.php');
if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</div>
</h3>
</div>
<?php endif ?>
When i submit the form, nothing happens.
What am i doing wrong?
You don't send $_POST['req_new_pw'] and you are asking if it's set.
You can use serialize() to send all form element by post:
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : $('#formoid').serialize(),
});
});
</script>
Make sure you are setting $_SESSION['capcode3'] either.
This works like a charm:
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
});

Image input wont show in $_FILES

I am trying to update an image in the my database. I have a modal that is loaded with jquery. When clicking on the save modification button, alla the form data shows up except for the image file, which does not show up in the $_FILES in php. I tried all the indication found on the web (php ini file enables file upload, images size is good). The code works if I use that classic submit method, but I don't want a full screen refresh, I need to do it all in ajax. Here is the html:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
alert(data);
var url = '/PubDev/updatePubDev';
$.post(url, data, null, 'json')
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error");
}
})
.fail(function (data) {
alert("ajax error");
})
.always(function () {
});
});
<div class="md-modal md-effect-1" id="updatePubDevModal" >
<div class="md-content">
<div class="modal-header">
<button class="md-close close">×</button>
<h4 class="modal-title">Update Publisher/Developer</h4>
</div>
<form id="updatePubDevFrm" class="dz-clickable dropzone" action="/PubDev/updatePubDev" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="row dropzone">
<div class="col-lg-5">
<div class="form-group">
<label for="pubDevName">System Id of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevIdDisplay" id="pubDevIdDisplay" class="form-control input-large" disabled="true">
<input type="hidden" name="pubDevId" id="pubDevId" >
</div>
<div class="form-group">
<label for="pubDevName">Name of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevName-update" id="pubDevName-update" class="form-control input-large">
</div>
<div class="form-group">
<label for="date-founded">Date Founded</label>
<input type="text" placeholder="Date founded" id="date-founded-update" name="date-founded-update" class="form-control date-picker input-large">
</div>
<div class="form-group">
<label>What type of company is this?</label>
<div class="checkbox-nice">
<input type="checkbox" name="isPub-update" id="isPub-update">
<label for="date-founded-update">
This company is a publisher
</label>
</div>
<div class="checkbox-nice">
<input type="checkbox" name="isDev-update" id="isDev-update">
<label for="isDev-update">
This company is a developer
</label>
</div>
</div>
</div>
<div class="col-lg-7">
<div class="main-box clearfix main-box-frame" >
<header class="main-box-header clearfix">
<h2>Upload Publisher /Developer Logo</h2>
</header>
<div class="main-box-body clearfix imgcontainer center">
<img id="preview" src="" class="pointable" alt="No Image Available" style="max-height:100%; max-width: 100%; "/>
<div class="main-box-body clearfix">
<div id="dropzone" class="drop-zone-frame" >
<input type="file" name="image2" id="image2">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="confirmUpdPubdev" class="btn btn-primary">Save Modifications.</button>
</div>
</form>
</div>
</div>
Here is the php code:
public function updatePubDev() {
$fields = array();
$fields[$this->pubdev->get_id_name()] = $this->input->post('pubDevId');
$fields['name'] = $this->input->post('pubDevName-update');
if ($this->input->post('date-founded'))
$fields['date_founded'] = stampa_data_formato_DATE($this->input->post('date-founded-update'), '/');
if ($this->input->post('isPub-update'))
$fields['publisher'] = 1;
else
$fields['publisher'] = 0;
if ($this->input->post('isDev-update'))
$fields['developer'] = 1;
else
$fields['developer'] = 0;
$row_count = $this->pubdev->update($fields,$this->pubdev->get_id_name());
$file = $_FILES['image2'];
//$idPubDev = $this->input->post("pubDevName");
$ds = DIRECTORY_SEPARATOR;
$path = dirname('../') . $ds . 'application' . $ds . 'assets' . $ds . 'img' . $ds . 'pub_devs' . $ds . 'logos' . $ds;
//print_r($file);
$info = new SplFileInfo($file['name']);
//var_dump($info->getExtension());
$filename = "logo_id_" . str_pad( $this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . "." . $info->getExtension();
$result = $this->upload->uploadfile($file, $path, $filename);
//echo "test";
if ($result['status'] === "OK") {
$logo = 'logo_id_' . str_pad($this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . '.' . $info->getExtension();
$this->pubdev->update(array('logo' => $logo, $this->pubdev->get_id_name() => $this->input->post('pubDevId')), $this->pubdev->get_id_name());
$result['message'] = "file saved successfully";
$result['query'] = $this->db->last_query();
}
$result['update_rows']= $row_count;
echo json_encode($result);
}
I tried the .ajax version, but the problem persist, here is the modified jquery:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
var url = '/PubDev/updatePubDev';
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false
})
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error!");
}
})
.fail(function (data) {
alert("ajax error!");
})
.always(function () {
});
});
It is not a duplicate question because the answer provide contained different properties necessary to uplaod both image and data inputs. these two properties in the $.ajax call are needed:
processData: false,
contentType: false
This way, it solved my problem.
Use FormData as data instead of $(this).serialize();, set processData and contentType to false
var data = new FormData();
data.append("file", $(":file", this)[0].files[0]);
$.ajax({
url: "/PubDev/updatePubDev",
type: "POST",
data: data,
processData: false,
contentType: false
})
Please try to use file_get_contents('php://input'); to get the upload content.

insert image into database with ajax using formData

I'm having some difficulties with uploading an image from an html form. the form should be able to send the image name with other data to php page.
I used formData instead of serialized function, since it can't handle files data.
$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:"includes/widgets/insert.php",
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
success: function (data) {
alert(data);
},
});
return false;
});
html form
<form id="insert_post" action="includes/widgets/insert.php" method="post" enctype="multipart/form-data" >
<div class="row">
<div class="medium-6 columns">
<label>First name
<input type="text" name="first_name" id="first_name" contenteditable>
</label>
</div>
<div class="medium-6 columns">
<label>Last name
<input type="text" name="last_name" id="last_name" contenteditable>
</label>
</div>
<div class="medium-12 columns">
<label>Last name
<input type="file" name="file" id="image" multiple contenteditable>
</label>
</div>
</div>
<button type="button" name="btn_add" id="btn_add" class="button btn btn-xs btn-success" >Submit</button>
</form>
php page
<?php
$connect = mysqli_connect("localhost", "root", "", "myaddboard");
echo $_POST['first_name'];
echo $_POST['last_name'];
echo $image = $_FILES['file']['name'];
echo $image_tmp = $_FILES['file']['tmp_name'];
/*
if(empty($image)){
echo 'error';
}
move_uploaded_file($image_tmp,"img/$image");
//$sql = "INSERT INTO posts(post_content, post_author) VALUES('".$_POST["first_name"]."', '".$_POST["last_name"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
} else {
echo 'error';
}
*/
?>
The php form is just to test if the ajax send the data correctly.
When I click on the button I always get errors that the php variables is not defined
The errors i get each time I submit the form
undefined index: frist_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 4
undefined index: last_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 5
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 8
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 9
what should I do to make the ajax send the data to the php page ?
This won't work because of how your selector is created.
$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);
In the above scenario, $(this)[0] is getting you the raw HTML interpretation of the button.
What you actually want is to change your button to a submit type, capture the form submit event, and then process your request.
button type="submit" <-- change
$(document).on('submit', '#insert_post', function(e){
e.preventDefault(); //stop default form submission
//do the rest of your stuff here
});
Now $(this)[0] is actually the form and not the button.

Codeigniter ajax request fail on output

I'm trying to make an ajax request with jquery/codeigniter. Well, there seems to be a problem. i do get it to work, but it seems like the POST is not sent, for some reason...
Javascript
$('#profileUpdateButton').click(function() {
$.ajax({ // Starter Ajax Call
method: "POST",
url: baseurl + 'profile/statusUpdate',
data: $('#statusUpdateForm').serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
From the codeigniter controller
if($this->input->is_ajax_request()) {
echo $this->input->post('profileUpdate');
}
If i replace the "echo $this->" etc.. with just echo "Hello" i do get an alertbox with "Hello", why don't i get the text from the box?
html
<div id="statusUpdate">
<?php echo form_open(base_url() . 'profile/statusUpdate', array('name' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
Change your html markup to this...
<div id="statusUpdate"> <!-- Use ID not NAME here |v| -->
<?php echo form_open(base_url() . 'profile/statusUpdate', array('id' => 'statusUpdateForm')); ?>
<input type="text" value="Hva tenker du på?" name="profileUpdate" id="profileUpdate" onfocus="if(this.value == 'Hva tenker du på?')this.value=''" onblur="if(this.value == '')this.value='Hva tenker du på?'" />
<input type="submit" value="" name="profileUpdateButton" id="profileUpdateButton" />
<?php echo form_close(); ?>
</div>
you were setting the form's name and you were selecting $('#statusUpdateForm') which means the id of statusUpdateForm, not the name attribute...

Categories