Within my straightforward form, users are required to input only text into a textarea. Upon clicking the submit button, a call is made using Vue and AJAX in JavaScript to insert the entered text into the database.
The issue arises when I attempt to clear the textarea right after submission, as the text persists even after being saved in the database. To address this, I am awaiting the .done (success) callback function in vue.js and ajax to proceed with clearing the form.
Are there any alternative ideas to automatically clear the textarea once the text has been successfully saved in the database?
Below is the blade code snippet for the form:
<div class="row" id="timeline">
<div class="col-md-4">
<form action="#" v-on:submit="postStatus">
<div class="form-group">
<textarea class="form-control" rows="5" maxlength="140" autofocus placeholder="What are you upto?" required v-model="post" id="textareapost"></textarea>
</div>
<input type="submit" value="Post" class="form-control btn btn-info">
{{ csrf_field() }}
</form>
</div>
<div class="col-md-8">
Timeline
</div>
</div>
Explained below is the controller:
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use App\Http\Requests;
class PostController extends Controller
{
public function create(Request $request, Post $post)
{
// validation:
$this->validate($request,[
'body' => 'required|max:140',
]);
// creating the post from the user:
$createdPost = $request->user()->posts()->create([
'body' => $request->body,
]);
// Responding with the created post:
return response()->json($post->with('user')->find($createdPost->id));
}
}
Furthermore, here is the current state of the javascript code:
var csrf_token = $('meta[name="csrf-token"]').attr('content');
new Vue({
el : '#timeline',
data : {
post : '',
token : csrf_token,
},
methods : {
postStatus : function (e) {
e.preventDefault();
var request = $.ajax({
url : '/posts',
method : "POST",
dataType : 'json',
data : {
'body' : this.post,
'_token': this.token,
}
}).done(function (msg) {
console.log('Data saved: '+msg);
this.post = '';
}.bind(this));
request.done(function( msg ) {
console.log('Data saved: '+msg+'. Outside ...');
});
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
}
},
});
Upon saving the text, the ".done" part is not triggered, and instead, the console displays a message stating:
Request failed: parsererror
Additionally, the controller's response includes <?php
. Could this be due to Chrome's inspect elements tool? Any thoughts on what might be causing this issue?