2016-09-19 8 views
0

Laravel-5.2에서 Ajax를 사용하여 데이터베이스에 사용자 입력을 저장하려고합니다.Ajax 폼 데이터가 데이터베이스에 저장되지 않았습니다.

이 내 내보기에서 route.php

Route::get('xxxxx/{task_id?}',function($task_id){ 
$task = App\XXXXX::find($task_id); 

return response()->json($task); 
}); 

    Route::put('xxxxx/{task_id?}',function(Request $request,$task_id){ 
     $task = App\XXXXX::find($task_id); 

     $task->Name = $request->Name;// 
     $task->Email = $request->Email; 
     $task->Telephone = $request->Telephone; 

     $task->save(); 

     return response()->json($task); 
    }); 

, 저장 버튼으로 사용됩니다.

<div class="modal-footer"> 
    <button type="button" class="btn btn-primary" id="btn-save" value="update">Save changes</button> 
     <input type="hidden" id="task_id" name="task_id" value="0"> 
</div> 

내 js 파일은 this tutorial.을 사용하여 생성되었습니다.
팝업이 나타나는데 Save 버튼이 작동하지 않습니다.
무엇이 잘못 되었나요? 나는 Ajax를 처음 접했습니다.
미리 감사드립니다.

+0

더블 응용 프로그램 루트 폴더 이름을 확인합니다. var url = "..."을 변경하십시오. 귀하의 폴더 이름 --->에서 댓글 – codemax

+1

@Sachit 브라우저의 개발자 도구에서 네트워크 탭으로 이동하여 XHR 유형을 확인하십시오. 거기에서 아약스 요청에 대한 서버의 응답을 볼 수 있습니다. ('click', '#btn-save', function (')')을 클릭하면 당신의 laravel 앱에서 발생한 에러가 표시됩니다. – jaysingkar

+0

$ ("# btn-save") {' –

답변

1

이 route.php입니다

경로 :: 일치 ([ '포스트'를 '얻을'] '내/데이터 저장', 'MyController에 @ 위해 SaveData');

저장이 당신의 컨트롤러 파일입니다

변경 :

이 HTML입니다 MyController.php

공공 기능을 위해 SaveData (요청 $ 요청) { $ 입력 = $ request-> all();

try{ 

     // You can now use the Subscribe model without its namespace 
     // as you referenced it by its namespace in a use statement. 
     $subscribe = new Subscribe(); 

     // If you want to use a class that is not referenced in a use 
     // statement then you must reference it by its full namespace. 
     $otherModel = new \App\Models\Other\Namespace\OtherModel(); 

     $otherModel = $input['Name']; 
     $otherModel = $input['Email']; 
     $otherModel = $input['Telephone']; 

     // save 
     $otherModel->save();   

    } 
    catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) 
    { 
     \Log::error($e->getMessage(), $context);    
    } 
    catch (Exception $e){ 
     \Log::error($e->getMessage(), $context); 
    } 

    return response()->json(['status'=>'success', 'message'=>'Completed successfully']); 
} 

이것은 당신의 JS 파일입니다 저장

기능 save.js() { GetData의 = { 이름 : GET eliment에서 "값", //
이메일 : "value", // get eliment에서 전화 : "value"// 엘림 얻으십시오 }};

$.ajax({ 
    type: 'post',   // POST Request 
    url: 'localhost/my/save-data', // localhost/my/save-data   // Url of the Route (in this case user/save not only save) 
    data: getData,   // Serialized Data 

    beforeSend: function (xhr) { 
     // Function needed from Laravel because of the CSRF Middleware 
     var token = $('meta[name="csrf_token"]').attr('content'); 

     if (token) { 
      return xhr.setRequestHeader('X-CSRF-TOKEN', token); 
     } 
    }, 
    success: function (data) { 
     // Successfuly called the Controler 

     // Check if the logic was successful or not 
     if (data.status == 'success') { 
      console.log('alles ok'); 
     } else { 
      console.log(data.msg); 
     } 
    }, 
    error: function (data) { 
     // Error while calling the controller (HTTP Response Code different as 200 OK 
     console.log('Error:', data); 
    } 
}); 

}

+0

나는 이것을 시도했다. – Sachith

관련 문제