I've been working with Ajax to send and upload files, everything worked perfect, I could upload both photos and files with no problem, but now it just don't work for .pdf files.
This is why I got, from my jQuery file:
function uploadImage(){
$('#file').change(function(){
var file = this.files[0]
if(file){
$('.alert.alert-danger').hide();
$('#filename').text(file.name);
$('#filename').show();
$('.cargando').show();
$('.uploaded').hide();
$('#file').hide();
name = file.name;
size = file.size;
type = file.type;
uploadAjax();
}
});
$('#uploadremove').click(function(e){
e.preventDefault();
$('.alert.alert-danger').hide();
$('#file').show();
$('.cargando').hide();
$('#filename').hide();
$('#uploadok').hide();
$('#uploadremove').hide();
$('#file_id').val("0");
$('.fileinput-button').show();
$('.savebtn').toggleClass('disabled');
$('.uploaded').hide();
});
}
function uploadAjax(){
var inputFileImage = document.getElementById("file");
var filelocation = $('#file').val();
var file = inputFileImage.files[0];
var info = new FormData();
var tipo_archivo = $("#file").attr('accept');
var tipo_archivo = type;
info.append('tipo', tipo_archivo); console.log(file);
var url = HTTP+"admin/uploadfile";
$.ajax({
url:url,
type:'POST',
contentType:false,
data: info,//{archivo : file, tipo : tipo_archivo},
processData:false,
cache:false,
success:function(response){
if(response != '' && !($.isNumeric(response)) ){
$('.alert.alert-danger #uploaderror').html(response);
$('.alert.alert-danger').fadeIn(2000);
$('.cargando').hide();
$('#filename').hide();
$('#file').show();
}
else{
$('.cargando').hide();
$('#uploadok').show();
$('#uploadremove').show();
$('#file_id').val(response);
$('.fileinput-button').hide();
$('.savebtn').toggleClass('disabled');
if(tipo_archivo == "image/*"){
console.log(file);
}
}
}
});
}
And this is the HTML form:
<form class="form-horizontal validate" role="form" method="post" action="<?=fk_link().'admin/savecv'?>">
<input name="location" type="hidden" class="location" value="admin/addcv/<?=#$profesor['id']?>" >
<input name="profesor_id" type="hidden" value="<?=#$profesor['id']?>" >
<div class="form_message">
<div class="alert alert-warning">
</div>
</div>
<?
$texto = "Seleccionar Archivo PDF";
if(#$profesor['profesor_cv']){ $texto = "Cambiar Cv";?>
<div class="uploaded">
<a class="btn btn-success fileDownloadPromise" target="_blank" href="<?=fk_link().'uploads/'.#$cv['cv']?>">
<i class="glyphicon glyphicon-cloud-download"></i>
<span>Descargar</span>
</a>
</div>
<?
} else $texto = "Seleccionar Archivo PDF";?>
<span class="btn btn-danger fileinput-button">
<i class="glyphicon glyphicon-cloud-upload"></i>
<span><?=$texto?></span>
<!-- The file input field used as target for the file upload widget -->
<input id="file" type="file" name="fileToUpload" id="filesToUpload">
</span>
<span class="cargando"><img src="<?=fk_theme_url().'/images/loading.gif'?>"></span>
<span id="filename"></span>
<input id="file_id" name="file_id" type="hidden" value="0" >
<span id="uploadok" class="glyphicon glyphicon-ok"></span>
Cambiar
<div class="clearfix" style="height:10px"></div>
<div class="alert alert-danger col-md-3" style="display:none;">
<span class="glyphicon glyphicon-warning-sign"></span>
<span id="uploaderror">error example</span>
</div>
<input class="btn btn-primary savebtn disabled" value="Guardar" type="submit">
</form>
As I said, everything worked fine but now it only works with images.
info.append('tipo', tipo_archivo);
Up there should be:
info.append('tipo', file);
Related
I created a form upload which contains some inputs but when I submitted the form to ajax, ajax was unable to grap the file name.
I keep on getting Notice: Undefined index: userImage in C:\wamp\www\osun\i_admin\php_action\uploadImage.php on line 14 . userImage is the name of the file
index.php
<?php include('header.php'); ?>
<?php include('top.php'); ?>
<?php include('links.php'); ?>
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Worker of the Month</h2>
</div>
<!-- Basic -->
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div id="error" class="closeit"></div>
<div id="messages"></div>
<div class="body">
<form enctype="multipart/form-data" id="uploadImageForm">
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="name" id="name">
<label class="form-label">Worker's Name</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="dept" id="dept">
<label class="form-label">Department</label>
</div>
</div>
<div class="form-group form-float">
<div class="input-group">
<div class="form-line">
<input type="text" data-type="date" id="date" name="date" placeholder="Date" class="form-control datepicker">
</div>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<textarea name="description" id="description" cols="30" rows="5" class="form-control no-resize"></textarea>
<label class="form-label">Description</label>
</div>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Photo</label>
<div id="kv-avatar-errors-2" class="center-block" style="width:800px;display:none"></div>
<div class="kv-avatar center-block" style="width:200px">
<input id="avatar-2" name="userImage" type="file" class="file-loading">
</div>
</div>
<div class="form-group" align="center">
<button type="input" name="submit" class="btn btn-success btn-md btn-icon waves-effect" id="btn-submit" ><i class="fa fa-check-square-o"></i> Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- #END# Basic -->
</div>
</section>
<?php include('footer.php'); ?>
uploadimage.php
include('../../includes/functions.php');
if($_POST) {
$valid = array('success' => false, 'messages' => array());
$name = $mysqli->real_escape_string($_POST['name']);// user name
$dept = $mysqli->real_escape_string($_POST['dept']);
$desc = $mysqli->real_escape_string($_POST['description']);// user email
$yr = $mysqli->real_escape_string($_POST['date']);
$fileName = $_FILES['userImage']['name'];
$type = explode('.', $fileName);
$type = $type[count($type) - 1];
$url = '../user_images/' . uniqid(rand()) . '.' . $type;
if(in_array($type, array('gif', 'jpg', 'jpeg', 'png'))) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
if(move_uploaded_file($_FILES['userImage']['tmp_name'], $url)) {
// insert into database
$sql = "INSERT INTO worker_of_the_month (name, dept, description, given, img) VALUES ('$name','$dept','$desc','$yr', '$url')";
if($mysqli->query($sql) === TRUE) {
$valid['success'] = true;
$valid['messages'] = "Successfully Saved.";
}
else {
$valid['success'] = false;
$valid['messages'] = "Error while saving. " . $mysqli->error;
}
$mysqli->close();
}
else {
$valid['success'] = false;
$valid['messages'] = "Error while saving. " . $mysqli->error;
}
}
}
echo json_encode($valid);
// upload the file
}
Ajax.js
$('document').ready(function() {
/* validation */
$("#uploadImageForm").validate({
rules:
{
name:{
required: true
},
dept:{
required: true
},
description:{
required: true
},
date:{
required: true
},
},
messages:
{
name: "Worker name required",
dept: "Worker department name required",
description: "Enter description for this honour.",
date: "Please select date",
},
submitHandler: submitForm
});
/* validation */
/* form submit */
function submitForm()
{
var data = $("#uploadImageForm").serialize();
$.ajax({
type : 'POST',
url : 'php_action/uploadImage.php',
data : data,
beforeSend: function()
{
$("#error").fadeOut();
$("#btn-submit").html('<img src="../img/processing.gif" width="30" /> processing');
},
success : function(data)
{
if(data.success == true)
{
$("#btn-submit").html('<img src="../img/processing.gif" width="30" /> Saving ...');
$("#messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
data.messages +
'</div>');
$('#uploadImageForm')[0].reset();
/*setTimeout(' window.location.href = "success.php"; ',4000);*/
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#btn-submit").html('<span class="fa fa-check-square-o"></span> Save');
});
}
}
});
return false;
}
/* form submit */
});
</script>
What am I doing wrong?
You need to use a FormData() to pass files.
Change
var data = $('#uploadImageForm').serialize();
to
var form = $('#uploadImageForm')[0];
var data = new FormData(form);
As #ThisGuyHasTwoThumbs pointed you should set cache, contentType and processData via your ajax call
$.ajax({
cache: false,
processData: false,
contentType: false,
//other ajax parameters
});
You cannot POST files via AJAX like you have your code now.
This is how you can upload files using javascript and way better option:
PHP:
<?php
$fileName = $_FILES['afile']['name'];
$fileType = $_FILES['afile']['type'];
$fileContent = file_get_contents($_FILES['afile']['tmp_name']);
$dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);
$json = json_encode(array(
'name' => $fileName,
'type' => $fileType,
'dataUrl' => $dataUrl,
'username' => $_REQUEST['username'],
'accountnum' => $_REQUEST['accountnum']
));
echo $json;
?>
HTML:
<!DOCTYPE html>
<!--
Copyright 2012 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Author: Eric Bidelman (ericbidelman#chromium.org)
-->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<title>xhr.send(FormData) Example</title>
</head>
<body>
<input type="file" name="afile" id="afile" accept="image/*"/>
<script>
document.querySelector('#afile').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("afile", file);
// These extra params aren't necessary but show that you can include other data.
fd.append("username", "Groucho");
fd.append("accountnum", 123456);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handle_file_upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
console.log('Server got:', resp);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
}, false);
</script>
<!--[if IE]>
<script src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
<script>CFInstall.check({mode: 'overlay'});</script>
<![endif]-->
</body>
</html>
Quick example taken from: https://gist.github.com/ebidel/2410898
I am using Angular in this code to send formData to my upload.php file and then from upload.php, copying file to another Direcrtory and insert its address to MySQL musiclist data base but my code isn't working and not even showing any Error I don't know what to do
Any help would be Appreciable
<body>
<div class="container" ng-app="myapp" ng-controller="cntrl">
<div class="col-md-4">
<input type="file" file-input="files">
</div>
<div class="col-md-6">
<button class="btn btn-info" ng-click="uploadfile()">upload</button>
</div>
</div>
<div class="container" ng-app="myapp" ng-controller="cntrl">
<div class="col-md-4">
<input type="file" file-input="files">
</div>
<div class="col-md-6">
<button class="btn btn-info" ng-click="uploadfile()">upload</button>
</div>
</div>
</body>
</html>
<script>
var app = angular.module("myapp",[]);
app.directive("fileinput", function($parse){
return{
link : function($parse,element,attrs){
element.on("change", function(event){
var files = event.target.files;
$parse(attrs.fileInput).assign(element[0].files);
$scope.apply();
});
}
}
});
app.controller("cntrl",function($scope,$http){
$scope.uploadfile = function(){
var form_data= new FormData();
angular.forEach($scope.files, function(file){
form_data.append('file',file);
});
$http.post('upload.php', form_data,
{
transformRequest: angular.identity,
headers{'Content-Type': undefined ,'Process-Data': false}
}).success(function(response){
alert(response);
});
}
});
upload.php Code is
<?PHP
$connect= mysqli_connect("localhost","root","","musiccloud");
if(!empty($_FILES)){
$path='uploads/'.$_FILES['file'['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'],$path))
{
$Insertquery= "INSERT INTO musiclist(name) VALUES('".$_FILES['file']
['name']."')";
if(mysqli_query($connect,$Insertquery))
{
echo 'file Uploaded';
}
else{
echo 'file Not Uploaded';
}
}
}
else{
echo 'some Error';
}
?>
Why this code not working
I am building a chatbot application using php and aiml. I have made the chat window for the same. But in chat window when I enter the message it overwrites the previous message every time. I want that the new message should come in the new line. Please help
My Code is
<div class="panel" id="chat">
<div class="panel-heading" style="background-color:#337ab7">
<h3 class="panel-title" style="color:#FFF">
<i class="icon wb-chat-text" aria-hidden="true" ></i> How Can I Help You
</h3>
</div>
<div class="panel-body">
<div class="chats">
<div class="chat">
<div class="chat-avatar">
<a class="avatar avatar-online" data-toggle="tooltip" href="#" data-placement="right" title="" data-original-title="June Lane">
<i></i>
</a>
</div>
<div class="chat-body">
<div class="chat-content">
<p>
<div class="botsay">Hey!</div>
</p>
<time class="chat-time" datetime="2015-07-01T11:37">
<?php
echo date("h:i:sa");
?></time>
</div>
</div>
</div>
<div class="chat chat-left">
<div class="chat-avatar">
<a class="avatar avatar-online" data-toggle="tooltip" href="#" data-placement="left" title="" data-original-title="Edward Fletcher">
<i></i>
</a>
</div>
<div class="chat-body">
<div class="chat-content">
<p><div class="usersay"> </div></p>
<time class="chat-time" datetime="2015-07-01T11:37">
<?php
echo date("h:i:sa");
?></time>
</div>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<form method="post" name="talkform" id="talkform" action="index.php">
<div class="input-group">
<input type="text" class="form-control" name="say" >
<input type="hidden" name="convo_id" id="convo_id" value="<?php echo $convo_id;?>" />
<input type="hidden" name="bot_id" id="bot_id" value="<?php echo $bot_id;?>" />
<input type="hidden" name="format" id="format" value="json" />
<span class="input-group-btn">
<input class="btn btn-primary" type="submit" name="submit" id="submit" value="Send" />
</span>
</div>
</form>
</div>
I am using ajax to input values in the chat window using aiml.
$(document).ready(function() {
// put all your jQuery goodness in here.
$('#talkform').submit(function(e) {
e.preventDefault();
var user = $('#say').val();
$('.usersay').text(user);
var formdata = $("#talkform").serialize();
$('#say').val('');
$('#say').focus();
$.get('<?php echo $url ?>', formdata, function(data){
var b = data.botsay;
if (b.indexOf('[img]') >= 0) {
b = showImg(b);
}
if (b.indexOf('[link') >= 0) {
b = makeLink(b);
}
var usersay = data.usersay;
if (user != usersay) {
$('.usersay').text(usersay);
}
$('.botsay').html(b);
}, 'json').fail(function(xhr, textStatus, errorThrown){
$('#urlwarning').html("Something went wrong! Error = " + errorThrown);
});
return false;
});
});
function showImg(input) {
var regEx = /\[img\](.*?)\[\/img\]/;
var repl = '<br><img src="$1" alt="$1" width="150" />';
var out = input.replace(regEx, repl);
console.log('out = ' + out);
return out
}
function makeLink(input) {
var regEx = /\[link=(.*?)\](.*?)\[\/link\]/;
var repl = '$2';
var out = input.replace(regEx, repl);
console.log('out = ' + out);
return out;
}
The problem with your code is you are just keeping on replacing the contents of usersay and botsay. You need to append or prepend as per your need to make it work.
Consider this bit of code, you need to change as per comments:
$.get('<?php echo $url ?>', formdata, function(data){
var b = data.botsay;
if (b.indexOf('[img]') >= 0) {
b = showImg(b);
}
if (b.indexOf('[link') >= 0) {
b = makeLink(b);
}
var usersay = data.usersay;
if (user != usersay) {
$('.usersay').append(usersay); // 1. Change here.
}
$('.botsay').append(b); // 2. Change here.
}, 'json')
Here i have two form fields(file upload),first user select the logo and select one banner image means value is getting in next page (home.php).suppose user select one logo and select multiple banner image means i can not get the value in next page (home.php).how can do this ?
<script>
var i=0;
$(document).on("click",".add_banner",function() {
i++;
var htmlText = '';
htmlText += '<div class="form-group"><label class="col-md-3 control-label">Project Banners</label><div class="col-md-6"><div class="fileupload fileupload-new" data-provides="fileupload"><div class="input-append"><div class="uneditable-input"><i class="fa fa-file fileupload-exists"></i><span class="fileupload-preview"></span></div><span class="btn btn-default btn-file"><span class="fileupload-exists">Change</span><span class="fileupload-new">Select file</span>';
htmlText +='<input type="file" name="banners[]" id="banners' + i +'">';
htmlText += '</span><span style="margin-left:10px"><button type="button" class="btn btn-default add_banner" id="add_banner">Add</button></span>Remove</div></div></div></div>';
$('#add_banner_append').append(htmlText);
});
</script>
<script>
$(document).ready(function(){
$('#btn-submit').click(function(){
if($('#empForm').valid()){
var formData = new FormData();
var formData = new FormData($('#empForm')[0]);
formData.append('logo', $('input[type=file]')[0].files[0]);
formData.append('banners', $('input[type=file]')[1].files[1]);
$.ajax({
type:'POST',
url :"php/home.php",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "Success"){
$("#alert_success").show();
$("#alert_success").fadeOut(3000);
setTimeout(function () {
window.location.href = "dashboard.php";
}, 2000); //will call the function after 2 secs.
}
},
error:function(exception){
alert('Exeption:'+exception);
}
});
return false;
}
});
});
// Shorthand for $( document ).ready()
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form class="form-horizontal form-bordered" method="POST" id="empForm">
<div class="form-group">
<label class="col-md-3 control-label">Project Logo</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="logo" name="logo" required="" data-msg-required="File" value="" aria-required="true">
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Project Banners</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="banners" name="banners[]" required="" data-msg-required="File" value="" aria-required="true">
</span><span style="margin-left:10px">
<button type="button" class="btn btn-default add_banner" id="add_banner">Add</button></span>
</div>
</div>
</div>
</div>
<div id="add_banner_append"></div>
<div class="form-group">
<div class="col-md-3">
</div>
<div class="col-md-6">
<input type="button" class="btn btn-primary btn-block" id="btn-submit" name="submit" value="SUBMIT">
</div>
</div>
</form
$postedBanners = array();
/* foreach ($_FILES['banners']['name'] as $key => $value) {
$postedBanners[$key] = array(
'name' => $_FILES['banners']['name'][$key],
'type' => $_FILES['banners']['type'][$key],
'tmp_name' => $_FILES['banners']['tmp_name'][$key],
'error' => $_FILES['banners']['error'][$key],
);
} */
$uploads_dir = '/banners';
foreach ($_FILES["banners"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["banners"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = $_FILES["banners"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
You are missing enctype in both html form and ajax calling. You should add enctype in form like as <form class="form-horizontal form-bordered" method="post" id="empForm" enctype="multipart/form-data">.
Aslo add enctype in ajax calling -
$('#btn-submit').click(function(){
if($('#empForm').valid()){
var formData = new FormData();
var formData = new FormData($('#empForm')[0]);
formData.append('logo', $('input[type=file]')[0].files[0]);
formData.append('banners', $('input[type=file]')[1].files[1]);
$.ajax({
type:'POST',
url :"test.php",
enctype: 'multipart/form-data',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
if(data == "Success"){
$("#alert_success").show();
$("#alert_success").fadeOut(3000);
setTimeout(function () {
window.location.href = "dashboard.php";
}, 2000); //will call the function after 2 secs.
}
},
error:function(exception){
alert('Exeption:'+exception);
}
});
return false;
}
});
I have added enctype: 'multipart/form-data' in ajax calling.
At server end you need to get all multiple added banner image as following -
if(!empty($_FILES['banners']['name'])){
$postedBanners = array();
foreach ($_FILES['banners']['name'] as $key => $value) {
$postedBanners[$key] = array(
'name' => $_FILES['banners']['name'][$key],
'type' => $_FILES['banners']['type'][$key],
'tmp_name' => $_FILES['banners']['tmp_name'][$key],
'error' => $_FILES['banners']['error'][$key],
);
}
echo '<pre>';
print_r($postedBanners);
}
I will return output as following -
Array
(
[0] => Array
(
[name] => preview.png
[type] => image/png
[tmp_name] => /private/var/tmp/php9Fyir9
[error] => 0
)
)
For Upload banner images in a folder.
$uploads_dir = '/uploads';
foreach ($_FILES["banners"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["banners"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["banners"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
Here i want save to database, the value 'isi' from textarea, when i running the function, always get null value from textarea, what i do for fix that ?
thanks.
Here script in view :
<div class="tab-pane active" id="tab_1">
<div class="box-body">
<textarea class="form-control" rows="3" placeholder="Apa yang Anda pikirkan ?">{!! Input::old('quoteinput') !!}</textarea>
</div>
<div class="box-footer">
<a href="{!! URL::to('/timeline/quote') !!}">
<button type="submit" class="btn btn-info pull-right">Posting</button>
</a>
</div>
</div>
Here script from controller :
public function postQuote()
{
$Qdata = new QuotesModel;
$Qdata -> kode_user = Auth::user()->kode_user;
$Qdata -> kode_quote = 'Q'.strtotime(Carbon\Carbon::now()).rand(100,999);
$Qdata -> isi = Input::get('quoteinput');
$kategori = 'quote';
if($Qdata->save())
{
$this->postToTimeline($Qdata->kode_quote , $kategori);
}
Session::flash('message', 'Berhasil memposting !');
return redirect()->back();
}
Here script in route:
Route::get('/timeline/quote', 'ClientTimeLineContr#postQuote' );
You can use jquery to get textarea value without form. And to save it to database use AJAX.
HTML
<textarea name="quoteinput" class="form-control mytextarea" rows="3" placeholder="Apa yang Anda pikirkan ?">{!! Input::old('quoteinput') !!}</textarea>
<button type="submit" class="btn btn-info pull-right">Posting</button>
Jquery and ajax:
$(document).on('click','button',function(e)
{
e.preventDefault();
var text = $('textarea.mytextarea').val(); //this is the value of textarea
$.ajax({
type:"POST",
url: "{{url('/timeline/quote')}}",
data: {
"_token": "{{ csrf_token() }}",
"text": text
},
success: function (data) {
var res = $.parseJSON(data);
if(res == true)
{
alert('saved');
}
}
});
});
Controller
public function postQuote(Request $request)
{
if($request->ajax())
{
$text=$request->text;
//save this textarea value to database
echo json_encode(TRUE);die;
}
You can't get value without creating form in html, wether you do it with form::open or by <form> tag. You also have to give the name to the textarea.
<div class="tab-pane active" id="tab_1">
<dorm method="GET" action="{!! URL::to('/timeline/quote') !!}">
<div class="box-body">
<textarea name="quoteinput" class="form-control" rows="3" placeholder="Apa yang Anda pikirkan ?">{!! Input::old('quoteinput') !!}</textarea>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right">Posting</button>
</div>
</form>
</div>