How to send a picture and name to the database? - mysql

Stack vue.js + laravel5.7 I need to load the image and name into the database using axios tools in the component. There is a problem in the code, I can’t understand what is wrong.
Separately, the name downloaded and displayed, it was useful to screw the picture, everything broke. The server on php7.1
Here is my template
<form v-on:submit.prevent="submitCategory()" class="col s12 l12">
<div class="col s12 l3">
<div class="input-field ">
<input id="name" type="text" v-model="posts.name">
<label for="name">Название</label>
<div class="file-field input-field">
<div class="btn">
<span>Загрузить изображение</span>
<input type="file" v-on:change="onFileChange">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
</div>
<div>
<button class="waves-effect waves-light btn">
Сохранить изменения
</button>
</div>
</div>
<div class="col s12 l3 center">
<div v-if="!posts.image">
<img src="/images/No_image.png" style="height: 200px"/>
</div>
<div v-else>
<img :src="posts.image" style="height: 200px"/>
<button #click="removeImage" class="btn">Удалить изо</button>
</div>
</div>
</form>
And this is my script
<script>
import axios from 'axios';
export default {
data: function() {
return {
posts: {
name:'',
image:'',
},
errors: []
}
},
methods:{
submitCategory() {
axios.post(`/categories`, this.posts)
.then(response => {
console.log(response)
//this.$router.push({path:'/'})
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
},
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
console.log(files);
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
var image = new Image();
var reader = new FileReader();
// var vm = this;
reader.onload = (e) => {
this.posts.image = e.target.result;
};
reader.readAsDataURL(file);
},
removeImage: function (e) {
this.posts.image = '';
e.posts.target.reset();
}
}
}
</script>
It is expected that the name and the picture will be written into the jamb with categories by the columns name and image, but nothing happens.

Related

I want to show the data in another page

I want to take the id, name image and content of tinymce editor which i want to show on another page using controller. I am using array through which i want to take id, name, image and content but i don't know how to retrive it on another controller.
<div class="col-sm-4">
<div class="form-group">
<label class="settinglabel">Name</label>
<input type="text" maxlength="20" class="form-control" ng-model="data.name">
</div>
</div>
<div class="col-sm-3" style="margin-bottom: 4px;">
<div class="BoardCardWithCustomProperties BoardCardWithCustomProperties--hover" draggable="true">
<div class="BoardCardWithCustomProperties-contents">
<img class="BoardCardCoverImage" ng-src={{data.thumbnail}}>
<div class="BoardCardWithCustomProperties-nameAndDropdownButton">
</div>
</div>
</div>
</div>
<div id="design-9">
<div class="col-sm-12" style="margin-top:10px; margin-bottom:5px">
<textarea rows="20" cols="100" ui-tinymce="tinymceOptions" ng-model="tinymceModel" />
<input name="image" type="file" id="upload" class="hidden" onchange="">
</div>
</div>
myApp.controller('SampleFormatCntrl', ['$scope', '$http', 'orderProcessService', '$timeout', 'authService', '$routeParams', 'localStorageService', '$q', 'CommonhttpService', function ($scope, $http, orderProcessService, $timeout, authService, $routeParams, localStorageService, $q, CommonhttpService) {
var id = $routeParams.id;
$scope.data = localStorageService.get("formatdata");
$scope.action = $routeParams.action;
if ($scope.action == 'Edit' || $scope.action == 'Copy') {
$scope.action = "Update"
}
else {
$scope.action = "Save"
}
$scope.tinyArray = [];
$scope.screenshot = function () {
$scope.tinyArray.push($routeScope.tinyArray);
}
<div ng-repeat="elem in data">
<button id="{{elem.id}}" ng-click="showItem($index, elem)">
{{elem.name}}
</button>
</div>
Controller:
$scope.showItem = function(elementIndex, dataItem){
console.log(elementIndex); // 0
console.log(dataItem.id + ':' + dataItem.name); // 1:Abhishek
}

Populating Dropdown list in html from Database using ViewBag

I am able to get values into ViewBag and then I am passing those values into the HTML page. The Problem I am facing is that once i am passing the value into HTML, I am not able to populate the value into the Dropdown List.
Following is my code for the same:
#using PagedList;
#using PagedList.Mvc;
#model IPagedList<NurseOneStop.SC.NurseProfile>
#{
ViewBag.Title = "People";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="peoplemain-container" ng-controller="connectCtrl">
<div class="row">
<div class="search-box">
#using (Html.BeginForm("People", "Nurse", FormMethod.Get))
{
<div class="j_searchName">
<input class="form-control" name="FirstName" placeholder="Search by FirstName" value="#ViewBag.FilterNurseSearch.FirstName" />
<input type="hidden" name="Connected" placeholder="Search Name" value="#(ViewBag.Connected == true ?"true":"false")" />
</div>
<div class="j_search2">
<center><button type="submit" class="btn btn-primary sb">Search</button></center>
</div>
}
</div>
<div class="search-box">
#using (Html.BeginForm("People", "Nurse", FormMethod.Get))
{
<div class="j_search">
<input class="form-control" name="FirstName" placeholder="Search by FirstName" value="#ViewBag.FilterNurseSearch.FirstName" />
<input type="hidden" name="Connected" placeholder="Search Name" value="#(ViewBag.Connected == true ?"true":"false")" />
</div>
<div class="j_search">
<input class="form-control" name="LastName" placeholder="Search by LastName" value="#ViewBag.FilterNurseSearch.LastName" />
</div>
<div class="j_search">
<input id="pinput" name="JobLocation" class="form-control" type="text" value="#ViewBag.FilterNurseSearch.JobLocation" placeholder="Enter a location">
<input id="Latitude" name="Latitude" type="hidden" value="#ViewBag.FilterNurseSearch.Latitude">
<input id="Longitude" name="Longitude" type="hidden" value="#ViewBag.FilterNurseSearch.Longitude">
</div>
<div class="j_search">
<select class="form-control" name="Profession">
<option value="#ViewBag.Profession" selected>Select Profession</option>
#for (int i = 1; i < ViewBag.Profession.Count + 1; i++)
{
<option value=#i #(ViewBag.FilterNurseSearch.Profession == i ? "selected" : "")>#ViewBag.Profession[i].Text</option>
}
</select>
</div>
<div class="form-group">
#Html.LabelFor(model => model., new { #class = "control-label" })
#Html.DropDownListFor(model => model.ParentProfessionId, (List<SelectListItem>)ViewBag.Profession, new { #class = "form-control" })
#Html.DropDownListFor(model => model.ParentProfessionId, (List<SelectListItem>)TempData["TempModel"], new { #class = "form-control" })
</div>
<div class="j_search2">
<center><button type="submit" class="btn btn-primary sb">Advance Search</button></center>
</div>
}
</div>
</div>
#foreach (var item in Model)
{
<div class="people_container">
<div class="connect_profile"><img src="#(item.ProfileUrl== "" ?"/image/placeholder.jpg" : #item.ProfileUrl)" title="#item.Title #item.FirstName #item.LastName" /></div>
<div class="clear"></div>
<div class="job_box">
<p><b>#item.Title #item.FirstName #item.LastName</b></p>
<p><span>#item.Profession</span></p>
</div>
<div class="job_box_btn">
<button class="details_btn">
#Html.ActionLink("View Nurse", "NurseView", "Nurse", new { NurseId = item.NurseId }, new { #class = "" })
</button>
<button class="details_btn">
<a style="display:#(item.Status==0? "block": "none")" id="connect_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId, 1)">Connect</a>
<a style="display:#(item.Status==1? "block": "none")" id="cancel_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId,3)">Cancel</a>
<a style="display:#(item.Status==2 || item.Status==3? "block": "none")" id="message_#item.NurseId" NurseFriendId="#item.NurseFriendId" href="/Nurse/GetInbox?FromNurseId=#NurseOneStop.WebSite.Models.ApplicationSession.CurrentUser.NurseId&ToNurseId=#item.NurseId&FromRecruiterId=&ToRecruiterId=">Message</a>
<div class="tick-right"><a style="display:#(item.Status==4? "block": "none")" id="accept_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId,2);"> <i class="fa fa-check"></i></a></div>
<div class="tick-wrong"><a style="display:#(item.Status==4? "block": "none")" id="reject_#item.NurseId" NurseFriendId="#item.NurseFriendId" ng-click="InviteNurse(#item.NurseId,3);"><i class="fa fa-times"></i></a></div>
</button>
</div>
</div>
}
<!--Confirm Modal -->
<div id="confirm" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content cancel-invitemodal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Cancel the Invitation to Connect</h4>
</div>
<div class="modal-body cancel-invitetion">
<h2>Are you sure you want to Cancel the Invitation to Connect</h2>
<div class="cancel-box">
<input type="button" class="btn" ng-click="RequestCancel(SelectedNurseId,3)" value="CANCEL INVITE">
<input type="button" class="btn" ng-click="Cancel()" value="DO NOT CANCEL INVITE">
</div>
</div>
</div>
</div>
</div>
<div class="pagination">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("People", new { page, Connected = ViewBag.Connected, SearchName = ViewBag.SearchName }), PagedListRenderOptions.OnlyShowFivePagesAtATime)
</div>
</div>
#section scripts{
<script>
function initMap() {
var input = document.getElementById('pinput');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function () {
var place = autocomplete.getPlace();
console.log(JSON.stringify(place));
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
var latlong = JSON.parse(JSON.stringify(place.geometry.location));
document.getElementById('Latitude').value = latlong.lat;
document.getElementById('Longitude').value = latlong.lng;
});
}
initMap();
function showhide(id) {
$("ul").hide();
$("#newpost" + id).toggle();
}
$('#pinput').on('input', function () {
document.getElementById('Latitude').value = '';
document.getElementById('Longitude').value = '';
// do your stuff
});
</script>
}
Following is how I am using my controller:
public void DropDown()
{
ProfessionDAL objProfessionDAL = new ProfessionDAL();
Profession objProfession = new Profession();
List<Profession> objProfessionList = new List<Profession>();
SelectListItem objSelect = new SelectListItem { Text = "Select Profession", Value = "", Selected = true };
objProfessionList = objProfessionDAL.GetProfessionList().Results;
var profession = (from kl in objProfessionList
select new SelectListItem
{
Text = kl.ProfessionName,
Value = kl.ProfessionId.ToString(),
Selected = false
}).ToList();
profession.Insert(0, objSelect);
ViewBag.Profession = profession;
}
public ActionResult People(bool Connected, int? page, FilterNurseSearch objFilterNurseSearch)
{
if (ApplicationSession.CurrentUser == null)
{
//redirect
return RedirectToAction("Login", "Account");
}
DropDown();
long NurseId = ApplicationSession.CurrentUser.NurseId;
ViewBag.FilterNurseSearch = objFilterNurseSearch;
Result objResult = objNurseDAL.GetNurses(NurseId, Connected, objFilterNurseSearch);
int pageSize = 12;
int pageNumber = (page ?? 1);
ViewBag.Connected = Connected;
return View(((List<NurseProfile>)objResult.Results).ToPagedList(pageNumber, pageSize));
}
I know I am making a silly mistake which I am not able to catch and henceforth, ask my fellow developers to help me.

OnChange Typescript input

I want to be able to trigger an on change when a file is selected from a input(file). I want the triggered event to set a textbox to be the name of the file.
I am using HTML5, Typescript and Angular2. I can't figure out or find an example of exactly how to produce the behavior I am after.
see my code below:
component.ts
import { Component } from '#angular/core';
import { Http } from '#angular/http';
import { Headers, RequestOptions } from '#angular/http';
#Component({
selector: 'testConnection',
// ignore error on require
template: require('./testConnection.component.html')
})
export class TestConnectionComponent {
public http: Http;
public requestData: RequestData;
public constructor(http: Http) {
this.http = http;
(<HTMLInputElement>document.getElementById('fileInput')).onchange = (ev: Event) => {
var fileInput = (<HTMLInputElement>ev.srcElement).files[0];
var fileTextbox = (<HTMLInputElement>document.getElementById('fileTextbox'));
fileTextbox.value = fileInput.name;
}
}
public testButtonClick() {
// Iniatialise Request object
let request: RequestData;
request = { "CountryCode": "", "SiteIDList": "" };
// Get site(s)
var siteIdList = (<HTMLInputElement>document.getElementById('siteIDInput')).value;
// Get selected country
var countryCode = (<HTMLInputElement>document.getElementById('countryDropdown')).value;
// Veryify contents is just site ids.
// TODO
request.CountryCode = countryCode;
request.SiteIDList = siteIdList;
// Set Http POST options
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
// Call Api with test connection data
this.http
.post('/api/TestConnection/TestConnection', JSON.stringify(request), options)
.subscribe(data => {
// alert request ok
alert('ok');
}, error => {
// Log error
console.log(error.json());
});
}
}
interface RequestData {
SiteIDList: string;
CountryCode: string;
}
component.html
<h2>Test Site Connection</h2>
<p>This will allow you to check the connectivity of a set of sites by either individually or uploading a CSV file of Site IDs.</p>
<br />
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Manual Test</h3>
</div>
<div class="panel-body">
<p>
Select the country and the sites you want to test.
</p>
<ul>
<li>Multiple sites can be selected using commas (,).</li>
<li>you can see results in the Site Connection Results tab</li>
</ul>
<br />
<!--Replace with lookup to enabled countries-->
<div class="form-group col-lg-4">
<div class="col-lg-6">
<select class="form-control" id="countryDropdown">
<option>Select Country</option>
<option>US</option>
<option>SG</option>
<option>NL</option>
</select>
</div>
</div>
<div>
<div class="col-lg-4">
<input type="text" class="form-control" placeholder="SiteID(s)" id="siteIDInput" />
</div>
<button class="btn btn-primary" (click)="testButtonClick()">Test</button>
</div>
</div>
</div>
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Upload file</h3>
</div>
<div class="panel-body">
<div>
<p>Upload a CSV file of sites to test all at once.</p>
<br />
<div class="col-lg-4">
<input type="text" class="col-lg-4 form-control" id="fileTextbox" disabled/>
</div>
<label class="btn btn-primary">
Browse <input type="file" id="fileInput" style="display:none;" onchange="{ setFileName() }"/>
</label>
<button class="btn btn-primary" (click)="searchButtonClick()">Test</button>
</div>
</div>
</div>
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Try using (change) event binding
<input type="file" id="fileInput" style="display:none;" (change)="setFileName()"/>
If you need to retrieve the file name before uploading it you can do it this way :
#Component({
selector: 'my-app',
template: `
<div>
<input type="file" (change)="onChange($event)"/>
</div>
<p>Filename : {{filename}}</p>
`,
providers: []
})
export class AppComponent {
filename: string;
constructor() { }
onChange(event) {
this.filename = event.srcElement.files[0].name;
}
}
Here is a working plunker

Remove Previously selected image in dropzone

I am using dropzone with a form on a modal. I have one button that is 'Add Slider'. When I click on that button the modal is opened. In that modal I have attached an image on dropzone and click on cancel button. When I click on 'Add Slider' button again it shows the previously selected image in dropzone. I want to remove the previously selected image.
Html Code
<modal title="Manage HomeSlider" modaltype="modal-primary" visible="IsFormVisible">
<form name="frmHomeSlider" method="post" class="form-horizontal bv-form" novalidate="novalidate" ng-submit="frmHomeSlider.$valid && fnSaveHomeSlider()">
<modal-body>
<input type="hidden" class="form-control" name="ID" ng-model="HomeSlider.ID" />
<div class="form-group">
<label class="col-lg-3 control-label">Upload Slider Photo</label>
<div class="col-lg-9">
<div class="dropzone profileImage" customdropzone="dropzoneConfig">
<div class="dz-default dz-message">
<div ng-show="HomeSlider.FullPathPhoto==''">
<span>Upload photo here</span>
</div>
<img src="{{HomeSlider.FullPathPhoto}}" required />
</div>
</div>
<input type="hidden" name="Photo" ng-model="HomeSlider.HomeSliderPhoto" required />
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Image Name</label>
<div class="col-lg-9">
<input type="text" class="form-control input-sm" name="ImageName" ng-model="HomeSlider.ImageName" placeholder="Enter Image Name" required />
</div>
</div>
</modal-body>
<modal-footer>
<button type="submit" class="btn btn-blue" ng-disabled="frmHomeSlider.$invalid">Submit</button>
<button type="reset" class="btn btn-default" ng-click="fnShowHomeSliderForm(false)">Cancel</button>
</modal-footer>
</form>
</modal>
Js Code
$scope.dropzoneConfig = {
'options': { // passed into the Dropzone constructor
'url': ContentService.UploadHomeSliderPhoto,
'addRemoveLinks': true,
'acceptedFiles': 'image/*',
'uploadMultiple': false,
'maxFiles': 1,
'dictDefaultMessage': 'Upload your photo here',
'init': function () {
this.on('success', function (file, response) {
$scope.HomeSlider.HomeSliderPhoto = response.FileNames[0];
});
this.on('thumbnail', function (file) {
if (file.width < 1800 || file.height < 1200 || file.width > 1800 || file.height > 1200) {
file.rejectDimensions();
}
else {
file.acceptDimensions();
}
});
},
'accept': function (file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function () {
done("The image must be at least 1800 x 1200px");
};
}
},
'eventHandlers': {
'sending': function (file, xhr, formData) {
},
'success': function (file, response) {
$scope.HomeSlider.HomeSliderPhoto = response.FileNames[0];
},
'error': function () {
$rootScope.Common.notifyDanger("Error accure while upload photo.")
}
}
};

Why doesn't Bootstrap popover scroll to form element?

I have resorted to using Bootstrap popover because HTML validation exhibits the same behavior I am now experiencing. Perhaps the solution for one will work for both.
JS
var validate = validate || {};
validate.issueError = function ($elem, msg, placement) {
placement = placement == undefined ? 'bottom' : placement;
$elem.attr('data-toggle', 'popover');
$elem.attr("data-offset", "0 25%");
var exclamationPoint = "<span style='font-weight: bold; font-size:medium; color: white; background-color: orange; height: 12px; padding: 1px 6px; margin-right: 8px;'>!</span>";
var content = "<span style='font-size: smaller;'>" + msg + "</span>";
$elem.popover("destroy").popover({
html: true,
placement: placement,
content: exclamationPoint + content
})
$elem.focus();
$elem.popover('show');
setTimeout(function () { $elem.popover('hide') }, 5000);
$elem.on("keydown click", function () {
$(this).popover('hide');
$(this).off("keydown click")
})
}
validate.edits = {
required: function ($form) {
var $reqFlds = $form.contents().find('[required], [data-required]');
$reqFlds.each(function () {
var $this = $(this);
var result = ($this.filter("input, select, textarea").length) ? $this.val() : $this.text();
if (!$.trim(result)) {
validate.issueError($this, "Please fill out this field.");
return false;
}
});
return true;
}
HTML (note I have substituted "required' with "data-required" to force the Bootstrap routines).
<!DOCTYPE html>
<html>
<head>
<title>Writer's Tryst - Writers Form</title>
<link type="text/css" href="css/writers.css" rel="stylesheet" />
<style>
body {padding: 0 20px;}
.limited-offer {
background-color: white;
padding: 3px;
margin-bottom: 12px;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="container-fluid">
<img id="img-writers" src="#" alt="images" />
<form id="form-writers" method="post" class="form-horizontal well">
<h1>Writers</h1>
<div class="form-group">
<label for="title" class="col-lg-3 control-label">Title</label>
<div class="col-lg-9">
<input type="text" class="form-control" data-required id="title" name="title" autofocus="true" placeholder="Title" />
</div>
</div>
<div class="form-group">
<label for="form-type" class="col-lg-3 control-label">Type of work</label>
<div class="col-lg-9">
<select class="form-control" data-required id="form-type" name="form-type"></select>
</div>
</div>
<div class="form-group">
<label for="genre" class="control-label col-lg-3">Genre</label>
<div class="col-lg-9">
<select id="genre" name="genre" class="form-control" data-required></select>
</div>
</div>
<div class="form-group">
<label for="nbr-pages" class="control-label col-lg-3">Number Pages</label>
<div class="col-lg-9">
<input type="number" id="nbr-pages" name="nbr-pages" class="form-control" data-required placeholder="Pages" />
</div>
</div>
<div id="tips">The objective of a synopsis or query letter is to entice enablers into requesting your manuscript.
It must be concise and to the point and of course very well written. One page is preferred and no more than 3 pages will be accepted.
Sample Query Letter
</div>
<p id="file-warning" class="thumbnail">Your synopsis/query letter must be a PDF file.
<a target="_blank" href="https://www.freepdfconvert.com/" target="_blank">Free file conversion to PDF.</a>
</p>
<div>
<a id="file-upload" class="btn btn-custom-primary btn-file btn-block text-xs-center" role="button">Choose PDF to Upload
<br/><div id="filename" class="btn-block" style="color: #fff">No file chosen</div>
</a>
<input type="file" id="file2upload" style="display: none">
</div><br/>
<div class="form-group">
<!-- <button type="submit" id="writers-submit" class="btn btn-custom-success btn-block m-t-8">Submit</button>-->
</div>
<div class="limited-offer">For a limited time, writer submissions will cost <span style="color: #f00; font-weight:bold">$15.00</span> to offset screening and editing costs and to promote quality synopsises and query letters. We reserve the right to change this policy without notice.</div>
<!-- <form id="form-paypal" name="form-paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" onsubmit="return ajaxSubmit()">-->
<form id="form-paypal" name="form-paypal" method="post" target="_top">
<input type="submit" class="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="U2LE82Z45PJ54">
<input style="display: block; margin: 0 auto;" id="but-pp" type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_paynowCC_LG.gif" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="PayPal" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
<input id="userid" name="userid" type="hidden" />
<input id="filesize-limit" name="filesize-limit" type="hidden" value="150000" />
</form>
</div>
<script>
angular.element(document).ready(function () {
showImages($("#form-writers"), $("#img-writers"), "authors", ["blake.jpg", "Melville.jpg", "lewis-carroll.jpg", "stephen-king.jpg", "twain.jpg", "camus.jpg", "nietzsche.jpg", "hesse.jpg"]);
});
$(function () {
populateWritersDropdowns();
$(document).on('change', ':file', function () {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$('#file-upload').on('click', function (e) {
e.preventDefault();
$('#file2upload')[0].click();
});
$("#file2upload").on("change", function () {
var filepath = $('#file2upload')[0].value;
var filename = filepath.substr(filepath.lastIndexOf("\\") + 1);
$("#filename").text(filename)
});
$("#but-pp").on("mousedown", function (e) {
//if (!$("#form-writers").get(0).checkValidity()) return false;
var $ret = validate.edits.required($("#form-writers"));
alert($ret.length);
if ($ret != true) {
$ret.focus();
return false;
}
if (!validate.edits.requireFile($("#filename"))) return false;
if (!fileEdits()) return false;
ajaxSubmit();
function fileEdits() {
var fileSizeLimit = $("#filesize-limit").val();
var file = document.getElementById('file2upload').files[0];
var fileName = file.name;
var fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
var fileSize = file.size;
if (fileSize > fileSizeLimit) {
showMessage(0, "Your file-size (" + (Math.round(parseInt(fileSize) / 1000)).toLocaleString() + "kb) exceeds the limit of " + (fileSizeLimit.toLocaleString() / 1000) + "kb");
return false;
} else {
if (fileExt.toLowerCase() != "pdf") {
showMessage(0, "Your synopsis / query letter MUST be a PDF file.");
return false;
};
return true;
}
};
function ajaxSubmit() {
var file_data = $('#file2upload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('action', "upload");
form_data.append('title', $("#title").val());
form_data.append('form-type', $("#form-type").val());
form_data.append('genre', $("#genre").val());
form_data.append('nbr-pages', $("#nbr-pages").val());
form_data.append('account-id', localStorage.getItem("account-id"));
ajax('post', 'php/writers.php', form_data, success, 'Error uploading file:', 'text', false, false, false);
function success(result) {
if (result.indexOf("PDF") == -1) {
showMessage(1, "Your submission will go live and you will be notified after our reviews are complete.");
var data = {};
data['writer-id'] = result;
ajax('post', 'php/paypal-ipn.php', data, listenerStarted);
function listenerStarted(result) {
alert("pp=" + result);
}
} else {
showMessage(0, result);
}
setTimeout(function () {
document.getElementById('form-writers').reset();
$("#filename").text("No file chosen");
}, 5000);
};
};
});
});
</script>
</body>
</html>