Unable to get uploaded file name using angularjs with php - php

I am trying to upload multiple files with different title but unable to get uploaded file names.
Here is my html code.
<div class="nav-md" ng-app="fileuploadModule">
<div class="container body" ng-controller="fileuploadController as parentCtrl">
<div class="form-group">
<div class="col-sm-6" style="padding:0px 10px 0px 0px;">
<label class="control-label">ID-NO</label>
<input type="text" class="form-control" id="idno" ng-model="idno" />
</div>
<div class="col-sm-6" style="padding:0px 10px 0px 0px;">
<label class="control-label" >Name</label>
<input type="text" class="form-control" id="pname" ng-model="pname" />
</div>
</div>
<div class="form-group" ng-controller="ChildController as childCtrl">
<div class="col-md-12" style="padding:0px 10px 0px 0px;">
<table ng-table="tableParams" class="display table table-striped table-bordered">
<thead>
<tr>
<th width="5%">Sr.No</th>
<th width="35%">Title</th>
<th width="35%">Upload Report</th>
<th width="25%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cap in data">
<td>{{$index+1}}</td>
<td>
<input class="form-control" id="tags" type="text" ng-model="cap.name" placeholder="Title" typeahead="drug.name for drug in drugArray | filter:$viewValue | limitTo:4">
</td>
<td>
<input type="file" id="i_file" name="file" ng-model="cap.file" ng-file-select="onFileSelect($files)" />
<input type="hidden" ng-model="cap.message" value={{message}} />
</td>
<td>
<input type="submit" ng-click="addFormField()" class="btn btn-default" value="Add Items" />
<input type="submit" value="Remove" class="btn btn-primary" ng-click="removeRow(cap.name)" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
Here is the angularjs Script.
//reports upload
var infu = angular.module('fileuploadModule',['angularFileUpload','angularUtils.directives.dirPagination','ui.bootstrap'])
infu.controller('fileuploadController', function ($scope, $http)
{
/*Add & Remove Script Starts Here*/
//to remove the row
$scope.removeRow = function(name) {
var index = -1;
var comArr = eval( $scope.data );
for( var i = 0; i < comArr.length; i++ ) {
if( comArr[i].name ==name ) {
index = i;
break;
}
}
if( index === -1 ) {
}
$scope.data.splice( index, 1 );
};
//dynamic row creation
$scope.data = [{}];
//Autocomplete for title
$scope.drugArray = [];
$http({method: 'GET',url: 'get_test_name.php',data: { applicationId: 3 }}).success(function (data) {
$scope.drugArray = data;
});
$scope.addFormField = function() {
$scope.data.push({});
}
/*Add & Remove Script Ends Here*/
//Updated Investigation
$scope.submitData = function()
{
var comArr = eval( $scope.data );
var name=new Array();
var file=new Array();
var message=new Array();
for( var i = 0; i < comArr.length; i++ )
{
name.push(comArr[i].name);
file.push(comArr[i].file);
message.push(comArr[i].message);
}
var answer = confirm("Do you want to Submit?")
if (!answer)
{
}
else
{
$http.post('update_details.php', {
'idno': $scope.idno,
'pname': $scope.pname,
'name': name,
'file': file,
'message': message,
/*'filename': $scope.parentCtrl.childCtrl.message //If i give like getting only last upload file name*/
})
.success(function (data, status, headers, config)
{
alert("Data has been Added Successfully");
window.location.href="list_investigation_reports.php";
})
.error(function(data, status, headers, config)
{
});
}
}
});
//ChildController For file Upload
infu.controller('ChildController',function ($scope, $http, $upload) {
$scope.parentCtrl.childCtrl = $scope.childCtrl;
$scope.onFileSelect = function($files) {
$scope.message = "";
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
console.log(file);
$scope.upload = $upload.upload({
url: 'upload.php',
method: 'POST',
file: file
}).success(function(data, status, headers, config) {
$scope.message = data;
$scope.message=$scope.message.replace('\"', '');
$scope.childCtrl.message=$scope.message.replace('\"', '');
}).error(function(data, status) {
$scope.message = data;
});
}
};
});
Here is php code for file upload
<?php
$target_dir = "uploadfiles/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
$result = array("filename" => $_FILES["file"]);
$filename = $result['filename']['name'];
echo json_encode($filename);
?>
Here is the final code to insert details into database.
$data = json_decode(file_get_contents("php://input"));
$idno = $data->idno;
$pname = $data->pname;
$tname = $data->name;
$filename = $data->file;
$message = $data->message;
$date=date('Y-m-d');
foreach($tname as $index => $value)
{
$name1 = $tname[$index];
$filename1 = $filename[$index];
$message1 = $message[$index];
$qry_ress = $dbConnection->prepare("INSERT INTO tablename(idno,pname,testname,filename,cts) VALUES (?,?,?,?,?)");
$qry_ress->execute(array($idno,$pname,$name1,$filename1,$cts));
$arr = array("idno" => "$idno","pname" => "$pname","TestName" => "$name1","FileName" => "$filename1");
$jsn = json_encode($arr);
echo $jsn;
}
Getting Result as below
{"idno":"20","pname":"Vijay","TestName":"OCT","FileName":"","Message":""}{"idno":"25","pname":"Salim","TestName":"FFA","FileName":"","Message":""}
Getting above result data except uploaded file. Please help me to solve this issue.
Thanks in advance.

Related

Not getting the filename of a drag and drop image in PHP

I'm trying to create a form that has a drag and drop image with it. I did a tutorial for the drag and drop and now I'm trying to
put it together with a form.
The problem I'm having is that I'm not able to get the filename, so that I can insert it into the database.
I've tried doing this
if(isset($_POST['add_product']))
{
$filename = $_FILES['files']['name'];
echo print_r($filename);
die();
}
but I get a blank array
Array ( [0] => ) 1
and when I do this
if(isset($_FILES['files']))
{
$filename = $_FILES['files']['name'];
echo print_r($filename);
die();
}
I get the name of my image, but if I do this
if(isset($_FILES['files']))
{
$filename = $_FILES['files']['name'];
}
if(isset($_POST['add_product']))
{
echo print_r($filename);
die();
}
I get a blank array as well
Array ( [0] => ) 1
Here I was hoping that I could grab the $filename and pass it on to the if(isset($_POST['add_product]))
Here is my form
<form action="" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="content">content</label>
<textarea name="content" id="content" class="form-control" cols="30" rows="10"></textarea>
</div>
<input type="file" name="files[]" id="standard-upload-files" multiple>
<input type="submit" value="Upload files" id="standard-upload">
<div class="wrapper">
<div class="upload-console">
<h2 class="upload-console-header">
Upload
</h2>
<div class="upload-console-body">
<div class="upload-console-drop" id="drop-zone">
just drag and drop files here
</div>
<div class="bar">
<div class="bar-fill" id="bar-fill">
<div class="bar-fill-text" id="bar-fill-text"></div>
</div>
</div>
<div class="hidden" id="uploads-finished">
<h3>Process files</h3>
<div class="upload-console-upload">
filename.jpg
<span>Success</span>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-dark btn-lg btn-block" name="add_product">Save</button>
</div>
</form>
Here is the js files that I got from the tutorial that I did.
main.js
(function(){
"use strict";
var dropZone = document.getElementById('drop-zone');
var barFill = document.getElementById('bar-fill');
var barFillText = document.getElementById('bar-fill-text');
var uploadsFinished = document.getElementById('uploads-finished');
var startUpload = function(files){
// console.log(files);
app.uploader({
files: files,
progressBar: barFill,
progressText: barFillText,
processor: 'index.php',
finished: function(data){
// console.log(data);
var x;
var uploadedElement;
var uploadedAnchor;
var uploadedStatus;
var currFile;
for(x = 0; x < data.length; x = x + 1)
{
currFile = data[x];
uploadedElement = document.createElement('div');
uploadedElement.className = 'upload-console-upload';
uploadedAnchor = document.createElement('a');
uploadedAnchor.textContent = currFile.name;
if(currFile.uploaded)
{
uploadedAnchor.href = 'uploads/'+currFile.file;
}
uploadedStatus = document.createElement('span');
uploadedStatus.textContent = currFile.uploaded ? 'Uploaded' : 'Failed';
uploadedElement.appendChild(uploadedAnchor);
uploadedElement.appendChild(uploadedStatus);
uploadsFinished.appendChild(uploadedElement);
}
uploadsFinished.className = '';
},
error: function(){
console.log('there was an error');
}
});
};
//drop functionality
dropZone.ondrop = function(e){
e.preventDefault();
this.className = 'upload-console-drop';
startUpload(e.dataTransfer.files);
};
dropZone.ondragover = function(){
this.className = 'upload-console-drop drop';
return false;
};
dropZone.ondragleave = function(){
this.className = 'upload-console-drop';
return false;
};
}());
upload.js
var app = app || {};
(function(o){
"use strict";
//private methods
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest();
var uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState === 4)
{
if(this.status === 200)
{
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function')
{
o.options.finished(uploaded);
}
}else{
if(typeof o.options.error === 'function')
{
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(e){
var percent;
if(e.lengthComputable === true)
{
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData();
var i;
for(i = 0; i < source.length; i = i + 1)
{
data.append('files[]', source[i]);
}
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined)
{
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined)
{
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options){
o.options = options;
if(options.files !== undefined)
{
ajax(getFormData(o.options.files));
// getFormData(o.options.files);
}
}
}(app));

How can I have an admin controller in Magento and use it in phhtml for uploading file

I'm beginner in PHP and Magento,
I have Plugin which has a admin menu which refers to a page.
What I want to do is adding an admin controller for uploading a file to server from the page.
this is my structure:
MyPlugin/KnownUser/Controller/Adminhtml/Admin/Index.php
<?php
namespace MyPlugin\KnownUser\Controller\Adminhtml\Admin;
require_once( __DIR__ .'../../../../IntegrationInfoProvider.php');
use \DateTime;
class Index extends \Magento\Backend\App\Action
{
/**
* #var \Magento\Framework\View\Result\PageFactory
*/
protected $resultPageFactory;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $resultPageFactory)
{
parent::__construct($context);
$this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
$configProvider = new \MyPlugin\KnownUser\IntegrationInfoProvider();
$configText = $configProvider->getIntegrationInfo(true);
$customerIntegration = json_decode($configText, true);
$resultPage = $this->resultPageFactory->create();
$layout = $resultPage->getLayout();
$block = $layout->getBlock('main_panel');
$block->setAccountId($customerIntegration["AccountId"]);
$block->setVersion($customerIntegration["Version"]);
$block->setPublishDate($customerIntegration["PublishDate"]);
$block->setUploadUrl($this->getUrl('knownuser/admin/process/index'));
$block->setIntegrationConfig( $configText);
return $resultPage;
}
}
MyPlugin\knownuser\view\adminhtml\templates\admin.phtml
<p>
<label style="width:200px">Publisher</label>
<br />
<input readonly type="text" value="<?php echo $this->getAccountId() ?>"> </input>
</p>
<p>
<label style="width:100px">Version</label>
<br />
<input readonly type="text" value="<?php echo $this->getVersion() ?>">
</input>
</p>
<p>
<label style="width:100px">Publish Date</label>
<br />
<input readonly type="text" value="<?php echo $this->getPublishDate() ?
>" > </input>
</p>
<p>
<label style="width:100px">IntegrationdedConfig</label>
</p>
<textarea rows="10" cols="200" readonly>
<?php echo $this->getIntegrationConfig() ?>
</textarea>
<form id='form' method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
<script>
const url = '<?php echo $this->getUploadUrl()?>';
alert(url);
const form = document.getElementById('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
debugger;
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
</script>
So what I want to do is add a new controller and post my file to server, but I don't know how can I do that.
I tried to add another controller and post my file from JavaScript but it didn't work and just redirect my request.
my controller is like this:
MyPlugin\knownuser\Controller\Adminhtml\Process
<?php
namespace MyPlugin\KnownUser\Controller\Adminhtml\Admin;
class Index extends \Magento\Framework\App\Action\Action
{
public function execute()
{
die('test index');
echo('just for sure it has been ran');
}
}
Finally I found the solution, I just needed to add another controller like this and use it in my html:
<?php
namespace Queueit\KnownUser\Controller\Adminhtml\Admin;
class UploadConfig extends \Magento\Framework\App\Action\Action
{
public function execute()
{
$configProvider = new \Queueit\KnownUser\IntegrationInfoProvider();
if ($_SERVER['REQUEST_METHOD'] === 'POST'){
print_r('{');
$errors = "";
$extensions = ['json'];
$uploads = new \Zend_File_Transfer_Adapter_Http();
$files = $uploads->getFileInfo();
$file_name= '';
$file_tmp ='';
foreach ($files as $file => $fileInfo) {
if ($uploads->isUploaded($file)) {
if ($uploads->isValid($file)) {
if ($uploads->receive($file)) {
$info = $uploads->getFileInfo($file);
$file_name = $info[$file]['name'];
$file_type = $info[$file]['type'];
$file_tmp = $info[$file]['tmp_name'];
$file_ext1 = explode('.', $file_name);
$file_ext2 = end($file_ext1);
$file_ext = strtolower($file_ext2);
if (!in_array($file_ext, $extensions)) {
$errors = 'extension not allowed: ' . $file_name . ' ' . $file_type;
}
}
}
}
break;
}
$strConfig = "";
if ($file_name != "") {
if ($errors == "") {
$strConfig = file_get_contents($file_tmp);
$objectConfig = json_decode($strConfig);
$configProvider->updateIntegrationInfo($objectConfig->integrationInfo, $objectConfig->hash);
print_r("\"stat\" : \"Successful\",");
$configText = $configProvider->getIntegrationInfo(false);
print_r("\"configText\" : " . $configText);
}
} else {
$errors = 'Config file is not found in your request!';
}
if ($errors) {
print_r("\"errors\" : \"");
print_r($errors);
print_r("\"");
}
print_r('}');
}
}
}
<div class="form-group">
<p>
<label style="width:200px">Publisher: </label>
<label id="AccountId"><?php echo $this->getAccountId() ?></label>
</p>
<p>
<label style="width:100px">Version: </label>
<label id="Version"><?php echo $this->getVersion() ?> </label>
</p>
<p>
<label style="width:100px">Publish Date: </label>
<label id="PublishDate" class="form-control"> <?php echo $this->getPublishDate() ?> </label>
</p>
<button id='asdf' class="collapsible">Display JSON Integration Configuration</button>
<div class="content">
<div id="Config">
</div>
</div>
</div>
<hr class="HR_1" />
<div> <span>Select your new Integration Configuration to update the old one:</span></div>
<br />
<div style="overflow: auto">
<form id='form' method="post" enctype="multipart/form-data">
<label class="button" style="float:left">
<input type="file" name="files[]" accept=".json" id="files[]" class="button">
<i class="fa fa-cloud-upload"></i> Select configuration:
</label> <input type='text' id="upload-file-name" class="input-text" style='margin-left: 5px;margin-right: 10px;padding-bottom: 4px;width:400px;float:left'>
<button id="submit-uplode-file" class="button" type="submit" disabled name="submit" style="float:left">
<span id="SPAN_3">Update Configuration</span>
</button>
</form>
</div>
<br />
<div id="announcement"></div>
<script>
require([
'jquery'], function ($) {
var configString = '<?php echo $this->getIntegrationConfig() ?>';
if (configString != '') {
var config = JSON.stringify(JSON.parse(configString), null, '\t');
}
function output(inp) {
var configNode = document.getElementById("Config");
while (configNode.firstChild) {
configNode.removeChild(configNode.firstChild);
}
configNode.appendChild(document.createElement('pre')).innerHTML = inp;
}
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
(function() {
if (config) {
output(syntaxHighlight(config));
}
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
const url = '<?php echo $this->getUploadUrl() ?>';
document.getElementById('files[]').onchange = function(e) {
if (e.target.files.length > 0) {
var filename = e.target.files[0].name;
document.getElementById("upload-file-name").value = filename;
document.getElementById("announcement").innerHTML = '';
document.getElementById("submit-uplode-file").disabled = false;
}
};
const form = document.getElementById('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
console.log(files);
jQuery.ajax({
url: url,
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
console.log('Sending');
},
success: function(data) {
console.log(data);
try {
var jsonData = JSON.parse(data);
} catch (e) {
jQuery("#announcement").html("<Span style='color:red'>" + "Some thing went wrong!" + "</Span>").fadeIn();
jQuery("#announcement").html("<Span style='color:red'>" + data + "</Span>").fadeIn();
}
if (jsonData.stat != undefined && jsonData.stat == 'Successful') {
jQuery("#AccountId").text(jsonData.configText.AccountId);
jQuery("#PublishDate").text(jsonData.configText.PublishDate);
jQuery("#Version").text(jsonData.configText.Version);
output(syntaxHighlight(JSON.stringify(jsonData.configText, null, '\t')));
// jQuery("#Config").text(JSON.stringify(jsonData.configText, null, '\t'));
jQuery("#announcement").html("<Span style='color:#4CAF50'>The File is uploaded successfully!</Span>").fadeIn();
document.getElementById("submit-uplode-file").disabled = true;
} else {
if (jsonData.errors != undefined && jsonData.errors != '') {
jQuery("#announcement").html("<Span style='color:red'>" + jsonData.errors + "</Span>").fadeIn();
} else {
jQuery("#announcement").html("<Span style='color:red'>" + "Some thing went wrong!" + "</Span>").fadeIn();
}
}
},
error: function(e) {
console.log(e);
jQuery("#announcement").html("Uploading file is faild!").fadeIn();
}
});
});
})();
});
</script>

Loading gif while Post files uploads to database

I am trying to prompt a loading gif while the POST data and Files are being uploaded to the database. I did a research online and I saw couple of examples with my same issue which was solved but when I tried for example this Ajax and Jquery code, it just loads the gif and it just keeps spinning. I don't know if there is another way to do it without using Ajax but just php.
Here is the Ajax code I tried just below my form
<div id="loader"></div>
<script src="http://code.jquery.com/jquery.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
var spinner = $('#loader');
$(function() {
$('form').submit(function(e) {
e.preventDefault();
spinner.show();
$.ajax({
url: 't2228.php',
data: $(this).serialize(),
method: 'post',
dataType: 'JSON'
}).done(function(resp) {
spinner.hide();
alert(resp.status);
});
});
});
and the t2228.php file to call my php code
<?php
include '../lib/session.php';
Session::checkSession();
include '../config/config.php';
include '../lib/database.php';
include '../helpers/format.php';
$db = new Database();
$fm = new Format();
define("DOCROOT", filter_input(INPUT_SERVER, "DOCUMENT_ROOT", FILTER_SANITIZE_STRING));
$pet = new Pet();
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit'])){
$addPet = $pet->petAdd($_POST, $_FILES);
}
?>
Here is the HTML Form
<form action="" method="post" enctype="multipart/form-data">
<table class="form">
<tr>
<td>
<label>Pet Name</label>
</td>
<td>
<input type="text" name="name" placeholder="Enter Pet Name..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Pet Price</label>
</td>
<td>
<input type="text" name="price" placeholder="Enter Pet Price..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Pet Serie</label>
</td>
<td>
<input type="text" name="serie" placeholder="Enter Pet Serie..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Pet Sex</label>
</td>
<td>
<select id="select" name="sex">
<option>Select Pet Sex</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Pet Age</label>
</td>
<td>
<input type="text" name="age" placeholder="Enter Pet Age..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Upload Image</label>
</td>
<td>
<div class="post-image-collection">
<label id="list">
</label>
<label class="post-image post-image-placeholder mrm mts empty">
<input type="file" id="Photofile" name="images[]" required="required" multiple />
<span class="icon-camera"><img src="../img/608815-200.png"></span>
<p class="uppercase">Photo</p>
</label>
</div>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" Value="Add Pet" />
</td>
</tr>
</table>
</form>
Here is My PHP code
public function petAdd($data, $file){
$name = mysqli_real_escape_string($this->db->link, $data['name']);
$price = mysqli_real_escape_string($this->db->link, $data['price']);
$serie = mysqli_real_escape_string($this->db->link, $data['serie']);
$sex = mysqli_real_escape_string($this->db->link, $data['sex']);
$age = mysqli_real_escape_string($this->db->link, $data['age']);
foreach($file["images"]["tmp_name"] as $key=>$tmp_name)
{
$file_name = $file["images"]["name"][$key];
$file_size = $file["images"]["size"][$key];
$file_temp = $file["images"]["tmp_name"][$key];
$file_size_preview = $_FILES['preview']['size'];
$div = explode('.', $file_name);
$file_ext = strtolower(end($div));
$permited = array('jpg', 'jpeg', 'png', 'gif');
if($tmp_name == ""){
$msg = "<span class='error'>Fields must not be empty!</span>";
return $msg;
}
elseif ($file_size > 1048567 || $file_size_preview > 1048567) {
$msg = "<span class='error'>Image Size should be less then 1MB! </span>";
return $msg;
}
elseif (in_array($file_ext, $permited) === false) {
$msg = "<span class='error'>You can upload only:-".implode(', ', $permited)."</span>";
return $msg;
}
}
if($name == "" || $price == "" || $serie == "" || $sex == "" || $age == "") {
$msg = "<span class='error'>Fields must not be empty!</span>";
return $msg;
} else{
$query = "INSERT INTO pets(name, price, serie, sex, age, status, details, shipping, type) VALUES('$name','$price','$serie', '$sex', '$age','$status', '$details','$shipping','$type')";
$inserted_row = $this->db->insert($query);
$last_id = $this->db->link->insert_id;
foreach($file["images"]["tmp_name"] as $key=>$tmp_name)
{
$div = explode('.', $file_name);
$file_ext = strtolower(end($div));
$unique_image = substr(md5(time()), 0, 10).'.'.$file_ext;
$uploaded_image = "../uploads/".$unique_image;
$saveToFolder = DOCROOT . "/dallasfrenchies/uploads/$unique_image";
$saveToDatabase = "uploads/$unique_image";
move_uploaded_file($tmp_name, $saveToFolder);
$query = "INSERT INTO images(petId, path) VALUES('$last_id','$saveToDatabase')";
$this->db->insert($query);
sleep(3);
}
$msg = "<span class='success'> Your Pet has been added Successfully. </span>";
return $msg;
}
}
Any one with a suggestion on what to modify or add?
<div id="loader"></div>
<script src="http://code.jquery.com/jquery.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
var spinner = $('#loader');
$(function() {
$('form').submit(function(e) {
e.preventDefault();
spinner.show();
$.ajax({
url: 't2228.php',
data: $(this).serialize(),
method: 'post',
dataType: 'JSON',
success: function(resp) {
spinner.hide();
alert(resp.status);
},
error: function(resp) {
spinner.hide();
alert(resp);
}
})
});
});
Rather than .done() i used the attributes for success and error
Try below code and make few changes in ajax code. Add below parameters in your code.
processData: false,
contentType: false,
And add var formData = new FormData($(this)); line before ajax starts.
Or Check below code and make changes according to you code.
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
var spinner = $('#loader');
var formData = new FormData($(this));
$.ajax({
url: 't2228.php',
type: "POST",
data: formData,
processData: false,
contentType: false,
beforeSend: function () {
spinner.show();
},
success: function (data)
{
spinner.hide();
},
error: function (resp) {
spinner.hide();
alert(resp);
}
});
});
</script>

How to show mobile no is already exits to particular row using angularjs

i'm working on a add & remove row to add multiple user at a time with mobile no validation/available (not in use) . Its working fine. But when the mobile no is already in use for only row, Message is showing for the other rows.
Here my code html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.9.0/ui-bootstrap-tpls.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="js/addmore.js"></script>
<script src="js/dirPagination.js"></script>
</head>
<body class="nav-md" data-ng-cloak data-ng-app="AddMoreModule" data-ng-controller="AddMoreController">
<form class="form-horizontal form-label-left" name="AddMoreForm" id="AddMoreForm" autocomplete="off" enctype="multipart/form-data" novalidate>
<div class="form-group">
<div class="col-lg-12 fade-in tada" style="padding: 10px 0px 0px 0px;">
<table ng-table="tableParams" class="display table table-striped table-bordered">
<thead>
<tr>
<th width="5%">Sr.No</th>
<th width="20%">Name</th>
<th width="20%">Mobile No</th>
<th width="25%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cap in data">
<td>{{$index+1}}</td>
<td data-title="'Name'" sortable="name">
<input type="text" class="form-control" id="name" data-ng-model="cap.name" placeholder="Name" required>
</td>
<td data-title="'Mobile No'" sortable="Mobile No">
<input type="text" class="form-control" id="mobno" maxlength="10" data-ng-model="cap.mobno" data-ng-change="get_mobno(cap.mobno)" placeholder="Mobile No" required>
<strong data-ng-show="mobnoerror" style="color:#FF0000;">{{MsgE}}</strong>
</td>
<td>
<input type="submit" data-ng-click="addNewForm()" class="btn btn-default" value="Add Items" />
<input type="submit" value="Remove" class="btn btn-primary" data-ng-click="removeNewRow(cap.name,cap.mobno)" />
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-success" data-ng-disabled="AddMoreForm.$invalid" data-ng-click="submitData()"/>Submit</button>
</div>
</div>
</form>
</body>
</html>
Here is the angularJS Script
var AddMore = angular.module('AddMoreModule',['angularUtils.directives.dirPagination','ui.bootstrap'])
AddMore.controller('AddMoreController', function ($scope, $http)
{
/*Add & Remove row script starts here*/
//to remove the row
$scope.removeNewRow = function(name,mobno)
{
var index = -1;
var comArr = eval( $scope.data);
for(var i = 0; i < comArr.length; i++)
{
if(comArr[i].name==name && comArr[i].mobno==mobno)
{
index = i;
break;
}
}
if(index===-1)
{
}
$scope.data.splice(index,1);
};
//Dynamic row creation
$scope.data = [{}];
$scope.addNewForm = function()
{
$scope.data.push({});
}
/*Add & Remove row script ends here*/
$scope.get_mobno = function(mobno)
{
$http.post('get_mobno.php', { 'mobno':mobno } )
.success(function (data, status, headers, config)
{
$scope.mobnoerror = false;
if(data!="OK")
{
$scope.mobnoerror = true;
$scope.MsgE = data;
}
else
{
$scope.mobnoerror = false;
}
});
};
$scope.submitData = function()
{
var comArr = eval( $scope.data);
var name = new Array();
var mobno = new Array();
for( var i = 0; i < comArr.length; i++ )
{
name.push(comArr[i].name);
mobno.push(comArr[i].mobno);
}
if($scope.AddMoreForm.$valid)
{
var answer = confirm("Do you want to Submit?")
if (!answer)
{
}
else
{
//insert code come here
alert("Data added successfully");
}
}
else
{
alert("All fields are mandatory");
$scope.AddMoreForm.submitted= true;
}
}
});
get_mobno.php shows Ok if Mobile No is available. Now i'm little confused how to show message only particular row?

AJAX Can't be Executed in CodeIgniter Form Submission

I'm new in AJAX programming and working on a project that should use AJAX.
I'm using PHP with CodeIgniter framework, and I want to create forms that when submitted, it will return a success message without reloading the page, that's why I chose ajax. But from the code that I have made, it works without reading the AJAX, it move to another page and of course, no success message to be displayed
So my main problem is my AJAX form submission can't be executed and I don't understand why.
Any help would be appreciated.
Here is my controller.php
public function index()
{
$this->form_validation->set_rules('advice', 'Advice', 'required');
$data["CatId"]=$this->viewbook_model->getCategory();
$this->ckeditor->basePath = base_url().'assets/ckeditor/';
$this->ckeditor->config['toolbar'] = array(
array( 'Source', '-', 'Bold', 'Italic', 'Underline', '-','Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo','-','NumberedList','BulletedList' )
);
$this->ckeditor->config['language'] = 'it';
$this->ckeditor->config['width'] = '730px';
$this->ckeditor->config['height'] = '300px';
//Add Ckfinder to Ckeditor
$this->ckfinder->SetupCKEditor($this->ckeditor,'../../assets/ckfinder/');
if($this->session->userdata('is_logged_in')){
$this->load->model('feedback_model');
$data['feedback'] = $this->feedback_model->get_subject();
$advice_list = $this->feedback_model->get_subject();
$x = 0;
foreach($advice_list AS $al)
{
$data['feedback'][$x] = array(
'CategoryAdviceId' => $al['CategoryAdviceId'],
'CategoryAdviceName' => $al['CategoryAdviceName']
);
$x++;
}
$data['booklist'] = $this->feedback_model->find($this->session->userdata('username'));
$book_list = $this->feedback_model->find('username');
$y = 0;
foreach($book_list AS $bl)
{
$data['booklist'][$y] = array(
'AssetTitle' => $bl['AssetTitle'],
'bi' => $bl['bi']
);
$y++;
}
$data['adviceid'] = $this->feedback_model->get_adviceId();
$adviceid_list = $this->feedback_model->get_adviceId();
$x = 0;
foreach($adviceid_list AS $adv)
{
$data['adviceid'][$x] = array(
'AdviceId' => $adv['AdviceId']
);
$x++;
}
$page_content["page_title"] = "Send Feedback";
$page_content["title"] = "Suggestion and Feedback";
$page_content["icon_title"] = "home";
$menu_params["current_navigable"] = "Feedback";
$menu_params["sub_current_navigable"] = "";
$page_content["menu"] = $this->load->view("main_menu", $menu_params, true);
$page_content["content"] = $this->load->view("feedback", $data, true);
$page_content["navmenu"] = $this->load->view("nav_menu", $data, true);
$this->load->view("template/main_template", $page_content);
}else{
redirect('login/restricted');
}
}
//this is the function that sent data to model and return json to view for display success message
function insert_to_db()
{
$this->feedback_model->insert_into_db();
echo json_encode('true');
}
this is my form code in view.php
<form id="feedback_form" name="feedback_form" action="<?php echo base_url();?>feedback/feedback/insert_to_db" method="post" class="form-horizontal" novalidate="novalidate">
<div class="control-group">
<!--FEEDBACK TYPE-->
<label class="span2 control-label" >Feedback for</label>
<div class="controls with-tooltip">
<select class="input-tooltip span5" tabindex="2" id="CategoryAdviceSelect" name="CategoryAdviceSelect" onchange="showhidebook();" >
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($x = 0 ; $x < count($feedback) ; $x++)
{ ?>
<option value="<?php echo $feedback[$x]['CategoryAdviceId']?>"><?php echo $feedback[$x]['CategoryAdviceName'] ?></option>
<?php
} ?>
</select>
</div>
</div>
<!--SUBJECT-->
<div class="control-group">
<label for="limiter" class="control-label">Subject</label>
<div class="controls">
<input type="text" class="span5" maxlength="50" id="Subject" name="Subject" placeholder="Type Your Feedback Subject.." />
<p class="help-block"></p>
</div>
</div>
<div id="emptybox"></div>
<!--CHOOSE BOOK-->
<div id="showupbox" style="display: none;">
<div class="control-group">
<label class="control-label">Choose Book</label>
<div class="controls">
<select class="chzn-select span5" tabindex="2" id="BookSelect" name="BookSelect">
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($y = 0 ; $y < count($booklist) ; $y++)
{ ?>
<option value="<?php echo $booklist[$y]['bi']?> - <?php echo $booklist[$y]['AssetTitle']?>"><?php echo $booklist[$y]['AssetTitle']?></option>
<?php
} ?>
</select>
</div>
</div>
</div>
<!--ADVICE-->
<div class="control-group">
<label for="limiter" class="control-label" >Suggestion</label>
<div class="controls">
<?php echo $this->ckeditor->editor("Advice",""); ?>
</div>
</div>
<!--Type Advice ID-->
<div class="control-group hidden">
<label for="limiter" class="control-label" >Sugg</label>
<div class="controls">
<?php
for($x = 0 ; $x < count($adviceid) ; $x++)
{ ?>
<input type="text" class="span5" maxlength="50" id="TypeAdviceId" name="TypeAdviceId" value="<?php echo $adviceid[$x]['AdviceId']?>"/>
<?php
} ?>
<p class="help-block"></p>
</div>
</div>
<div class="control-group hidden">
<label for="limiter" class="control-label" >Sugg</label>
<div class="controls">
<input type="text" class="span5" maxlength="50" id="NoBook" name="NoBook" value="-"/>
<p class="help-block"></p>
</div>
</div>
<!--div class="alert alert-success">
<a class="close" data-dismiss="alert">×</a>
<strong>Success!</strong> Thanks for your feedback!
</div-->
<div class="bton1">
<button class="btn btn-primary round" type="submit" id="btnSubmit">Submit</button>
<button class="btn btn-primary round" type="refresh">Reset</button>
</div>
</form>
this is my script and AJAX code:
$(document).ready(function() {
//this is for CKEDITOR validation
for(var name in CKEDITOR.instances) {
CKEDITOR.instances["Advice"].on("instanceReady", function() {
// Set keyup event
this.document.on("keyup", updateValue);
// Set paste event
this.document.on("paste", updateValue);
});
function updateValue() {
CKEDITOR.instances["Advice"].updateElement();
$('textarea').trigger('keyup');
}
}
//this is my form validation
$("#feedback_form").validate({
ignore: 'input:hidden:not(input:hidden.required)',
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:{
required: function(element){
return $("#CategoryAdviceSelect").val()==1;
}
}
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required",
},
errorElement: "span",
errorPlacement: function (error, element) {
if ($(element).attr('name') == 'Advice') {
$('#cke_Advice').after(error);
} else {
element.after(error);
}
},
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
//this is my ajax submission
$("#btnSubmit").click(function() {
var formURL = $(this).attr("action");
var methodtype = $(this).attr("method");
$.ajax({
url : formURL,
type: methodtype,
data : {
CategoryAdviceSelect:CategoryAdviceSelect,
Subject:Subject,
Advice:Advice,
BookSelect:BookSelect,
TypeAdviceId:TypeAdviceId,
NoBook:NoBook
},
ajaxOptions: {
dataType: 'json'
},
success : function(data){
setTimeout(function() {location.reload(true)}, 1700);
$('#success .success-content span').html('Thankyou for your <b>feedback</b>');
$('#success').fadeIn();
setTimeout(fade_out, 1200);
}
});
return false;
});
});
instead of form tag just use: (in codeigniter)
<?php $attr = array('id'=>'feedback_form', 'name'=>'feedback_form', 'class'='form-horizontal', 'novalidate'=>'novalidate');?>
<?php echo form_open('feedback/feedback/insert_to_db', $attr);?>
change in ajaxfunction (change button click event to form submit event)
$("#feedback_form").submit(function(e) {
e.preventDefault();
var formURL = $(this).attr("action");
var methodtype = $(this).attr("method");
$.ajax({
url : formURL,
type: methodtype,
data : {
CategoryAdviceSelect:CategoryAdviceSelect,
Subject:Subject,
Advice:Advice,
BookSelect:BookSelect,
TypeAdviceId:TypeAdviceId,
NoBook:NoBook
},
ajaxOptions: {
dataType: 'json'
},
success : function(data){
setTimeout(function() {location.reload(true)}, 1700);
$('#success .success-content span').html('Thankyou for your <b>feedback</b>');
$('#success').fadeIn();
setTimeout(fade_out, 1200);
}
});
return false;
});

Categories