首页 文章

AJAX发布不向控制器发送数据

提问于
浏览
0

也许这是一个非常常见的主题,但我找不到任何解决方案!,当我尝试console.log时,我尝试向控制器发送ajax帖子,数据存在,但数据没有发送到我的控制器,这是截屏我的console.log,我需要将一些数据从jquery ajax发送到laravel控制器,这样我有一个带有csrf令牌的元数据,当我使用ajax将发送请求发送到URL时,它只是发送令牌!但我没有给它发送的数据 .

console log

This is my javaScript code:-

function doComment(lesson_id, parent_id) {
    var body = $('#textbody'+parent_id).val();
    var file_data = $('#image').prop("files")[0]; 
    if (body == '') {
      alert('Harap Isi Komentar !')
    }else {
      var postData =
                  {
                      "_token":$('meta[name="csrf-token"]').attr('content'),
                      "lesson_id": lesson_id,
                      "parent_id": parent_id,
                      "image" : image,
                      "body": body
                  }
      $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      $.ajax({
          type    :'POST',
          url     :'{{ url("lessons/coments/doComment") }}',
          dataType: 'json',
          cache: false,
          contentType: false,
          processData: false,
          data    : postData,
          beforeSend: function(){
            console.log(postData);
            // Show image container
            swal({
                title: "Sedang mengirim Komentar",
                text: "Mohon Tunggu sebentar",
                imageUrl: "{{ asset('template/web/img/loading.gif') }}",
                showConfirmButton: false,
                allowOutsideClick: false
              });
              {{--  $("#loader").show();  --}}
          },
          success:function(data){
            if (data.success == false) {
               window.location.href = '{{ url("member/signin") }}';
            }else if (data.success == true) {
              $('#textbody'+parent_id).val('');
              swal({
                title: "Komentar anda sudah terkirim!",
                showConfirmButton: true,
                timer: 3000
              });

              getComments();
            }
          }
      });
    }
  }

这是我的控制者

public function doComment()
    {
        $response = array();
        if (empty(Auth::guard('members')->user()->id)) {
            $response['success'] = false;
        } else {

            $now = new DateTime();
            $uid = Auth::guard('members')->user()->id;
            $body = Input::get('body');
            $lesson_id = Input::get('lesson_id');
            $member = DB::table('members')->where('id', $uid)->first();
            $lessons = DB::table('lessons')->where('id', $lesson_id)->first();
            $parent_id = Input::get('parent_id');
            $contri = Lesson::where('id',$lesson_id)
                      ->select('contributor_id')
                      ->first();
            // dd($lesson_id);
            $image = Input::file('image');
            // dd($image);

            $lessonsDestinationPath= 'assets/source/komentar';

            if(!empty($image)){
                $imagename    = $image->getClientOriginalExtension();
                $image->move($lessonsDestinationPath, $imagename);
            }else{
                $imagename    = '';
            }
            if($imagename ==''){
                $url_image= $imagename;
            }else{
                $urls=url('');
                $url_image= $urls.'/assets/source/komentar/'.$imagename;
            }

            $store = DB::table('comments')->insertGetId([
                'lesson_id' => $lesson_id,
                'member_id' => $uid,
                'body' => $body,
                'parent_id' => $parent_id,
                'status' => 0,
                'desc'   => 0,
                'images' => $url_image,
                'contributor_id' => str_replace('}','',str_replace('{"contributor_id":', '',$contri)),
                'created_at' => $now,
                'updated_at' => $now,
            ]);

            $getmembercomment = DB::table('comments')
            ->Join('members','members.id','=','comments.member_id')
            ->where('comments.lesson_id',$lesson_id)
            ->where('comments.parent_id',0)
            ->where('comments.status',1)
            ->select('comments.*','members.username as username')
            ->first();

            $getemailchild = DB::table('comments')
                             ->Join('comments as B', 'comments.id', 'B.parent_id')
                             ->Where('B.parent_id', $parent_id)
                             ->where('comments.member_id', '<>', 'B.member_id')
                             ->select('comments.member_id as tanya', 'B.member_id as jawab')->distinct()
                             ->get();


            // dd($getemailchild);
            if($parent_id != 0){
                foreach ($getemailchild as $mails) {
                //  Check type
                if (is_array($mails)){
                    //  Scan through inner loop
                    foreach ($mails as $value) {
                        $member = Member::Find($value);
                        $lesson = Lesson::Find($lesson_id);
                        $contrib = Contributor::find($lessons->contributor_id);
                        $member->notify(new UserReplyNotification($member, $lesson, $contrib));
                    }
                }
            }

            }
            if ($store) {

                // dd($store);
                    DB::table('contributor_notif')->insert([
                        'contributor_id' => $lessons->contributor_id,
                        'category' => 'Komentar',
                        'title' => 'Anda mendapat pertanyaan dari ' . $member->username,
                        'notif' => 'Anda mendapatkan pertanyaan dari ' . $member->username . ' pada ' . $lessons->title,
                        'status' => 0,
                        'created_at' => $now,
                    ]);
                    $member = Member::Find($uid);
                    $comment = Comment::Find($store);
                    $lesson = Lesson::find($lessons->id);
                    $contrib = Contributor::find($lessons->contributor_id);
                    $contrib->notify(new UserCommentNotification($member, $comment, $contrib, $lesson));


                    $response['success'] = true;
            }
        }
        echo json_encode($response);
    }

这是我的路线:

Route::post('lessons/coments/doComment','Web\LessonsController@doComment');

This is my error:-
error when send data

1 回答

  • 0

    我不确定laravel如何处理发布数据(无论是处理还是普通的$ _POST和php://输入) . 您可以尝试从Javascript Ajax代码中删除 datatype :JSON . 删除 cache: false, contentType: false, processData: false, ;这些参数是可选的,您应该让它使用默认值,除非您有特殊原因需要json数据类型 . 您可以再次尝试使用 $received = file_get_contents("php://input"); 然后 print_r($received) 在控制器上接收数据 . 看看它是否 grab 了JSON数据

相关问题