Multiple file is not uploaded in codeigniter using dropzone js - javascript

I have used dropzone js to upload multiple image.
My code looks like below.
var s_currency = $('select[name="currency"]');
Dropzone.autoDiscover = false;
if($('#dropzoneDragArea').length > 0){
var expenseDropzone = new Dropzone("#expense-form", {
autoProcessQueue: false,
clickable: '#dropzoneDragArea',
acceptedFiles:allowed_files,
previewsContainer: '.dropzone-previews',
addRemoveLinks: true,
//maxFiles: 1,
//parallelUploads: 1,
uploadMultiple: true,
dictDefaultMessage:drop_files_here_to_upload,
dictFallbackMessage:browser_not_support_drag_and_drop,
dictRemoveFile:remove_file,
dictMaxFilesExceeded:you_can_not_upload_any_more_files,
error:function(file,response){
alert_float('danger',response);
},
success:function(file,response){
response = $.parseJSON(response);
this.options.autoProcessQueue = true;
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
window.location.assign(response.url);
}
},
});
}
$(document).ready(function(){
_validate_form($('form'),{category:'required',date:'required',amount:'required',currency:'required'},expenseSubmitHandler);
$('input[name="billable"]').on('change',function(){
do_billable_checkbox();
});
});
function expenseSubmitHandler(form){
s_currency.removeAttr('disabled');
$('input[name="billable"]').prop('disabled',false);
$.post(form.action, $(form).serialize()).success(function(response) {
response = $.parseJSON(response);
if (response.expenseid) {
if(typeof(expenseDropzone) !== 'undefined'){
//console.log(expenseDropzone.getQueuedFiles().length);return;
if (expenseDropzone.getQueuedFiles().length > 0) {
expenseDropzone.options.url = admin_url + 'expenses/add_expense_attachment/' + response.expenseid;
expenseDropzone.processQueue();
} else {
window.location.assign(response.url);
}
} else {
window.location.assign(response.url);
}
} else {
window.location.assign(response.url);
}
});
return false;
}
<form action="http://127.0.0.1/perfex_crm_aug_25/admin/expenses/expense" id="expense-form" class="dropzone dropzone-manual" enctype="multipart/form-data" method="post" accept-charset="utf-8" novalidate="novalidate">
<div id="dropzoneDragArea" class="dz-default dz-message">
<span>Attach file here</span>
</div>
<div class="dropzone-previews"></div>
<button type="submit" class="btn btn-info pull-right mtop15">Submit</button>
</form>
My controler looks like this :
public function expense($id = '')
{
if (!has_permission('expenses', '', 'view')) {
access_denied('expenses');
}
if ($this->input->post()) {
if ($id == '') {
if (!has_permission('expenses', '', 'create')) {
set_alert('danger', _l('access_denied'));
echo json_encode(array(
'url' => admin_url('expenses/expense')
));
die;
}
$id = $this->expenses_model->add($this->input->post());
if ($id) {
set_alert('success', _l('added_successfuly', _l('expense')));
echo json_encode(array(
'url' => admin_url('expenses/list_expenses/' . $id),
'expenseid' => $id
));
die;
}
echo json_encode(array(
'url' => admin_url('expenses/expense')
));
die;
} else {
if (!has_permission('expenses', '', 'edit')) {
set_alert('danger', _l('access_denied'));
echo json_encode(array(
'url' => admin_url('expenses/expense/' . $id)
));
die;
}
$success = $this->expenses_model->update($this->input->post(), $id);
if ($success) {
set_alert('success', _l('updated_successfuly', _l('expense')));
}
echo json_encode(array(
'url' => admin_url('expenses/list_expenses/' . $id),
'expenseid' => $id
));
die;
}
}
if ($id == '') {
$title = _l('add_new', _l('expense_lowercase'));
} else {
$data['expense'] = $this->expenses_model->get($id);
$title = _l('edit', _l('expense_lowercase'));
//echo "<pre>";
//print_r($data['expense']);
}
if($this->input->get('customer_id')){
$data['customer_id'] = $this->input->get('customer_id');
$data['do_not_auto_toggle'] = true;
}
$this->load->model('taxes_model');
$this->load->model('payment_modes_model');
$this->load->model('currencies_model');
$this->load->model('projects_model');
$data['customers'] = $this->clients_model->get();
$data['taxes'] = $this->taxes_model->get();
$data['categories'] = $this->expenses_model->get_category();
$data['supplier'] = $this->expenses_model->get_supplier();
//print_r($data['supplier']);
$data['payment_modes'] = $this->payment_modes_model->get();
$data['currencies'] = $this->currencies_model->get();
$data['title'] = $title;
$this->load->view('admin/expenses/expense', $data);
}
I have also created helper for uploading image. That function looks like below :
function handle_lead_attachments($leadid)
{
if(isset($_FILES['file']) && _perfex_upload_error($_FILES['file']['error'])){
header('HTTP/1.0 400 Bad error');
echo _perfex_upload_error($_FILES['file']['error']);
die;
}
$CI =& get_instance();
if (isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
do_action('before_upload_lead_attachment',$leadid);
$path = LEAD_ATTACHMENTS_FOLDER . $leadid . '/';
// Get the temp file path
$tmpFilePath = $_FILES['file']['tmp_name'];
// Make sure we have a filepath
if (!empty($tmpFilePath) && $tmpFilePath != '') {
// Setup our new file path
if (!file_exists($path)) {
mkdir($path);
fopen($path . 'index.html', 'w');
}
$filename = unique_filename($path, $_FILES["file"]["name"]);
$newFilePath = $path . $filename;
// Upload the file into the company uploads dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$CI =& get_instance();
$CI->db->insert('tblleadattachments', array(
'leadid' => $leadid,
'file_name' => $filename,
'filetype' => $_FILES["file"]["type"],
'addedfrom' => get_staff_user_id(),
'dateadded' => date('Y-m-d H:i:s')
));
$CI->load->model('leads_model');
$CI->leads_model->log_lead_activity($leadid, 'not_lead_activity_added_attachment');
return true;
}
}
}
return false;
}
Here, when I have upload one image than its working fine.But when I have tried to upload multiple image than it store other data image column has pass null value.
So what should I have to change in My code to upload multiple image. I have used perfex-crm project. I have to modify its expence module.

Related

How to return ajax with separate API URL response to controller in YII2?

I am trying to call a API URL using AJAX. I need to validate the response and update the DB, SO I need to return it to the controller.
Is there any way to do that. Here is my view, JS and controller code.
Here is my View Code where I have a separate URL for validation, which is the API URL
View
<?php $form = ActiveForm::begin([
'action' => ['users/renderstep3'],
'validationUrl' => 'API URL',
'options' => [
'class' => 'comment-form'
]
]); ?>
<?= $form->field($paymentmodel, 'customerId')->hiddenInput(['value'=> $userid])->label(false) ?>
<?= $form->field($paymentmodel, 'owner')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
JS
jQuery(document).ready(function($) {
$('body').on('submit', '.comment-form', function(event) {
event.preventDefault(); // stopping submitting
var data = $(this).serializeArray();
data.splice(0,1);
var result = {};
for ( i=0 ; i < data.length ; i++)
{
key = data[i].name.replace("UserPaymentDetails[", "").slice(0,-1);
result[key] = data[i].value;
}
var url = $(this).attr('validationUrl');
$.ajax({
url: url,
type: 'post',
dataType: 'json',
data: JSON.stringify(result)
})
.done(function(response) {
return response;
})
.fail(function() {
console.log("error");
});
});
});
Controller Action
public function actionRenderstep3()
{
$model = new Users();
$detailsmodel = new UserDetails();
$paymentmodel = new UserPaymentDetails();
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$data = Yii::$app->request->post();
print_r($data) ; exit;
}
if ($paymentmodel->load(Yii::$app->request->post()) && $paymentmodel->validate())
{
$paymentmodel->Status = 0;
$paymentmodel->save();
return $this->redirect(['index']);
}
return $this->render('renderstep3', [
'model' => $model,
'detailsmodel' => $detailsmodel,
'paymentmodel' => $paymentmodel,
]); }
Thanks in advance!!
In your controller, you have to change the action like this in order to validate using Ajax. I have edited my answer. Please note that you can delete your custom js code in order to use like this.
// ... The View file
<?php
$form = ActiveForm::begin([
'action' => ['users/renderstep3'],
'enableAjaxValidation' => true,
'validationUrl' => 'API URL',
'options' => [
'class' => 'comment-form'
]
]);
?>
<?= $form->field($paymentmodel, 'customerId')->hiddenInput(['value'=> $userid])->label(false) ?>
<?= $form->field($paymentmodel, 'owner')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
// ... Controller
public function actionRenderstep3()
{
$model = new Users();
$detailsmodel = new UserDetails();
$paymentmodel = new UserPaymentDetails();
if (Yii::$app->request->isAjax && $paymentmodel->load(Yii::$app->request->post())) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($paymentmodel->load(Yii::$app->request->post())) {
$paymentmodel->Status = 0;
$paymentmodel->save(false); // Validate false, because we did the validation before
return $this->redirect(['index']);
}
return $this->render('renderstep3', [
'model' => $model,
'detailsmodel' => $detailsmodel,
'paymentmodel' => $paymentmodel,
]);
}
You can find more information here
https://www.yiiframework.com/doc/guide/2.0/en/input-validation
<?php
$form = ActiveForm::begin([
'action' => ['users/renderstep3'],
'validationUrl' => 'API URL',//ajax validation hit to validationUrl if provide other wise validationUrl is action Url
'options' => [
'class' => 'comment-form'
]
]);
?>
and change some code in js
the below code calls befor form submit
$('body').on('beforeSubmit', '.comment-form', function(event)
In controller
In case of single model validation
if ($paymentmodel->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return yii\widgets\ActiveForm::validate($model);
}
$paymentmodel->Status = 0;
if ($paymentmodel->save(false)) {
return $this->redirect(['index']);
}
}
In case of multiple model validation
if ($model->load(Yii::$app->request->post())) {
$detailsmodel->load(Yii::$app->request->post());
$paymentmodel->load(Yii::$app->request->post());
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$return = yii\widgets\ActiveForm::validate($model);
$return = \yii\helpers\ArrayHelper::merge(yii\widgets\ActiveForm::validate($detailsmodel), $return);
$return = \yii\helpers\ArrayHelper::merge(yii\widgets\ActiveForm::validate($paymentmodel), $return);
return $return;
}
//here is data saving or logic
}

json and php Uncaught Error: Function name must be a string in in php 7.0

I tried to translate the site to php7.0 and I have a login system and registration when I press the buttons gives an error
<br />
Notice: Array to string conversion in /var/www/html/new/lib/class/class.ajax.php on line 252
Notice: Undefined property: ajax::$Array in /var/www/html/new/lib/class/class.ajax.php on line 252
Fatal error: Uncaught Error: Function name must be a string in /var/www/html/new/lib/class/class.ajax.php:252
Stack trace:
0 {main}
My code :
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
session_start(); // запуск сессии
date_default_timezone_set('Europe/Moscow'); //выбор временного региона Москва
require_once 'class.auth.php';
// принятие данных с ajax запросов
include_once('db.php');
require_once 'class.mix.php';
//$servers = new MixServers();
// если человек онлайн обновление информации
class ajax
{
public $ip;
protected $OOP_auth;
protected $OOP_mix;
public function __construct() {
$this->OOP_auth = new Authorization();
$this->OOP_mix = new MixServers();
if ( isset($_SESSION['auth']) )
{
$this->OOP_auth->online($_SESSION['auth']);
$this->OOP_mix->id_player = $_SESSION['auth'];
}
}
public function __destruct()
{
$this->OOP_auth = null;
$this->OOP_mix = null;
}
public function login($array)
{
//print_r($array);
// функция проверка отправленых данных
if ( isset($array['Username']) && isset($array['psw']) && $array['psw'] != '' && $array['Username'] != '' )
{
if ( isset($array['remembe']) && ($array['remembe'] == "true") )
{
SetCookie("remember",'1',time()+604800,'/');
SetCookie("login", $array['Username'],time()+604800,'/');
SetCookie("password",md5($array['psw']),time()+604800,'/');
}
else
{
SetCookie("remember",'0',time()+604800,'/');
}
$this->OOP_auth->login($array['Username'], $array['psw']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Ошибка при вводе");
return json_encode($answer);
}
else
{
return json_encode(array('status' => false, 'message' => 'Логин или пароль не введены'));
}
}
public function registration($array)
{
if ( isset($array['reg_login'])
and isset($array['reg_password'])
and isset($array['reg_password1'])
and $array['reg_password'] === $array['reg_password1']
and 3 < mb_strlen($array['reg_login'], 'utf-8')
and 3 < mb_strlen($array['reg_password'], 'utf-8')
and 3 < mb_strlen($array['reg_password1'], 'utf-8') )
{
$this->OOP_auth->pre_registration($this->ip, $array['reg_login'], $array['reg_password']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Вы уже зарегистрированны");
return json_encode($answer);
}
else
{
return json_encode(array('status' => false, 'message' => 'Логин или пароль не введены или введены неправильно'));
}
}
public function check_reg($array)
{
$this->OOP_auth->check_reg($this->ip) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Вы еще не зашли на сервер");
return json_encode($answer);
}
public function in_login($array)
{
$this->OOP_auth->loginIP($this->ip) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Ошибка при входе");
return json_encode($answer);
}
public function unlogin($array)
{
$this->OOP_auth->unlogin($_SESSION['auth']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Ошибка при выходе");
if ($answer['status'])
{
SetCookie("login", "", time() - 3600,'/');
SetCookie("password","", time() - 3600,'/');
}
return json_encode($answer);
}
public function change_country($array)
{
$DATA = $this->OOP_mix->free_servers("sity", $array['add_mix_country']);
$option = "";
if (isset($DATA['mix_sity']))
{
foreach ($DATA['mix_sity'] as $key => $value)
{
$option .= "<option value=\"" . $DATA['mix_sity'][$key]['name'] . "\">" . $DATA['mix_sity'][$key]['name'] . "</option>";
}
}
return $option;
}
public function create_mix($array)
{
if ( isset($array['name']) && isset($array['country']) && isset($array['sity']) && isset($array['map']) && 3 < mb_strlen($array['name'], 'utf-8') && 40 > mb_strlen($array['name'], 'utf-8'))
{
$this->OOP_mix->create_mix_server($_POST['name'], $_POST['country'], $_POST['sity'], $_POST['map']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Ошибка при создании микса");
}
else
{
$answer = array("status" => false, "message" => "Ошибка при вводе данных");
}
return json_encode($answer);
}
public function ajax_mixs_free()
{
if (isset($_SESSION['auth']))
{
$answer['message'] = $this->OOP_mix->get_info_all_servers();
}
return $answer['message']['free_servers'];
}
public function join_team($array)
{
if ( isset($_SESSION['auth']) && (int) $array['team'] > 0 && (int) $array['team'] < 3)
{
if ($this->OOP_mix->check_player())
{
$this->OOP_mix->join_team((int) $array['team']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Все слоты заняты");
}
else
{
$answer = array("status" => false, "message" => "Вы не на миксе");
}
}
else
{
$answer = array("status" => false, "message" => "Ошибка при выборе команды");
}
return json_encode($answer);
}
public function message_mix($array)
{
if (isset($_SESSION['auth']))
{
$this->OOP_mix->messeges_send($array['text']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Проблемы с текстом");
}
else
{
$answer = array("status" => false, "message" => "Авторизируйтес на сайте");
}
return json_encode($answer);
}
public function update_chat($array)
{
if (isset($_SESSION['auth']) && isset($array['id']))
{
if ($answer = $this->OOP_mix->messeges_get($array['id'])) $answer['status'] = true;
}
else
{
$answer = array("status" => false, "message" => "Авторизируйтес на сайте");
}
return json_encode($answer);
}
public function exit_mix()
{
if (isset($_SESSION['auth']))
{
$this->OOP_mix->exit_on_server() ? $answer['status'] = true : $answer = array("status" => false, "message" => "Этого не может быть");
}
return json_encode($answer);
}
public function select_mix($array)
{
if (isset($_SESSION['auth']))
{
$this->OOP_mix->set_on_mix($array['val']) ? $answer['status'] = true : $answer = array("status" => false, "message" => "Не правильный id");
}
else
{
$answer = array("status" => false, "message" => "Авторизация закончилась");
}
return json_encode($answer);
}
public function back_to_mixs()
{
if (isset($_SESSION['auth']))
{
if ($this->OOP_mix->check_player())
{
$this->OOP_mix->back_to_mixs() ? $answer['status'] = true : $answer = array("status" => false, "message" => "Вы не можете выйти так как являетесь игроком сервера");
}
else
{
$answer = array("status" => true, "message" => "Все ваши игры завершены");
}
}
else
{
$answer = array("status" => false, "message" => "Авторизация закончилась");
}
return json_encode($answer);
}
}
if ( isset($_POST['url']) && $_POST['url'] != '' )
{
$OOPajax = new ajax();
if(isset($_SERVER['HTTP_CF_CONNECTING_IP']))
{
$OOPajax->ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
}
else
{
$OOPajax->ip = $_SERVER['REMOTE_ADDR'];
}
if ( method_exists($OOPajax, $_POST['url']) )
{
$answer = $OOPajax->$_POST['url']($_POST);
}
else
{
$answer = json_encode(array("status" => false, "message" => "Не наебешь"));
}
}
else
{
$answer = json_encode(array("status" => false, "message" => "Пошел на хуй"));
}
echo $answer;
/*
// Выход с сайта - обнуление кукки
if ( isset($_POST['set']) && ($_POST['set'] == 'unlogin') )
{
SetCookie("login", "", time() - 3600,'/');
SetCookie("password","", time() - 3600,'/');
}
// Авторизация
if (isset($_POST['set']) && ($_POST['set'] == 'login') && isset($_POST['Username']) && isset($_POST['psw']))
{
// авторизация
if ( isset($_POST['remembe']) && ($_POST['remembe'] == "true") )
{
SetCookie("remember",'1',time()+604800,'/');
SetCookie("login", $_POST['Username'],time()+604800,'/');
SetCookie("password",md5($_POST['psw']),time()+604800,'/');
}
else
{
SetCookie("remember",'0',time()+604800,'/');
}
if ($authorization->login($_POST['Username'], $_POST['psw'])) echo 'true';
}
// Регистрация
if ( isset($_POST['reg_login']) && isset($_POST['reg_password']) && isset($_POST['reg_password1']) && ( $_POST['reg_password'] === $_POST['reg_password1'] ) )
{
if ( $authorization->pre_registration($ip, $_POST['reg_login'], $_POST['reg_password']) ) echo 'true';
}
// Выход с сайта
if ( isset($_POST['set']) && ($_POST['set'] == 'unlogin') )
{
if ( $authorization->unlogin($_SESSION['auth']) ) echo 'true';
}
// обновление микса
if ( isset($_POST['set']) && ($_POST['set'] == 'info_mix') )
{
echo $servers->info_mix_server();
}
// обновление списка миксов
if ( isset($_POST['set']) && ($_POST['set'] == 'info_mixs') )
{
echo $servers->info_mix_servers();
}
// Получение списка городов в стране
if ( isset($_POST['add_mix_country']) && ($_POST['add_mix_country'] != '') )
{
$DATA = $servers->free_servers("sity", $_POST['add_mix_country']);
foreach ($DATA['mix_sity'] as $key => $value)
{
echo "<option value=\"" . $DATA['mix_sity'][$key]['name'] . "\">" . $DATA['mix_sity'][$key]['name'] . "</option>";
}
}
// Создание микса
if ( isset($_POST['set']) && ($_POST['set'] == 'create_mix') && isset($_POST['name']) && isset($_POST['country']) && isset($_POST['sity']) && isset($_POST['map']) && isset($_POST['password']))
{
if ($servers->create_mix_server($_POST['name'], $_POST['country'], $_POST['sity'], $_POST['map'], $_POST['password'])) echo "true";
}
// Вход на микс
if ( isset($_POST['set']) && ($_POST['set'] == 'select_mix') && isset($_POST['val']) && isset($_POST['pass']))
{
if($servers->set_on_mix($_POST['val'], $_POST['pass'])) echo "true";
}
// Вход на сервер
if ( isset($_POST['set']) && ($_POST['set'] == 'select_server') && isset($_POST['val']))
{
if($servers->set_on_server($_POST['val'])) echo "true";
}
// Выход с микса
if ( isset($_POST['set']) && ($_POST['set'] == 'exit_mix') )
{
if ($servers->exit_on_server()) echo "true";
}
*/
?>
PHP 7 introduced some backward incompatible changes, including the evaluation of indirect expressions. You need to change the line:
$answer = $OOPajax->$_POST['url']($_POST);
to this:
$answer = $OOPajax->{$_POST['url']}($_POST);
to get the old PHP 5 behaviour.
The manual lists other expressions that were affected by this change here: http://php.net/manual/en/migration70.incompatible.php (see the "Changes to variable handling" section).

Form/PHP script clears the form after submission as desired in Edge, Submits but not clearing form in Chrome and Firefox

Why does this PHP/Form submit and clear in Edge, but a form submit in Chrome and Firefox is not clearing the form after submit.
End result will be Edge submits the form, pops up a success message then clears the data from the form. Both in Chrome and Firefox, it submits the data but the success message and the form does not clear, allowing multiple submissions of the same form.
Here is the Form:
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/haydon.css" type="text/css" media="screen">
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/script.js"></script>
<script src="js/forms.js" type="text/javascript"></script>
</head>
<form id="contact-form" method="post" action="../bin/Mailhandler.php">
<div class="success">Contact form submitted!
<br><strong>We will be in touch soon.</strong>
</div>
<fieldset>
<label class="name">
<input type="text" value="Name:"><span class="error">*This is not a valid name.</span><span class="empty">*This field is required.</span>
</label>
<label class="email">
<input type="text" value="E-mail:"><span class="error">*This is not a valid email address.</span><span class="empty">*This field is required.</span>
</label>
<label class="phone">
<input type="tel" value="Phone:"><span class="error">*This is not a valid phone number.</span><span class="empty">*This field is required.</span>
</label>
<label class="message">
<textarea>Message:</textarea><span class="error">*The message is too short.</span><span class="empty">*This field is required.</span>
</label>
<div class="buttons-wrapper"><a class="button" data-type="reset">Clear</a><a class="button" data-type="submit">Submit</a>
</div>
</fieldset>
</form>
PHP script:
<?php
//SMTP server settings
$host = "smtp.blanked.com";
$port = "587";
$username = "smtpform#blanked.com";
$password = "Blanked";
$messageBody = "";
if($_POST['name']!='false'){
$messageBody .= '<p>Visitor: ' . $_POST["name"] . '</p>' . "\n";
$messageBody .= '<br>' . "\n";
}
if($_POST['email']!='false'){
$messageBody .= '<p>Email Address: ' . $_POST['email'] . '</p>' . "\n";
$messageBody .= '<br>' . "\n";
}else{
$headers = '';
}
if($_POST['state']!='false'){
$messageBody .= '<p>State: ' . $_POST['state'] . '</p>' . "\n";
$messageBody .= '<br>' . "\n";
}
if($_POST['phone']!='false'){
$messageBody .= '<p>Phone Number: ' . $_POST['phone'] . '</p>' . "\n";
$messageBody .= '<br>' . "\n";
}
if($_POST['fax']!='false'){
$messageBody .= '<p>Fax Number: ' . $_POST['fax'] . '</p>' . "\n";
$messageBody .= '<br>' . "\n";
}
if($_POST['message']!='false'){
$messageBody .= '<p>Message: ' . $_POST['message'] . '</p>' . "\n";
}
if($_POST["stripHTML"] == 'true'){
$messageBody = strip_tags($messageBody);
}
if($host=="" or $username=="" or $password==""){
$owner_email = $_POST["owner_email"];
$headers = 'From:' . $_POST["owner_email"] . "\r\n" . 'Content-Type: text/plain; charset=UTF-8' . "\r\n";
$subject = 'A message from your site visitor ' . $_POST["name"];
try{
if(!mail($owner_email, $subject, $messageBody, $headers)){
throw new Exception('mail failed');
}else{
echo 'mail sent';
}
}catch(Exception $e){
echo $e->getMessage() ."\n";
}
}else{
require_once 'Mail.php';
$to = $_POST["owner_email"];
$subject = 'A message from your site visitor ' . $_POST["name"];
$headers = array (
'From' => 'From:' . $_POST["owner_email"] . "\r\n" . 'Content-Type: text/plain; charset=UTF-8' . "\r\n",
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory(
'smtp',
array (
'host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $messageBody);
try{
if(PEAR::isError($mail)){
echo $mail->getMessage();
}else{
echo 'mail sent';
}
}catch(Exception $mail){
echo $mail->getMessage() ."\n";
}
}
?>
Here is the forms.js
(function ($) {
$.fn.forms = function (o) {
return this.each(function () {
var th = $(this),
_ = th.data('forms') || {
errorCl: 'error',
emptyCl: 'empty',
invalidCl: 'invalid',
notRequiredCl: 'notRequired',
successCl: 'success',
successShow: '4000',
mailHandlerURL: 'http://www.blankeddomain.co.uk/bin/Mailhandler.php',
ownerEmail: '',
stripHTML: true,
smtpMailServer: 'localhost',
targets: 'input,textarea',
controls: 'a[data-type=reset],a[data-type=submit]',
validate: true,
rx: {
".name": {
rx: /^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,
target: 'input'
},
".state": {
rx: /^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,
target: 'input'
},
".email": {
rx: /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,
target: 'input'
},
".phone": {
rx: /^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,
target: 'input'
},
".fax": {
rx: /^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,
target: 'input'
},
".message": {
rx: /.{20}/,
target: 'textarea'
}
},
preFu: function () {
_.labels.each(function () {
var label = $(this),
inp = $(_.targets, this),
defVal = inp.val(),
trueVal = (function () {
var tmp = inp.is('input') ? (tmp = label.html().match(/value=['"](.+?)['"].+/), !! tmp && !! tmp[1] && tmp[1]) : inp.html()
return defVal == '' ? defVal : tmp
})()
trueVal != defVal && inp.val(defVal = trueVal || defVal)
label.data({
defVal: defVal
})
inp
.bind('focus', function () {
inp.val() == defVal && (inp.val(''), _.hideEmptyFu(label), label.removeClass(_.invalidCl))
})
.bind('blur', function () {
_.validateFu(label)
if (_.isEmpty(label))
inp.val(defVal), _.hideErrorFu(label.removeClass(_.invalidCl))
})
.bind('keyup', function () {
label.hasClass(_.invalidCl) && _.validateFu(label)
})
label.find('.' + _.errorCl + ',.' + _.emptyCl).css({
display: 'block'
}).hide()
})
_.success = $('.' + _.successCl, _.form).hide()
},
isRequired: function (el) {
return !el.hasClass(_.notRequiredCl)
},
isValid: function (el) {
var ret = true
$.each(_.rx, function (k, d) {
if (el.is(k))
ret = d.rx.test(el.find(d.target).val())
})
return ret
},
isEmpty: function (el) {
var tmp
return (tmp = el.find(_.targets).val()) == '' || tmp == el.data('defVal')
},
validateFu: function (el) {
el.each(function () {
var th = $(this),
req = _.isRequired(th),
empty = _.isEmpty(th),
valid = _.isValid(th)
if (empty && req)
_.showEmptyFu(th.addClass(_.invalidCl))
else
_.hideEmptyFu(th.removeClass(_.invalidCl))
if (!empty)
if (valid)
_.hideErrorFu(th.removeClass(_.invalidCl))
else
_.showErrorFu(th.addClass(_.invalidCl))
})
},
getValFromLabel: function (label) {
var val = $('input,textarea', label).val(),
defVal = label.data('defVal')
return label.length ? val == defVal ? 'nope' : val : 'nope'
},
submitFu: function () {
_.validateFu(_.labels)
if (!_.form.has('.' + _.invalidCl).length)
$.ajax({
type: "POST",
url: _.mailHandlerURL,
data: {
name: _.getValFromLabel($('.name', _.form)),
email: _.getValFromLabel($('.email', _.form)),
phone: _.getValFromLabel($('.phone', _.form)),
fax: _.getValFromLabel($('.fax', _.form)),
state: _.getValFromLabel($('.state', _.form)),
message: _.getValFromLabel($('.message', _.form)),
owner_email: _.ownerEmail,
stripHTML: _.stripHTML
},
success: function () {
_.showFu()
}
})
},
showFu: function () {
_.success.slideDown(function () {
setTimeout(function () {
_.success.slideUp()
_.form.trigger('reset')
}, _.successShow)
})
},
controlsFu: function () {
$(_.controls, _.form).each(function () {
var th = $(this)
th
.bind('click', function () {
_.form.trigger(th.data('type'))
return false
})
})
},
showErrorFu: function (label) {
label.find('.' + _.errorCl).slideDown()
},
hideErrorFu: function (label) {
label.find('.' + _.errorCl).slideUp()
},
showEmptyFu: function (label) {
label.find('.' + _.emptyCl).slideDown()
_.hideErrorFu(label)
},
hideEmptyFu: function (label) {
label.find('.' + _.emptyCl).slideUp()
},
init: function () {
_.form = _.me
_.labels = $('label', _.form)
_.preFu()
_.controlsFu()
_.form
.bind('submit', function () {
if (_.validate)
_.submitFu()
else
_.form[0].submit()
return false
})
.bind('reset', function () {
_.labels.removeClass(_.invalidCl)
_.labels.each(function () {
var th = $(this)
_.hideErrorFu(th)
_.hideEmptyFu(th)
})
})
_.form.trigger('reset')
}
}
_.me || _.init(_.me = th.data({
forms: _
}))
typeof o == 'object' && $.extend(_, o)
})
}
})(jQuery)
$(window).load(function () {
$('#contact-form').forms({
ownerEmail: 'blanked#domain.co.uk'
})
})
Any direction or advice from other eyes would be appreciated at this point.

Send and image from PHP to Javascript (JSON)

I'm trying to make a "meal" in my DB, so in my website i made a form with a name, and a picture. This is the code of the form :
<?php
$new_meal_title = htmlentities($_POST["new_meal_title"]);
$new_meal_img = htmlentities($_POST["new_meal_img"]);
$data = array(
'new_meal_title' => $new_meal_title,
'new_meal_img' => base64_encode($new_meal_img)
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents(constant("API_URL")."/meal", false, $context);
if($result === FALSE){
var_dump($result);
}
$json = json_decode($result);
if($json->success == "true"){
header('Location: ../../');
return;
}
else{
echo $json->message;
}
header('Location: ../../');
?>
The form is sending data to my Node API. My Question is, how to save into a folder the image path through form in Javascript after it has been received in JSON.
Thanks for your help, i just had to change this line :
$new_meal_img = htmlentities($_POST["new_meal_img"]);
By
$new_meal_img = $_FILES['new_meal_img']["tmp_name"];
And
'new_meal_img' => base64_encode($new_meal_img)
By
'new_meal_img' => base64_encode(file_get_contents($new_meal_img))

Formating results of a directory using jstree

I'm trying to transform a directory url in a tree using jstree. Based on this post: Need help formatting results of a directory listing in PHP, javascript tree control by #hek2mgl, I got something like in the screenshot:. My problem is that it isn't showing the name of my directories, it just shows me the name of the files that I have inside the directory but not the name of the directory.
My php function is quite the same that #hek2mgl's post:
file: dir2json.php
header("Content-Type: application/json");
echo json_encode(dir_to_jstree_array("/var/www/html/images"));
function dir_to_jstree_array($dir, $order = "a", $ext = array()) {
if(empty($ext)) {
$ext = array (
"jpg", "gif", "jpeg", "png", "doc", "xls", "pdf", "tif", "ico", "xcf", "gif87", "scr"
);
}
$listDir = array(
'data' => basename($dir),
'attr' => array (
'rel' => 'folder'
),
'metadata' => array (
'id' => $dir
),
'children' => array()
);
$files = array();
$dirs = array();
if($handler = opendir($dir)) {
while (($sub = readdir($handler)) !== FALSE) {
if ($sub != "." && $sub != "..") {
if(is_file($dir."/".$sub)) {
$extension = pathinfo($dir."/".$sub, PATHINFO_EXTENSION);
if(in_array($extension, $ext)) {
$files []= $sub;
}
}
elseif (is_dir($dir."/".$sub)) {
$dirs []= $dir."/".$sub;
}
}
}
if($order === "a") {
asort($dirs);
}
else {
arsort($dirs);
}
foreach($dirs as $d) {
$listDir['children'][]= dir_to_jstree_array($d);
}
if($order === "a") {
asort($files);
}
else {
arsort($files);
}
foreach($files as $file) {
$listDir['children'][]= $file;
}
closedir($handler);
}
return $listDir;
}
The json returned from this dir2json.php is:
{"data":"images","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images"},"children":[{"data":".xvpics","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/.xvpics"},"children":["fundo2.jpg","mha1.gif","mha2.gif","the777.gif"]},{"data":"tree_20x20","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/tree_20x20"},"children":["tree_h.png","tree_h.xcf","tree_l.png","tree_l.xcf","tree_t+-.xcf","tree_t+.png","tree_t+.xcf","tree_t-.png","tree_t-.xcf","tree_t.png","tree_t.xcf","tree_v.png","tree_v.xcf"]},{"data":"tree_25x25","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/tree_25x25"},"children":["tree_h.png","tree_h.xcf","tree_l.png","tree_l.xcf","tree_t+-.xcf","tree_t+.png","tree_t+.xcf","tree_t-.png","tree_t-.xcf","tree_t.png","tree_t.xcf","tree_v.png","tree_v.xcf"]},{"data":"tree_30x30","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/tree_30x30"},"children":[{"data":".xvpics","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/tree_30x30\/.xvpics"},"children":["tree_h.png","tree_h.xcf","tree_l.png","tree_l.xcf","tree_t+-.xcf","tree_t+.png","tree_t+.xcf","tree_t-.png","tree_t-.xcf","tree_t.png","tree_t.xcf","tree_v.png","tree_v.xcf"]},{"data":"tst","attr":{"rel":"folder"},"metadata":{"id":"\/var\/www\/html\/images\/tree_30x30\/tst"},"children":["conv.scr","tree_h.gif","tree_h.gif87","tree_h.png","tree_h.xcf","tree_l.gif","tree_l.png","tree_l.xcf","tree_t+-.gif","tree_t+-.xcf","tree_t+.gif","tree_t+.png","tree_t+.xcf","tree_t-.gif","tree_t-.png","tree_t-.xcf","tree_t.gif","tree_t.png","tree_t.xcf","tree_v.gif","tree_v.png","tree_v.xcf"]},"tree_h.png","tree_h.xcf","tree_l.png","tree_l.xcf","tree_t+-.xcf","tree_t+.png","tree_t+.xcf","tree_t-.png","tree_t-.xcf","tree_t.png","tree_t.xcf","tree_v.png","tree_v.xcf"]},"asc.gif","back.gif","bg.gif","cygnus.ico","desc.gif","eud_owner.png","favicon.ico","fundo2.jpg","mha.ico","mha1.gif","mha1_14_06_2007.gif","mha1_t3.gif","mha1_t4.gif","mha2.gif","mha2.png","mha2_MURILO.gif","mha2_ORIGINAL.gif","show-calendar.gif","the777.gif","tree_h.gif","tree_h.png","tree_h.xcf","tree_l.gif","tree_l.png","tree_l.xcf","tree_t+-.gif","tree_t+-.xcf","tree_t+.gif","tree_t+.png","tree_t+.xcf","tree_t-.gif","tree_t-.png","tree_t-.xcf","tree_t.gif","tree_t.png","tree_t.xcf","tree_v.gif","tree_v.png","tree_v.xcf"]}
And my php function that load javascript is:
function load_js() {
echo ' <link rel="stylesheet" type="text/css" href="/css/jstree/dist/themes/default/style.min.css" />
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/jstree/dist/jstree.min.js"></script>
<script type="text/javascript">
function on_load_padrao() {
$(\'#jstree_demo_div\').jstree({
\'core\' : {
\'data\' : {
\'type\' : "POST",
\'url\' : \'mypath/dir2json.php\',
\'data\' : function (node) {
return { \'id\' : node["id"]};
}
},
\'dataType\' : \'json\'
},
\'plugins\' : ["checkbox" ]
});
}
</script> ';
}
I'd like to have this result:
What am I missing?
I found what I was doing wrong, the sctructure of array (that I was building JSON) was wrong.
I was doing this:
$listDir = array(
'data' => basename($dir),
'attr' => array (
'rel' => 'folder'
),
'metadata' => array (
'id' => $dir
),
'children' => array()
);
But the correct structure (in version 3.0 of jstree) is:
$listDir = array(
'id' => basename($dir),
'text' => basename($dir),
'children' => array()
);
So, my php file (dir2json.php) looks like this:
header("Content-Type: application/json");
echo json_encode(dir_to_jstree_array("/var/www/html/images"));
function dir_to_jstree_array($dir, $order = "a", $ext = array()) {
if(empty($ext)) {
$ext = array (
"jpg", "gif", "jpeg", "png", "doc", "xls", "pdf", "tif", "ico", "xcf", "gif87", "scr"
);
}
$listDir = array(
'id' => basename($dir),
'text' => basename($dir),
'children' => array()
);
$files = array();
$dirs = array();
if($handler = opendir($dir)) {
while (($sub = readdir($handler)) !== FALSE) {
if ($sub != "." && $sub != "..") {
if(is_file($dir."/".$sub)) {
$extension = pathinfo($dir."/".$sub, PATHINFO_EXTENSION);
if(in_array($extension, $ext)) {
$files []= $sub;
}
}
elseif (is_dir($dir."/".$sub)) {
$dirs []= $dir."/".$sub;
}
}
}
if($order === "a") {
asort($dirs);
}
else {
arsort($dirs);
}
foreach($dirs as $d) {
$listDir['children'][]= dir_to_jstree_array($d);
}
if($order === "a") {
asort($files);
}
else {
arsort($files);
}
foreach($files as $file) {
$listDir['children'][]= $file;
}
closedir($handler);
}
return $listDir;
}
for add icon to your file
you can use this code :
last code :
foreach($files as $file) {
$listDir['children'][]= $file;
}
new code :
foreach($files as $file) {
$exten = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($exten, $ext)) {
$icon = '';
if($exten == 'jpg' or $exten == 'png' or $exten == 'jpeg' or $exten == 'gif' or $exten == 'ico'){
$icon = 'fa fa fa-file-image-o';
}// end if
if($exten == 'doc' or $exten == 'docx'){
$icon = 'fa fa-file-word-o';
}
if ($exten == 'txt'){
$icon = 'fa fa-file-text-o';
}
if ($exten == 'pdf'){
$icon = 'fa fa-file-pdf-o';
}
if ($exten == 'xls'){
$icon = 'fa fa-file-excel-o';
}
if ($exten == 'zip'){
$icon = 'fa fa-file-archive-o';
}
}
$listDir['children'][]= array('id' => $dir.'/'.$file , 'text' => $file , 'icon' => $icon);
}

Categories

Resources