Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have this simple form where the user should only type text inside a textarea. When the user clicks on the submit button, inside the javascript, I make a call with vue and ajax to insert that text into the database.

My problem is that, right after the user clicks on submit, I want the textarea to be cleared, but after the text has been saved into the database, the text is still there. It persists. Since I am using vue.js and ajax, there is this .done (success) callback function I am waiting in order to proceed to clear the form.

Or is there any other idea to clear the textarea, if the text was saved into the database?

Here is my blade code of the form:

<div class="row" id="timeline">
    <div class="col-md-4">
        <form action="#" v-on:submit="postStatus">{{-- Name of the method in Vue.js --}}
            <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>

This is my 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)
    {
        //$request->body;
        //Remember, all we really need is the body. Because if create this post through
        //the User model, it'll automatically assign us a user_id

        //validation:
        $this->validate($request,[
            'body'  =>  'required|max:140',
        ]);
        //die('Posted in the controller!: '.$request->body); //$request->get('body');

        //creating the post from the user, from the post that belongs to the user:
        $createdPost = $request->user()->posts()->create([
            'body'  =>  $request->body,
        ]);

        //Now respond with the post that has been created:
        return response()->json($post->with('user')->find($createdPost->id));
    }
}

And the javascript code so far:

var csrf_token = $('meta[name="csrf-token"]').attr('content');
    /*Event handling within vue*/
    //when we actually submit the form, we want to catch the action
    new Vue({
        el      : '#timeline',
        data    :   {
            post    : '',
            token   : csrf_token,
        },
        methods : {
            postStatus : function (e) {
                e.preventDefault();
                console.log('Posted: '+this.post+ '. Token: '+this.token);
                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 = '';/*Attempting to clear the form*/
                }.bind(this));/*http://stackoverflow.com/a/26479602/1883256*/

                request.done(function( msg ) {
                    console.log('Data saved: '+msg+'. Outside ...');
                    //$( "#log" ).html( msg );
                });

                request.fail(function( jqXHR, textStatus ) {
                    console.log( "Request failed: " + textStatus );
                });
            }
        },
    });

After the the text has been saved, I never get the console.log text of the .done part, but I get the .fail message which says:

Request failed: parsererror

And the response from the controller is right the following:

<?php{"id":29,"user_id":1,"body":"Sunday evening post","created_at":"2016-10-09 23:03:11","updated_at":"2016-10-09 23:03:11","user":{"id":1,"firstname":null,"lastname":null,"username":"pathros","email":"[email protected]","created_at":"2016-10-08 05:33:06","updated_at":"2016-10-08 18:57:19"}}

I noticed that the response adds <?php. Is it maybe the Chrome's inspect elements tool? What am I missing? (Note: I am using jQuery 3.1.1 and Laravel 5.3)

share|improve this question
up vote 2 down vote accepted

Your issue has to do with the dataType option on the AJAX. You currently have dataType: 'json', which means the request is successful when the server returns a JSON.

If you are returning something like return 'ok'; that AJAX will fail.

Make sure you're returning something like:

return Response::json(['ok' => 'true']);
share|improve this answer
    
Oh no. I missed to show the controller's code. I have updated my question with it. But in this case, I not only want to return an ok, but the current post just inserted. I have tried return response()->json(['ok' => 'true',$post->with('user')->find($createdPost->id)]); The response is now <?php{"ok":"true","0":{"id":31,"user_id":1,"body":"Hello, ","created_at":"2016-10-09 23:25:18","updated_at":"2016-10-09 23:25:18", ... But I still get the same error. Then how would I do that? – Pathros Oct 9 '16 at 23:35
    
@Pathros Your code seems ok. The issue with php comes from somewhere else. Check this post that seems to describe the same issue. – milz Oct 9 '16 at 23:55
1  
Thanks a lot! That link helped me a lot. My problem was in the RouteServiceProvider.php file, where I was calling an empty file with only a <?php. I was planning to code later on something there and the only content was that <?php tag. So I commented that part for now. – Pathros Oct 10 '16 at 2:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.