How upload an image in nuxt js and laravel 7 - laravel

I develop an ecommerce application in nuxtjs frontend and laravel backend.But it is difficult to upload image and save it in the database.Can anyone help me solve the problem ?

Here example of Nuxt Or Vuejs image uploader with Laravel API. I left a comment inside the code for you.
First of all, you must make upload.vue component with this content.
<template>
<div class="container">
<label class="custom-file" for="file">
{{files.length ? `(${files.length}) files are selected` : "Choose files"}}
<input #change="handleSelectedFiles" id="file" multiple name="file" ref="fileInput" type="file">
</label>
<!--Show Selected Files-->
<div class="large-12 medium-12 small-12 cell">
<div class="file-listing" v-for="(file, key) in files">{{ file.name }} <span class="remove-file" v-on:click="removeFile( key )">Remove</span></div>
</div>
<!--Submit Button && Progress Bar-->
<div>
<button #click="upload">Start Upload</button>
- Upload progress : {{this.progress}}
</div>
</div>
</template>
<script>
export default {
data() {
return {
files : [],
progress: 0
}
},
computed: {
/*The FormData : Here We Make A Form With Images Data To Submit.*/
form() {
let form = new FormData();
this.files.forEach((file, index) => {
form.append('files[' + index + ']', file);
});
return form;
}
},
methods : {
handleSelectedFiles() {
let selectedFiles = this.$refs.fileInput.files;
for (let i = 0; i < selectedFiles.length; i++) {
/*Check Already Has Been Selected Or Not ...*/
let isFileExists = this.files.find(file => file.type === selectedFiles[i].type && file.name === selectedFiles[i].name && file.size === selectedFiles[i].size && file.lastModified === selectedFiles[i].lastModified);
if (!isFileExists)
this.files.push(selectedFiles[i]);
}
},
removeFile(key) {
this.files.splice(key, 1);
},
upload() {
const config = {
onUploadProgress: (progressEvent) => this.progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
};
this.$axios.post('host-url/upload-image', this.form, config)
.then(res => {
this.progress = 0;
this.files = [];
console.log(res)
})
.catch(err => console.log(err))
}
}
}
</script>
<style>
.custom-file {
padding: 1.2rem;
border-radius: .8rem;
display: inline-block;
border: 2px dashed #a0a0a0;
}
.custom-file input {
display: none;
}
</style>
After this, we must make an endpoint in Laravel API routes like this:
Route::post('/upload-image', 'UploadController#image');
In the last, Put this codes on upload
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UploadController extends Controller
{
public function image(Request $request)
{
$request->validate([
'files' => ['required', 'array'],
'files.*' => ['required', 'image','min:5','max:5000']
]);
$uploadedFiles = [];
foreach ($request->file('files') as $file) {
$fileName = bcrypt(microtime()) . "." . $file->getClientOriginalExtension();
$file->move('/uploads', $fileName);
array_push($uploadedFiles, "/uploads/{$fileName}");
}
return response($uploadedFiles);
}
}
Attention: Progress in localhost is so fast, then if you want to test it in local upload a file largest than 50 MB.

Related

Impossible to upload file with buefy upload

I'm creating a website and now I try to use my upload file system. I test it with postman and it works perfectly. But when I try to use with my website page, it not works.
Backend : I use Lumen
Frontend : I use Buefy
The upload function into UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function uploadImageIntoUser(Request $request, $id){
//try{
$user = User::findOrFail($id);
if ($user->id == Auth::id()) {
$url = json_decode($this->uploadImage($request, $id)->getContent(), true);
$newRequest = new Request();
$newRequest->replace(['picture' => $url['data']['image'] ]);
return $this->update($id, $newRequest);
}
return response()->json(['message' => 'You not have the right to do this'], 412);
/*}catch (\Exception $e){
return response()->json(['message' => 'User not found'], 404);
}*/
}
}
The upload function into my Controller.php
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Galerie;
use Illuminate\Support\Str;
class Controller extends BaseController
{
//Upload image
public function uploadImage(Request $request, $id)
{
try{
$this->validate($request, [
'folder' => array(
'required',
'alpha')
]);
$folder = $request->input('folder');
if(strcmp($folder, "user") !== 0 && strcmp($folder, "article") !== 0 && strcmp($folder, "galerie") !== 0){
return response()->json(['message' => 'Incorrect folder name : choose between user, article and galerie'], 409);
}
} catch (\Exception $e) {
return response()->json(['message' => 'Incorrect folder name : only in lowercase'], 409);
}
$response = null;
$user = (object) ['image' => ""];
if ($request->hasFile('image')) {
$original_filename = $request->file('image')->getClientOriginalName();
$original_filename_arr = explode('.', $original_filename);
$file_ext = end($original_filename_arr);
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
$image = time() . '.' . $file_ext;
if ($request->file('image')->move($destination_path, $image)) {
if ($folder == 'user') {
$user->image = '/upload/user/' . $image;
}else if($folder == 'article'){
$user->image = 'upload/article/' . $image;
}else if($folder == 'galerie'){
$user->image = 'upload/galerie/' . $image;
$galerie = new Galerie;
$galerie->id = Str::uuid();
$galerie->url = $user->image;
$galerie->save();
}
return $this->responseRequestSuccess($user);
} else {
return $this->responseRequestError('Cannot upload file');
}
} else {
return $this->responseRequestError('File not found');
}
}
protected function responseRequestSuccess($ret)
{
return response()->json(['status' => 'success', 'data' => $ret], 200)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
protected function responseRequestError($message = 'Bad request', $statusCode = 200)
{
return response()->json(['status' => 'error', 'error' => $message], $statusCode)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
Call my upload system from my profile page (called connexion.vue)
<template>
<section class="section">
<div class="container">
<p id="center-text" class="title">Informations Personnelles</p><br>
<b-notification v-if="error" type="is-warning">
{{ error }}
</b-notification>
<div class="columns">
<div class="column">
<img :src='baseURL + loggedInUser.picture'>
<b-field label="Modifier la photo de profil">
<b-field class="file is-secondary" :class="{'has-name': !!file2}">
<b-upload v-model="file2" class="file-label" rounded>
<span class="file-cta">
<b-icon class="file-icon" icon="upload"></b-icon>
<span class="file-label"><strong>Sélectionner un fichier à envoyer</strong></span>
</span>
<span class="file-name" v-if="file2">
{{ file2.name }}
</span>
</b-upload>
</b-field>
</b-field>
<b-button v-if="file2" type="is-secondary" #click="upload">Envoyer</b-button>
</div>
<div class="column">
<p class="title">{{ loggedInUser.pseudo }} <b-button #click="modifyPseudo" icon-right="pencil"/> </p><br v-if="!isModifyPseudo">
<form v-if="isModifyPseudo" method="post" #submit.prevent="sendModification">
<b-field label="Nouveau nom d'utilisateur" label-for="newPseudo">
<b-input id="newPseudo" v-model="newPseudo"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Adresse mail : {{ loggedInUser.email }} <b-button #click="modifyMail" icon-right="pencil"/> </p>
<form v-if="isModifyMail" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle adresse mail" label-for="newMail">
<b-input id="newMail" v-model="newMail" type="email"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Nationalité : {{ loggedInUser.nationality }} <b-button #click="modifyNation" icon-right="pencil"/> </p>
<form v-if="isModifyNation" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle nationalité" label-for="newNation">
<b-select expanded v-model="newNation" icon="earth">
<option
v-for="nation in nationalities"
:value="nation.code"
:key="nation.id">
{{ nation.name }}
</option>
</b-select>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
</div>
</div>
</div>
</section>
</template>
<script>
import { mapGetters } from 'vuex'
import countries from '#/assets/countries.json';
export default {
middleware: 'auth',
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser'])
},
data (){
return {
baseURL: 'http://localhost:8000/',
isModifyPseudo: false,
isModifyMail: false,
isModifyNation: false,
newPseudo: '',
newMail: '',
newNation: '',
nationalities: {},
error: '',
file2 : null,
}
},
methods: {
modifyPseudo() {
if(!this.isModifyPseudo){
this.newPseudo='';
}
this.isModifyPseudo = !this.isModifyPseudo;
},
modifyMail() {
if(!this.isModifyMail){
this.newMail='';
}
this.isModifyMail = !this.isModifyMail;
},
modifyNation() {
if(!this.isModifyNation){
this.newNation='';
}
this.isModifyNation = !this.isModifyNation;
},
async upload(){
try{
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
const newPicture = await this.$axios.post('users/' + this.loggedInUser.id + '/picture', formData, {
headers: {'Content-Type': 'multipart/form-data'}
});
console.log(newPicture);
const updatedUser = {...this.$auth.user}
updatedUser.picture = newPicture.data.picture;
this.$auth.setUser(updatedUser)
this.file2 = null;
}catch (error){
//this.error = error.response.data.message;
console.log(error.response);
}
},
async sendModification(){
try{
if(this.isModifyPseudo){
const newPseudo = await this.$axios.put('users/' + this.loggedInUser.id, {
pseudo: this.newPseudo
});
const updatedUser = {...this.$auth.user}
updatedUser.pseudo = newPseudo.data.pseudo;
this.$auth.setUser(updatedUser)
this.newPseudo = '';
this.isModifyPseudo = false;
}
if(this.isModifyMail){
const newMail = await this.$axios.put('users/' + this.loggedInUser.id, {
email: this.newMail
});
const updatedUser = {...this.$auth.user}
updatedUser.email = newMail.data.email;
this.$auth.setUser(updatedUser)
this.newMail = '';
this.isModifyMail = false;
}
if(this.isModifyNation){
const newNation = await this.$axios.put('users/' + this.loggedInUser.id, {
nationality: this.newNation
});
const updatedUser = {...this.$auth.user}
updatedUser.nationality = newNation.data.nationality;
this.$auth.setUser(updatedUser)
this.newNation = '';
this.isModifyNation = false;
}
}catch(error){
this.error = error.response.data.message;
}
}
},
async mounted() {
try {
this.nationalities = countries;
} catch (err) {
throw err;
}
},
}
</script>
<style scoped>
img {
border-radius: 50%;
object-fit: cover;
height: 10em;
width: 10em;
}
.container #center-text {
text-align: center;
}
.file-label strong{
color: white;
}
</style>
And when I click on the send button, because I don't catch the error, it sends the error 500.
EDIT :
So into my upload function into my profile page (called connexion.vue) :
I replace that
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
by this
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
formData.append('folder', 'user');
and into my Controller.php file I replace this :
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
by this
if($folder == 'user'){
$destination_path = storage_path('../public/upload/user/');
//$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = storage_path('../public/upload/article/');
//$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = storage_path('../public/upload/galerie/');
//$destination_path = './upload/galerie/';
}

Vue.js component conflict in laravel blade view

I have 2 of the same components in my laravel blade view, but they are conflicting.
What i'm trying to accomplish:
I've made a vue component that uploads a file to firebase and stores it in my database. In my blade view i have 2 places where i want to use this component. I configure the component with props so the component knows where to store the file.
What going wrong:
Every time i try to upload a file with the second component, i fire the function in the first component. How do i fix that the components can't conflict?
My laravel balde view:
component 1
<uploadfile
:key="comp100"
:user_data="{{ Auth::user()->toJson() }}"
store_path="/users/{{ Auth::user()->username }}/settings/email_backgrounds"
:store_route="'settings.project_email'"
:size="1000"
fillmode="cover"
></uploadfile>
component 2
<uploadfile
:key="comp200"
:user_data="{{ Auth::user()->toJson() }}"
store_path="/users/{{ Auth::user()->username }}/settings/email_backgrounds"
:store_route="'settings.project_email'"
:size="1000"
fillmode="cover"
></uploadfile>
The Vue component:
<template>
<div class="vue-wrapper">
<FlashMessage position="right top"></FlashMessage>
<div v-if="loading" class="lds-dual-ring"></div>
<div class="field">
<div class="control">
<label class="button main-button action-button m-t-20" for="uploadFiles"><span style="background-image: url('/images/icons/upload.svg')"></span>Kies bestand</label>
<input type="file" name="uploadFiles" id="uploadFiles" class="dropinput" #change="selectFile">
</div>
</div>
</div>
</template>
<script>
import { fb } from '../../firebase.js';
export default {
data() {
return {
fileObject: {
filePath: null,
url: null,
file: null,
resizedPath: null
},
loading: false
};
},
mounted() {
console.log(this.size)
console.log(this.fillmode)
},
props: [
'user_data',
'store_path',
'store_route',
'size',
'fillmode'
],
methods: {
selectFile(event)
{
var file = event.target.files[0];
this.fileObject.file = file
this.fileObject.filePath = this.store_path + '/' + file.name
this.fileObject.resizedPath = this.store_path + '/resized-' + file.name
if(file.type == 'image/png' || file.type == 'image/jpeg')
{
this.uploadFile(this.fileObject)
} else {
this.flashMessage.success({
title: 'Oeps!',
message: 'De afbeelding moet een png of een jpeg zijn!',
blockClass: 'success-message'
});
}
},
uploadFile(fileObject)
{
var vm = this
console.log(fileObject)
var storageRef = fb.storage().ref(fileObject.filePath)
var uploadTask = storageRef.put(fileObject.file)
this.loading = true
uploadTask.on('state_changed', function(snapshot){
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
},function(error) {
}, function() {
var resizeImage = fb.functions().httpsCallable('resizeImage')
resizeImage({filePath: fileObject.filePath, contentType: fileObject.file.type, watermark: false, size: vm.size, fit: vm.fillmode}).then(function(result){
var downloadRef = fb.storage().ref(fileObject.resizedPath);
downloadRef.getDownloadURL().then(function(url){
fileObject.url = url
vm.loading = false
vm.storeImage(fileObject)
}).catch(function(error){
console.log(error)
})
}).catch(function(error){
});
});
},
storeImage(file)
{
axios.post('/api/app/store_file', {
api_token: this.user_data.api_token,
user: this.user_data,
file: file,
storeRoute: this.store_route
}).then((res) => {
location.reload()
}).catch((e) => {
});
}
}
}
</script>
Does someone know how to fix this?

How to make Laravel pagination without refresh page

I'm making an online exam and I want to paginate the questions in different pages but the problem is that when I go to the next page the previous answers gone because the page refresh so how can I make the Laravel pagination withou refresh?
running Laravel 5.8
controller code:
$questions = $exam->questions()->paginate(1);
return view('exam.exam',compact('questions','exam'));
$questions = $exam->questions()->paginate(1);
return view('exam.exam',compact('questions','exam'));
view code
{!! $questions->render() !!}
This, sadly, can't be achieved without a little bit of asynchronous javascript - unless you want to preload all pages.
Your best bet is creating an API that returns paginated entries in a json format, then load it with javascript.
finally i did it using vue.js and axios
app.js code :
data: {
posts: {},
pagination: {
'current_page': 1
}
},
methods: {
fetchPosts() {
axios.get('posts?page=' + this.pagination.current_page)
.then(response => {
this.posts = response.data.data.data;
this.pagination = response.data.pagination;
})
.catch(error => {
console.log(error.response.data);
});
}
},
mounted() {
this.fetchPosts();
}
//and i added the pagination in a Component:
<template>
<nav class="pagination is-centered" role="navigation" aria-label="pagination">
<a class="pagination-previous" #click.prevent="changePage(1)" :disabled="pagination.current_page <= 1">First page</a>
<a class="pagination-previous" #click.prevent="changePage(pagination.current_page - 1)" :disabled="pagination.current_page <= 1">Previous</a>
<a class="pagination-next" #click.prevent="changePage(pagination.current_page + 1)" :disabled="pagination.current_page >= pagination.last_page">Next page</a>
<a class="pagination-next" #click.prevent="changePage(pagination.last_page)" :disabled="pagination.current_page >= pagination.last_page">Last page</a>
<ul class="pagination" style="display:block">
<li v-for="page in pages">
<a class="pagination-link" :class="isCurrentPage(page) ? 'is-current' : ''" #click.prevent="changePage(page)">{{ page }}</a>
</li>
</ul>
</nav>
</template>
<style>
.pagination {
margin-top: 40px;
}
</style>
<script>
export default {
props: ['pagination', 'offset'],
methods: {
isCurrentPage(page) {
return this.pagination.current_page === page;
},
changePage(page) {
if (page > this.pagination.last_page) {
page = this.pagination.last_page;
}
this.pagination.current_page = page;
this.$emit('paginate');
}
},
computed: {
pages() {
let pages = [];
let from = this.pagination.current_page - Math.floor(this.offset / 2);
if (from < 1) {
from = 1;
}
let to = from + this.offset - 1;
if (to > this.pagination.last_page) {
to = this.pagination.last_page;
}
while (from <= to) {
pages.push(from);
from++;
}
return pages;
}
}
}
</script>
<!-- begin snippet: js hide: false console: true babel: false -->
and make a route to get the pagination infromation into:
NOTE: this route will be used to return the pagination data into json only
Route::get('/posts', 'postContoller#pagination');
and in controller make a function to return the pagination information:
public function pagination(\App\post $post){
$posts = $post->paginate(1);
$response = [
'pagination' => [
'total' => $posts->total(),
'per_page' => $posts->perPage(),
'current_page' => $posts->currentPage(),
'last_page' => $posts->lastPage(),
'from' => $posts->firstItem(),
'to' => $posts->lastItem()
],
'data' => $posts
];
return response()->json($response);
}
now create a new view and paste this into
<div id="app">
<div v-for="post in posts">
<div class="font-weight-bold p-4"> #{{post.qname}}</div>
</div>
</div>
and create a route for it
Route::get('/', 'postController#index');

How to upload photo using Laravel RestApi and vuejs

I'm working on a RestFulApi using Laravel and Vuejs, now want upload a photo using RestfulApi and vuejs. Here comes my sample code:
<div class="form-group form-group-default float-left required">
<label for="photo">Photo</label>
<input class="file-input" type="file" ref="photo" name="photo" v-
on:change="addFile($event)">
</div>
data(){
return{
films_info:
{
photo: null,
}
}
},
methods: {
addFile: function(e){
let that = this;
that.films_info.photo = this.$refs.photo.files[0];
},
saveFilms: function(){
let that = this;
axios.post('/api/films/save_films',that.films_info)
.then(function (response) {
location.reload(true);
})
.catch(function (error) {
that.errors = error.response.data.errors;
console.log("Error Here: "+error.response.data);
});
}
}
protected function saveFilms(Films $request)
{
if ( $request->photo ) {
$extension = $filmsObj->photo->getClientOriginalExtension();
$request->photo = 'films_'.\Carbon\Carbon::now().'.'.$extension; // renaming image
$request->photo->move($dir_path, $request->photo);
}
}
Here in this code I get error in getClientOriginalExtension() method call. It says:
getClientOriginalExtension() method called on string.
Finally I managed to solved the photo upload issue using VueJS and Laravel Api call.
<div class="form-group form-group-default float-left required">
<label for="file">File</label>
<input class="file-input" type="file" ref="file" name="file" v-
on:change="addFile($event)">
</div>
data(){
return{
films_info:
{
file: null,
}
}
},
methods: {
addFile(e){
this.films_info.file = this.$refs.file.files[0];
},
saveFilms(){
let formData = new FormData();
formData.append('file', this.films_info.file);
axios.post('/api/films/save_films',formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
location.reload(true);
})
.catch(error => {
that.errors = error.response.data.errors;
console.log("Error Here: "+error.response.data);
});
}
}
$dir_path = 'uploads/films/images';
$dir_path_resize = 'uploads/films/images/45x45';
if( $request ){
$filmsObj = new Film();
if (!File::exists($dir_path))
{
File::makeDirectory($dir_path, 0775, true);
}
if (!File::exists($dir_path_resize))
{
File::makeDirectory($dir_path_resize, 0775, true);
}
if ( $request->file ) {
$file = $request->file;
$extension = $file->getClientOriginalExtension(); // getting image extension
$file_name = 'films_'.\Carbon\Carbon::now().'.'.$extension; // renaming image
$file->move($dir_path, $file_name); // uploading file to given path
// Start : Image Resize
$image = Image::make(public_path($dir_path.'/'.$file_name));
// resize the image to a height of 45 and constrain aspect ratio (auto width)
$image->resize(null, 45, function ($constraint) {
$constraint->aspectRatio();
});
$image->save(public_path($dir_path_resize.'/'.$file_name));
// End : Image Resize
}

submit form from <div> html value in codeigneter

i have problem using form in codeigneter when to submit value from div html,
example view
<label for="title">Title:</label>
<input type="text" class="form_field" id="title" name="title" size="30" value="<?php echo set_value('title', isset($default['title']) ? $default['title'] : ''); ?>" />
<div class="form_field" name="contentbox" id="contentbox" contenteditable="true">
<?php echo set_value('contentbox', isset($default['contentbox']) ? $default['contentbox'] : ''); ?></div>
in div id="contentbox" is set contenteditable="true", and i will get dinamic value,
controller
....
$data = array( 'title' => $this->input->post('title'),
'content' => $this->input->post('contentbox'));
$this->my_model->add($data);
....
but in controller i can't get value div id="contentbox" , i have problem input to database,when i'm typing "sometext" in div id="contentbox" value always "0"
You can use the jquery cookie plugin to grab CI csrf token and include it before this function
jQuery
(function($){
var do_ajax = function(data, scope){
// depending on your version of CI csrf token name will differ
// newer versions of CI use the name in your application/config file
data = {content : data, csrf_token : $.cookie('csrf_token')}
$.ajax({
url : BASE_PATH + 'some_class/some_method',
data: data,
context : scope,
type : 'POST',
dataType : 'json',
success : function(callback){
//check the status first!
var $this = $(this);
$this.find(".msg").fadeIn();
$this.find("#contentbox").html(data);
}
});
}
var contents = {
init: function(){
if($("#editme"))
this.contentEditable();
},
contentEditable : function(){
var scope = $("#editme"),
eicon = $(".icon-editable").hide(),
emessage = $(".msg").hide(),
econtent = $("#contentbox");
econtent.hover(function(){
eicon.show();
}, function(){
eicon.hide();
});
econtent.blur(function(){
do_ajax($(this).html(), scope);
});
}
}
$(function(){
contents.init();
});
})(jQuery);
HTML
<div id="editme" class="editme">
<span class="icon-editable">✎</span>
<span class="msg">Content updated!</span>
<h4>Some relevant title</h4>
<div id="contentbox" class="contentbox" contenteditable="true">
This is editable...
</div>
</div>
CSS
div.editme{
position:relative;
background:#ffffff;
padding:30px 8px 8px 8px;
}
span.icon-editable, span.msg{
position:absolute;
top:0;
}
span.icon-editable{
left:0;
border:1px solid #d1d1d1;
border-top:0;
border-left:0;
font-size:1em;
line-height:1.2em;
}
span.msg{
right:0;
font-size:0.8em;
line-height:1.2em;
color:#fafafa;
background:green;
padding:3px;
}
PHP
class some_class extends Controller{
public function some_method(){
if($this->input->is_ajax_request())
{
$data = array(
'content' => $this->input->post('content')
);
if($this->my_model->add($data))
{
$responce = array(
'status' => 'ok'
);
}
else
{
$responce = array(
'status' => 'notok'
);
}
echo json_encode($responce);
}
else
{
show_404();
}
}
}
Test version without ajax request
CLICK HERE

Resources