how to pass laravel route name to ajax request 1

how to pass laravel route name to ajax request

var id= $("input[name=editId]").val();
$.ajax({
   type:'POST',
   enctype: 'multipart/form-data',
   url:"{{ route('updateArticle') }}" + '/' + id,
   data: formdata,
   contentType: false,
   processData: false,
   success:function(data){
        $('.alert-success').html(data.success).fadeIn('slow');
        $('.alert-success').delay(3000).fadeOut('slow');
   }
});

Here is what the above code is Doing:
1. We are getting the id of the article we want to update.
2. We are making an ajax call to the route we created earlier.
3. We are passing the id of the article we want to update.
4. We are passing the form data to the route.
5. We are displaying a success message if the article is updated successfully.

Now, let’s create the route to update the article.

Route::post(‘/updateArticle/{id}’, ‘ArticleController@updateArticle’);

Now, let’s create the updateArticle method in the ArticleController.

public function updateArticle(Request $request, $id)
{
$article = Article::find($id);
$article->title = $request->title;
$article->body = $request->body;
$article->save();
return response()->json([‘success’=>’Article Updated Successfully.’]);
}

Here’s what the above code is doing:
1. We are getting the id of the article we want to update.
2. We are getting the article from the database.
3. We are updating the title and body of the article.
4. We are saving the article.
5. We are returning a success message.

Now, let’s create the deleteArticle method in the ArticleController.

public function deleteArticle($id)
{
$article = Article::find($id);
$article->delete();
return response()->json([‘success’=>’Article Deleted Successfully.’]);
}

Here’s what the above code is doing:
1. We are getting the id of the article we want to delete.
2. We are getting the article from the database.
3. We are deleting the article.
4. We are returning a success message.

Now, let’s create the delete route.

Route::get(‘/deleteArticle/{id}’, ‘ArticleController@deleteArticle’);

Now, let’s create the delete button in the index.blade.php file.

Now, let’s create the search button click event in the index.blade

Similar Posts