Use ajax javascript in laravel 11
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
return view("show");
}
public function ajaxCall()
{
$data = array("one", "two", "three");
return response()->json(["data" => $data]);
}
}
Above File is app\Http\Controllers\UserController.php FileAbove File is app\Models\User.php File
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
Below File is resources\views\show.blade.php File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Show</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-10">
<div class="card">
<div class="card-header">
<h3>Ajax</h3>
<p id="data"></p>
</div>
<div class="card-body">
<button onclick="ajaxCall()" class="btn btn-success">Click to Ajax Call</button>
</div>
</div>
</div>
</div>
</div>
<script>
function ajaxCall()
{
document.getElementById("data").innerHTML = "";
var req = new XMLHttpRequest();
req.open("GET","/ajax-call",true);
req.send();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200) {
// console.log(req.responseText);
var data = JSON.parse(req.responseText);
for(let i=0;i<data.data.length;i++) {
console.log(i);
document.getElementById("data").innerHTML += " " + data.data[i];
}
}
}
}
</script>
</body>
</html>
Below File is routes\web.php File
.png)
Comments
Post a Comment