2017-06-16 8 views
-1

ajaxが成功したかどうかを確認するメッセージを表示します。 これまでのコードは動作しますが、いくつかのメッセージを追加したいと思います。Laravel Ajaxショーメッセージ

私のコントローラは、機能削除:

public function destroy(Request $request, $streamID = 0) 
{ 
    $stream = Stream::find($streamID); 

    if($stream) 
    { 
     $stream->delete(); 
     File::delete($stream->image); 
     return redirect()->route('stream.index')->with('success', 'Hooray'); 
    } 
    else 
    { 
     return redirect()->route('stream.index')->with('success', 'Not Hooray'); 
    } 
} 

とAjaxの成功とエラー部分:代わりにPHPコードからリダイレクトする

 success: function(data) { 
      // show message? 
     }, 
     error: function(data) { 
      // show message? 
     } 
+0

どうすればよろしいですか? '警告'機能について教えてください。 –

+0

Flashデータhttps://laravel.com/docs/5.4/session#flash-data – mfgabriel92

+0

を使用すると、リダイレクト() - >経路( 'stream.index') - >( 'success'、 'Hooray ');)return return() - > json([' success '=>' Hooray ']); – sunilwananje

答えて

1

を、あなたのAjaxの機能からリダイレクトし、あなたにJSONレスポンスを送信しますajax関数as

public function destroy(Request $request, $streamID = 0) 
{ 
    $stream = Stream::find($streamID); 

    if($stream) 
    { 
     $stream->delete(); 
     File::delete($stream->image); 
     return response() ->json(['code'=>200,'success' => 'Hooray']); 
    } 
    else 
    { 
     return response() ->json(['code'=>400,'success' => 'Not Hooray']) 
    } 
} 

とあなたのajaxの成功関数

success: function(response) { 
     alert(response.success); 
     window.location.href = 'stream.index'; 
}, 
error: function(data) { 
     // show message? 
} 
+0

どのようにlaravelsフラッシュメッセージスタイル(緑色/赤色の背景のボックス)でそれを表示しますか? – utdev

+0

あなたのコードは動作しませんでした – utdev

0

は、私はこれに前の回答を更新:

.... 
    if($stream) { 
     $stream->delete(); 
     File::delete($stream->image); 
     return response()->json(['code'=>200,'success' => 'Hooray'],200); 
} 
    else { 
      return response()->json(['code'=>400,'success' => 'Not Hooray'],200); 
    } 
+0

こんにちは、どこで/どのように私はajaxで成功メッセージを追加しますか? – utdev

+0

@utdevあなたのコメントへの回答を掲載しました – hazelcodes

0

ブートストラップを使用している場合は、これはどこでもあなたのアラートが

<div id="ajax-alert" class="alert" style="display:none"></div> 

表示これにスクリプトを変更したい追加します:

success: function(response){ 
    If(response.code === 200) { 
     $('#ajax-alert').addClass('alert-sucess').show(function(){ 
      $(this).html(response.success); 
     }); 
    } 
    If(response.code === 400){ 
     $('#ajax-alert').addClass('alert-danger').show(function(){ 
      $(this).html(response.success); 
     }); 
    } 
}, 
error: function(data) { 
    alert ('Ajax run unsuccessful'); 
}