简体   繁体   中英

laravel ajax response return html elements

I have used made use of ajax before, but have not encounted this sort of problem,

here is my form

<form action="" method="post" enctype="multipart/form-data" class="m-form m-form--fit m-form--label-align-right" id="basicinfoform">
                                                {{ csrf_field() }}
                                                <input type="hidden" value="{{ $studentinfo->id }}" name="studentformid">
                                                <div class="form-group m-form__group row">
                                                            <center><label for="sphoto">
                                                                        <?php 
                                                                            $photo = "student.png";
                                                                            if($studentinfo->photo !== ""){
                                                                                $photo = $studentinfo->id.'.'.$studentinfo->photo;
                                                                            }
                                                                        ?>
                                                            <img style="width:180px;height:180px;cursor:pointer;border:2px solid lightblue" id="schoollogo" src="<?php echo asset('images/passports/'.$photo) ?>"  alt="">
                                                        </label>
                                                        <input onchange="getPhoto.call(this);showsavebuttonforviewstudentedit();" type="file" class="form-control m-input newb" style="display:none" value="" id="sphoto" name="sphoto" aria-describedby="emailHelp" >
                                                        <br>
                                                            <span class="m-form__help text-accent">
                                                                <b>Click the image to change it</b>
                                                            </span>
                                                        </center>
                                                        <input type="hidden" value="" id="studentid" name="studentid">

                                                </div>

                                                <div class="form-group m-form__group row">
                                                    <div class="col-md-4">
                                                    <label for="exampleInputPassword1">
                                                        Admission No:
                                                    </label>
                                                    <input type="text" disabled="disabled" class="form-control m-input m-input--square"  value="{{ $studentinfo->admissionid }}">
                                                    </div>
                                                    <div class="col-md-4">
                                                    <label for="exampleInputEmail1">
                                                        Full name
                                                    </label>
                                                    <input type="text" name="fullname" class="form-control m-input m-input--square newb" value="{{ $studentinfo->fullname }}" onchange="showsavebuttonforviewstudentedit()">

                                                    </div>

                                                    <div class="col-md-4">
                                                    <label for="exampleInputPassword1">
                                                        Gender
                                                    </label>
                                                    <!-- <input type="password" class="form-control m-input m-input--square" id="exampleInputPassword1" placeholder="Password"> -->
                                                        <select name="gender" id="gender" class="form-control m-input m-input--square newb" onchange="showsavebuttonforviewstudentedit()">
                                                            <option value="1" {{($studentinfo->gender == "1") ? "selected" : ""}}>Male</option>
                                                            <option value="2" {{($studentinfo->gender == "2") ? "selected" : ""}}>Female</option>
                                                        </select>
                                                    </div>                                                        
                                                </div>

                                                <div class="form-group m-form__group row">
                                                    <div class="col-md-4">
                                                    <label for="exampleInputEmail1">
                                                        Class
                                                    </label>
                                                    <!-- <input type="text" class="form-control m-input m-input--square" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> -->
                                                    <select name="class" id="theclass" class="form-control m-input m-input--square newb" onchange="showsavebuttonforviewstudentedit();getArms();">
                                                        @foreach($allclasses as $list)
                                                            <option value="{{$list->id}}" {{ ($studentinfo->class == $list->id) ? "selected" : ""}}>{{ $list->classname }}</option>
                                                        @endforeach
                                                    </select>
                                                    </div>

                                                    <div class="col-md-4">
                                                    <label for="exampleInputPassword1">
                                                        Arm
                                                    </label>
                                                    <select name="arm" id="thearm" class="form-control m-input m-input--square newb" onchange="showsavebuttonforviewstudentedit()">
                                                        @foreach($allarms as $list)
                                                            <option value="{{$list->id}}" {{ ($studentinfo->arm_id == $list->id) ? "selected" : ""}}>{{ $list->arm }}</option>
                                                        @endforeach
                                                    </select>
                                                    </div>

                                                    <div class="col-md-4">
                                                    <label for="exampleInputPassword1">
                                                        House:
                                                    </label>
                                                    <select name="house" id="house" class="form-control m-input m-input--square newb" onchange="showsavebuttonforviewstudentedit()">
                                                        @foreach($allhouses as $list)
                                                            <option value="{{$list->id}}" {{ ($studentinfo->house == $list->id) ? "selected" : ""}}>{{ $list->house }}</option>
                                                        @endforeach
                                                    </select>
                                                    </div>
                                                </div>

                                                <div class="form-group m-form__group row">
                                                    <div class="col-md-4">
                                                    <label for="exampleInputEmail1">
                                                        Date of Birth
                                                    </label>
                                                    <input type="text" class="form-control m-input m-input--square newb" name=""dob id="dob10" value="{{ $studentinfo->dob}}" onchange="showsavebuttonforviewstudentedit()">
                                                    </div>

                                                    <div class="col-md-4">
                                                    <label for="exampleInputPassword1">
                                                        State
                                                    </label>
                                                    <select name="state" id="stateid" class="form-control m-input m-input--square newb" onchange="getLGA();showsavebuttonforviewstudentedit()">
                                                        @foreach($allstates as $list)
                                                            <option value="{{$list->StateID}}" {{ ($studentinfo->s_of_o == $list->StateID) ? "selected" : ""}}>{{ $list->State }}</option>
                                                        @endforeach
                                                    </select>
                                                    </div>

                                                    <div class="col-md-4">
                                                    <label for="exampleInputPassword1">
                                                        Local Govt.
                                                    </label>
                                                    <select name="lga" id="lgafield" class="form-control m-input m-input--square newb" onchange="showsavebuttonforviewstudentedit()">
                                                        @foreach($alllga as $list)
                                                            <option value="{{$list->lgaId}}" {{ ($studentinfo->lga == $list->lgaId) ? "selected" : ""}}>{{ $list->lga }}</option>
                                                        @endforeach
                                                    </select>
                                                    </div>
                                                </div>


                                                <div class="form-group m-form__group row">
                                                    <div class="col-md-4">
                                                    <!-- <input type="text" class="form-control m-input m-input--square" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> -->
                                                    <button type="submit" id="basicbtn" onclick="return submitStudentDetailInViewStudentPage();" disabled="disabled" class="btn btn-brand">&nbsp&nbsp Save <i class="fa fa-spinner fa-spin" style="display:none"></i>&nbsp&nbsp</button>
                                                    </div>

                                                </div>
                                            </div>

                                            </form>

onclick of the save button, ajax is firedup, this is the ajax

form = document.getElementById('basicinfoform');

formdata = new FormData(form);

console.log(formdata)
$.ajax({
    url : "/ajax/post/studentinfo",
    data: formdata,
    method: 'post',
    processData: false,
    contentType: false,
    success : function (res){
        if(res){
            console.log(res)

        }
    }
   });
return false;

here is my controller

public function viewStudent(Request $request, $studentid = null)
{


    if(!Auth::check()){
        return redirect('/');
    }

    if($request){
          echo 'yes';
    }
    if(!is_null($studentid)){

        $data['allstates']  = DB::table('tblstates')->get();
        $data['alllga'] = DB::table('tbl_lga')->get();
        $data['studentinfo'] = DB::table('tblstudents')
                                ->where('id', $studentid)
                                ->first();

        return view('Students.viewstudents', $data);
    }
    return redirect('/all/students');
}

in this controller, i have set a condition to check if request has been made so to make edit, so I simply echoed 'Yes' for the sake of testing and this question. Meaning my ajax response is simply suppose to be 'Yes' string literal, but below is what I get in the as response

 <!DOCTYPE html>

<!-- Required meta tags -->

--begin::Base Styles -->  

    <!--begin::Page Vendors -->

    <link href="http://127.0.0.1:8000/assets/vendors/custom/fullcalendar/fullcalendar.bundle.css" rel="stylesheet" type="text/css" />

    <!--end::Page Vendors -->

    <link href="http://127.0.0.1:8000/assets/vendors/base/vendors.bundle.css" rel="stylesheet" type="text/css" />

    <link href="http://127.0.0.1:8000/assets/demo/default/base/style.bundle.css" rel="stylesheet" type="text/css" />

<!-- <link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> -->

    <!--end::Base Styles -->

    <link rel="shortcut icon" href="http://127.0.0.1:8000/assets/demo/default/media/img/logo/favicon.ico" />

<link rel="stylesheet" type="text/css" href="http://127.0.0.1:8000/DataTables/datatables.min.css"/>

    <link rel="stylesheet" type="text/css" href="http://127.0.0.1:8000/css/bootstrap.css"/>

what happens in your case is, it echos yes , but it keeps executing the rest of the code, and it returns a view file. So you get the html response.

if you need to see the echoed text simply add exit() after the echo statement and you will get the 'Yes' response

if($request){
   echo 'yes';
   exit();
}

I think it should look something like this

public function viewStudent(Request $request, $studentid = null)
{
    if(!Auth::check())
    {
        return redirect('/');
    }

    if($request)
    {
          // echo outputs to the server, but you should really return something
          // for the requester, thus we will return "YES" to the response
          // and since we are returning, it will return and no further executions will made.
          return 'yes';
    }

    if(!is_null($studentid))
    {

        $data['allstates']  = DB::table('tblstates')->get();
        $data['alllga'] = DB::table('tbl_lga')->get();
        $data['studentinfo'] = DB::table('tblstudents')
                                ->where('id', $studentid)
                                ->first();

        return view('Students.viewstudents', $data);
    }

    return redirect('/all/students');
}

You could use return json for returning data to ajax request like

return response()->json(['success' => 'yes']);

Do not use echo for return value to ajax response

Do some functionality as your requirement in ajax call. I'm filtering table data using the search input.

                $.ajax({
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                type    :"POST",
                url     :"{{route('filter')}}",
                dataType:"JSON",
                data    :{keyword:keyword,'_token':'{!!csrf_token()!!}'},
                success :function(response)
                {
                    if (response.status=='success') 
                    {
                        $('#table_body').html(response.data); 
                    } 
                }
            });

And now on my controller after fetching tables data using query i send the data on another blade view that i want to return in responce and my code is something like this:-

public function filter(Request $r)
{ 
    $keyword=$r->keyword;
    $orders=DB::table('orders')->where('print_orders.address','like','%' .$keyword. '%')->paginate(50);

    $html=view('orders',compact('orders'))->render();

    if ($this->check_count($orders)>0) 
    {
        return response::json(['status'=>'success','data'=>$html]);
    } 
    else 
    {
        return response::json(['status'=>'fail','Nothing Found!!']);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM