Laravel5.1 Building a simple community (12)--ajax change avatar

Source: Internet
Author: User

This article records how to use Ajax for avatar replacement, using Ajax to introduce a jquery plug-in jquery form, introduced in app.blade.php:

    <Linkrel= "stylesheet"href= "/css/bootstrap.css">{{--introduce fontawesome--}}<Linkrel= "stylesheet"href= "/css/font-awesome.css">    <Linkrel= "stylesheet"href= "/css/style.css">{{--introduce Jqueryform plugin--}}<Scriptsrc= "/js/jquery-2.1.4.min.js"></Script>    <Scriptsrc= "/js/bootstrap.min.js"></Script>    <Scriptsrc= "Https://cdn.bootcss.com/jquery.form/4.2.1/jquery.form.js"></Script>

Modify the front-end page of avatar.blade.php after the plugin is introduced:

<Divclass= "Container">        <Divclass= "Row">            <Divclass= "Col-md-6 col-md-offset-3">                <Divclass= "Text-center">                    <DivID= "Validation-errors"></Div>                    <imgsrc= "{{Auth::user ()->avatar}}"width= "+"class= "Img-circle"ID= "User-avatar"alt="">                    {!!                    Form::open ([' method ' = ' post ', ' url ' = ' User/avatar ', ' id ' = ' avatar ', ' Files ' =>true])! <Divclass= "Text-center">                        <Buttontype= "button"class= "btn btn-success Avatar-button"ID= "Upload-avatar">Upload a new avatar</Button>                    </Div>                    {!!                    Form::file (' Avatar ', [' class ' = ' Avatar ', ' id ' = ' image '])! <!--Submit -                    {!!                    Form::close ()!!} <Divclass= "Span5">                        <DivID= "Output"style= "Display:none">                        </Div>                    </Div>                    {{--{!! Form::open ([' method ' = ' post ', ' url ' = ' User/avatar ', ' Files ' =>true])! --}} {{--avatar upload--}} {{--{!! Form::file (' Avatar ')!} --}}                    {{--<!--Submit ---}} {{--{!! Form::submit (' Tijao ', [' class ' = ' btn ' btn-primary form-control '])! --}}                    {{--{!! Form::close ()!!} --}}                </Div>            </Div>@if ($errors->any ())<ulclass= "List-group">@foreach ($errors->all () as $error)<Liclass= "List-group-item List-group-item-danger">{{$error}}</Li>@endforeach</ul>@endif</Div>    </Div>

Then write the JS code:

<Script>$ (document). Ready (function() {            varOptions={beforesubmit:showrequest, success:showresponse, DataType: 'JSON'            }; $('#image'). On (' Change', function(){                $('#upload-avatar'). HTML ('uploading ...'); $('#avatar'). Ajaxform (Options). Submit ();        });        }); functionShowrequest () {$ ("#validation-errors"). Hide (). empty (); $("#output"). CSS ('Display','None'); return true; }        functionShowresponse (response) {if(response.success== false)            {                varresponseerrors=response.errors; $.each (Responseerrors,function(Index, value) {if(Value.length!= 0)                    {                        $("#validation-errors"). Append ('<div class= "alert Alert-error" ><strong>'+value+'</strong><div>');                }                }); $("#validation-errors"). Show (); } Else {                $('#user-avatar'). attr ('src', Response.avatar); $('#upload-avatar'). HTML ('change a new avatar'); }        }    </Script>

The front-end work ends here, and we deal with the business logic behind the scenes:

    Public Function Changeavatar (Request $request) {//declares path name $destinationPath = ' uploads/';        Take the picture $file = $request->file (' Avatar ');        $input = Array (' image ' = = $file);        $rules = Array (' image ' = ' image ');        $validator = \validator::make ($input, $rules); if ($validator->fails ()) {return \response::json ([' success ' = = False, '        Errors ' = ' $validator->getmessagebag ()->toarray ()]); }//Get the name of the picture in order to ensure that we add UserID and time $file _name = \auth::user ()->id. ‘_‘ . Time ().        $file->getclientoriginalname ();        Execute the Move method $file->move ($destinationPath, $file _name);        Crop a picture to generate a thumbnail image of 200x200 image::make ($destinationPath. $file _name)->fit (+)->save ();        Save to User $user = User::findorfail (\auth::user ()->id); $user->avatar = '/'. $destinationPath.        $file _name; $User->save ();        return \response::json ([' Success ' = True, ' avatar ' = Asset ($destinationPath. $file _name),    ]); }

Note that the JSON file is returned here

Laravel5.1 Building a simple community (12)--ajax change avatar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.