irankhosravi
1 week ago
339
12
Laravel

How to change PHP AJAX to Laravel Ajax?

Posted 1 week ago by irankhosravi

I have a code in PHP AJAX. I want to PHP AJAX convert to Laravel Ajax.

I want to read data after insert post in database.

Look at my codes in PHP AJAX.

index.php

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	<link rel="stylesheet" type="text/css" href="themes/css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="themes/fontawesome/css/all.min.css">
	<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/dt-1.10.20/datatables.min.css"/>
	<title>CURD Application Using PHP-OOP, PDO-MYSQL, Ajax</title>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
	<a class="navbar-brand" href="#"><i class="fab fa-wolf-pack-battalion"></i> Oxibr</a>
	<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
		<span class="navbar-toggler-icon"></span>
	</button>
	<div class="collapse navbar-collapse" id="collapsibleNavbar">
		<ul class="navbar-nav ml-auto">
			<li class="nav-item">
				<a class="nav-link" href="#">Home</a>
			</li>
			<li class="nav-item">
				<a class="nav-link" href="#">About</a>
			</li>
			<li class="nav-item">
				<a class="nav-link" href="#">Contact</a>
			</li>
			<li class="nav-item">
				<a class="nav-link" href="#">Blog</a>
			</li>
		</ul>
	</div>
</nav>

<div class="container">
	<div class="row">
		<div class="col-lg-12">
			<h4 class="text-center text-danger font-weight-normal my-3">CURD Application Using Bootstrap 4, PHP-OOP, PDO-MYSQL, Ajax, DataTables & SweetAlert 2</h4>
		</div>
	</div>
	<div class="row">
		<div class="col-lg-6">
			<h2 class="mt-2 text-primary">All users in database!</h2>
		</div>
		<div class="col-lg-6">
			<button class="btn btn-primary m-1 float-right" type="button" data-toggle="modal" data-target="#addUserModal"><i class="fas fa-user-plus"></i> Add New User</button>
			<a href="action.php?export=excel" class="btn btn-success m-1 float-right"><i class="fas fa-table fa-lg"></i> Export To Excel</a>
		</div>
	</div>
	<hr class="my-1">
	<div class="row">
		<div class="col-lg-12">
			<div class="table-responsive" id="showUsers">
				<h3 class="text-center text-success mt-5">Loading...</h3>
			</div>
		</div>
	</div>
</div>

<div class="modal fade" id="addUserModal">
	<div class="modal-dialog modal-dialog-centered">
		<div class="modal-content">

			<!-- Modal Header -->
			<div class="modal-header">
				<h4 class="modal-title">Add New User</h4>
				<button type="button" class="close" data-dismiss="modal">&times;</button>
			</div>

			<!-- Modal body -->
			<div class="modal-body px-4">
				<form action="" method="post" id="addNewUserForm">
					<div class="form-group">
						<input type="text" id="first_name" name="first_name" class="form-control" placeholder="First name">
					</div>
					<div class="form-group">
						<input type="text" id="last_name" name="last_name" class="form-control" placeholder="Last name">
					</div>
					<div class="form-group">
						<input type="text" id="email" name="email" class="form-control" placeholder="E-Mail Address">
					</div>
					<div class="form-group">
						<input type="tel" id="phone" name="phone" class="form-control" placeholder="Phone">
					</div>
					<div class="form-group">
						<input type="submit" id="insert" name="insert" class="btn btn-danger btn-block" value="Add User">
					</div>

				</form>
			</div>

		</div>
	</div>
</div>

<div class="modal fade" id="editUserModal">
	<div class="modal-dialog modal-dialog-centered">
		<div class="modal-content">

			<!-- Modal Header -->
			<div class="modal-header">
				<h4 class="modal-title">Edit User</h4>
				<button type="button" class="close" data-dismiss="modal">&times;</button>
			</div>

			<!-- Modal body -->
			<div class="modal-body px-4">
				<form action="" method="post" id="editUserForm">
					<input type="hidden" id="id" name="id">
					<div class="form-group">
						<input type="text" id="first_name" name="first_name" class="form-control" placeholder="First name">
					</div>
					<div class="form-group">
						<input type="text" id="last_name" name="last_name" class="form-control" placeholder="Last name">
					</div>
					<div class="form-group">
						<input type="text" id="email" name="email" class="form-control" placeholder="E-Mail Address">
					</div>
					<div class="form-group">
						<input type="tel" id="phone" name="phone" class="form-control" placeholder="Phone">
					</div>
					<div class="form-group">
						<input type="submit" id="update" name="update" class="btn btn-warning btn-block" value="Update User">
					</div>

				</form>
			</div>

		</div>
	</div>
</div>

<script src="themes/js/jquery-3.3.1.slim.min.js"></script>
<script src="themes/js/jquery-3.4.1.min.js"></script>
<script src="themes/js/popper.min.js"></script>
<script src="themes/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/v/bs4/dt-1.10.20/datatables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</body>
</html>

<script>
	$(document).ready(function () {
		showAllUsers();
		function showAllUsers() {
			$.ajax({
				url: "action.php",
				type: "POST",
				data: {action: "view"},
				success: function (response) {
					console.log(response);
					$("#showUsers").html(response);
					$("table").DataTable({
						order: [0, 'desc']
					});
				}
			});
		}
		$('#addUserModal').click(function (e) {
			e.preventDefault();
			if ($("#addNewUserForm")[0].checkValidity()) {
				e.preventDefault();
				$.ajax({
					url: "action.php",
					type: "POST",
					data: $("#addNewUserForm").serialize() + "&action=insert",
					success: function (response) {
						Swal.fire({
							title: "User added successfully.",
							type: 'success',
						});
						$('#addUserModal').modal('hide');
						$('#addNewUserForm')[0].reset();
						showAllUsers();
					}
				});
			}
		});
	});
</script>

db.php

<?php
class Database {
	private $dsn = "mysql:host=localhost;dbname=new_crud";
	private $user = "root";
	private $pass = "";
	public $conn;

	public function __construct()
	{
		try {
			$this->conn = new PDO($this->dsn, $this->user, $this->pass);
		}
		catch (PDOException $exception) {
			echo $exception->getMessage();
		}
	}

	public function insert($first_name, $last_name, $email, $phone)
	{
		$sql = "INSERT INTO users (first_name, last_name, email, phone) VALUES (:first_name, :last_name, :email, :phone)";
		$stmt = $this->conn->prepare($sql);
		$stmt->execute(['first_name' => $first_name, 'last_name' => $last_name, 'email' => $email, 'phone' => $phone]);
		return true;
	}

	public function read()
	{
		$data = array();
		$sql = "SELECT * FROM users";
		$stmt = $this->conn->prepare($sql);
		$stmt->execute();
		$result = $stmt->fetchAll(PDO::FETCH_OBJ);
		foreach ($result as $row) {
			$data[] = $row;
		}
		return $data;
	}

action.php

<?php
require_once 'db.php';
$db = new Database();
if (isset($_POST['action'])  && $_POST['action'] == 'view') {
	$output = '';
	$data = $db->read();
	if ($db->totalRowColumn() > 0) {
		$output .= '<table class="table table-striped table-bordered table-sm">
						<thead>
						<tr class="text-center">
							<th>ID</th>
							<th>First Name</th>
							<th>Last Name</th>
							<th>E-Mail</th>
							<th>Phone</th>
							<th>Action</th>
						</tr>
						</thead>
						<tbody>';
			foreach ($data as $row) {
				$output .= '<tr class="text-center text-secondary">
								<td>' . $row->id . '</td>
								<td>' . $row->first_name . '</td>
								<td>' . $row->last_name . '</td>
								<td>' . $row->email . '</td>
								<td>' . $row->phone . '</td>
								<td>
									<a href="#" id="' . $row->id . '" title="View Details" class="text-success infoBtn"><i class="fas fa-info-circle fa-lg"></i></a>&nbsp;&nbsp;
									<a href="#" id="' . $row->id . '" title="Edit" data-toggle="modal" data-target="#editUserModal" class="text-primary editBtn"><i class="fas fa-user-edit fa-lg"></i></a>&nbsp;&nbsp;
									<a href="#" id="' . $row->id . '" title="Delete" class="text-danger deleteBtn"><i class="fas fa-user-times fa-lg"></i></a>
								</td>
							</tr>';
						}
		$output .= '</tbody>
				</table>';
			echo $output;
	} else {
		echo '<h3 class="text-center text-secondary mt-3">:( Vo any user present in the database!)</h3>';
	}
}

if (isset($_POST["action"]) && $_POST["action"] == "insert") {
	$first_name = $_POST['first_name'];
	$last_name = $_POST['last_name'];
	$email = $_POST['email'];
	$phone = $_POST['phone'];
	$db->insert($first_name, $last_name, $email, $phone);
}

And in my laravel

PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use Illuminate\Http\Response;

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::latest()->get();
        return view('index', compact('posts'));
    }

    public function store (Request $request)
    {
        $post = new Post();
        $post->title = $request->title;
        $post->body = $request->body;
        $post->user_id = 1;
        if($request->has('image_post')) {
            $image = $request->file('image_post');
            $filename = $image->getClientOriginalName();
            $image->move(public_path('images/posts'), $filename);
            $post->image = $request->file('image_post')->getClientOriginalName();
        }
        $post->save();
        $post->categories()->attach($request->category);
        return json_encode($post);
    }
}

web.php

Route::resource('posts', 'PostController');

ajax

<script>
    $(document).ready(function () {
        $('#postAdd').click(function(e){

            e.preventDefault();

            var form = $('#addPost');
            var formData = new FormData($('#addPost')[0]);

            $.ajax({
                type: "POST",
                url: "{{ route('posts.store') }}",
                data: formData,
                processData: false,
                contentType: false,
                success: function (data) {
                    var resp = JSON.parse(data);
                    var result = "";
                },
                error: function (error) {
                    console.log(error);
                    alert('error'+error);
                }
            })
        })
    })
</script>

Please sign in or create an account to participate in this conversation.