 Laravel по-русски
Laravel по-русски
      
      
    Русское сообщество разработки на PHP-фреймворке Laravel.
Ты не вошёл. Вход тут.
Страницы 1
Здравствуйте. Пытаюсь сделать ajax отправку формы, но почему-то выдает ошибку throw new MethodNotAllowedHttpException($others);
Route:
Route::get('/', 'IndexController@index');
Route::post('/sendmail', 'Ajax\ArticleController@send');IndexController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Article;
use DB;
class IndexController extends Controller
{
    public function index() {
    
    
        $articles = DB::select("SELECT * FROM `articles`");
        dump($articles);
        return view('welcome')->withUsers($articles);
    
    }
}Ajax\ArticleController:
<?php
namespace App\Http\Controllers\Ajax;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Article;
use DB
class ArticleController extends Controller
{
    public function send(Request $request)
    {
        dump($request->all());
    }
}JS файл
$(document).ready(function(){
    $('#contactform').on('submit', function(e){
        e.preventDefault();
 
        $.ajax({
            type: 'POST',
            url: '/sendmail',
            data: $('#contactform').serialize(),
            success: function(result){
                console.log(result);
            }
        });
    });
});Шаблон:
<form id="contactform" method="POST" >
                 <input type="hidden" name="_token" value="{{ csrf_token() }}">
                <input type="hidden" name="_method" value="POST">
    
    <input type="text" name="username" placeholder="Введите ник" required />
    <input type="text" name="text" placeholder="Введите сообщение" required />
     <button type="submit">Отправить</button>
     
</form>
@foreach ($users as $user) 
                        {{ $user->text }}
                @endforeachМодель Article
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
    protected $fillable = ['username','text'];
}Буду очень благодарен помощи. Только начал изучать и эта ошибка меня ввела в ступор
Изменено SPtrue (31.10.2017 12:43:45)
Не в сети
->withUsers() это что за метод?
Не в сети
Передаю переменную в вьюху
@foreach ($users as $user) 
                        {{ $user->text }}
                @endforeachтут используется
Не в сети
Не нашел такой метод в доке - я ->with('users', $articles) использую
Изменено maximilianno (31.10.2017 20:27:15)
Не в сети
Это у меня работает точно, я проверял. Ошибка в чем-то другом
Не в сети
у тебя jquery не подключен наверно, только версию сам выбирай
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Изменено maximilianno (01.11.2017 08:41:24)
Не в сети
Перепробовал разные версии. Все равно та же ошибка...
Вот полный код вьюхи
<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
         <link rel="stylesheet" type="text/css" media="all" href="{{asset('css')}}/app.css" />
		
		
        <title>Форум</title>
        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Raleway', sans-serif;
                font-weight: 100;
                height: 100vh;
                margin: 0;
            }
            .full-height {
                height: 100vh;
            }
            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }
            .position-ref {
                position: relative;
            }
            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }
            .content {
                text-align: center;
            }
            .title {
                font-size: 84px;
            }
            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 12px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }
            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
        <script type="text/javascript" src="/js/jquery-3.2.1.min.js"></script>
    </head>
    <body>
    
        <div class="flex-center position-ref full-height">
            @if (Route::has('login'))
                <div class="top-right links">
                    @auth
                        <a href="{{ url('/home') }}">Home</a>
                    @else
                        <a href="{{ route('login') }}">Login</a>
                        <a href="{{ route('register') }}">Register</a>
                    @endauth
                </div>
            @endif
            
            <div class="content">
                <form id="contactform" method="POST" >
                 <input type="hidden" name="_token" value="{{ csrf_token() }}">
                <input type="hidden" name="_method" value="POST">
    
                <input type="text" name="username" placeholder="Введите ник" required />
                <input type="text" name="text" placeholder="Введите сообщение" required />
                 <button type="submit">Отправить</button>
     
                </form>
                @foreach ($users as $user) 
                        {{ $user->text }}
                @endforeach
            </div>
        </div>
        
        
    </body>
</html>/js/jquery-3.2.1.min.js загружен, в исходном коде переходил, ссылка верная
Изменено SPtrue (01.11.2017 12:15:33)
Не в сети
Короче в полном коде вьюхи не вижу теперь подключения твоего скрипта. Попробуй мою вью я там еще с токеном строку переделал, там что-то другое вылезало:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form id="contactform" method="POST" >
    {{--<input type="hidden" name="_token" value="{{ csrf_token() }}">--}}
    {{csrf_field()}}
    <input type="hidden" name="_method" value="POST">
    <input type="text" name="username" placeholder="Введите ник" required />
    <input type="text" name="text" placeholder="Введите сообщение" required />
    <button type="submit">Отправить</button>
</form>
@foreach ($users as $user)
    {{ $user->text }}
@endforeach
<script>
    $(document).ready(function(){
        $('#contactform').on('submit', function(e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: '/sendmail',
                data: $('#contactform').serialize(),
                success: function(result){
                    console.log(result);
                }
            });
        });
    });
</script>
Изменено maximilianno (01.11.2017 13:26:59)
Не в сети
или вот твоя переделанная у меня работает
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="all" href="{{asset('css')}}/app.css" />
    <title>Форум</title>
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
    <!-- Styles -->
    <style>
        html, body {
            background-color: #fff;
            color: #636b6f;
            font-family: 'Raleway', sans-serif;
            font-weight: 100;
            height: 100vh;
            margin: 0;
        }
        .full-height {
            height: 100vh;
        }
        .flex-center {
            align-items: center;
            display: flex;
            justify-content: center;
        }
        .position-ref {
            position: relative;
        }
        .top-right {
            position: absolute;
            right: 10px;
            top: 18px;
        }
        .content {
            text-align: center;
        }
        .title {
            font-size: 84px;
        }
        .links > a {
            color: #636b6f;
            padding: 0 25px;
            font-size: 12px;
            font-weight: 600;
            letter-spacing: .1rem;
            text-decoration: none;
            text-transform: uppercase;
        }
        .m-b-md {
            margin-bottom: 30px;
        }
    </style>
    {{--<script type="text/javascript" src="/js/jquery-3.2.1.min.js"></script>--}}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<div class="flex-center position-ref full-height">
    @if (Route::has('login'))
        <div class="top-right links">
            @auth
                <a href="{{ url('/home') }}">Home</a>
                @else
                    <a href="{{ route('login') }}">Login</a>
                    <a href="{{ route('register') }}">Register</a>
                    @endauth
        </div>
    @endif
    <div class="content">
        <form id="contactform" method="POST" >
            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            <input type="hidden" name="_method" value="POST">
            <input type="text" name="username" placeholder="Введите ник" required />
            <input type="text" name="text" placeholder="Введите сообщение" required />
            <button type="submit">Отправить</button>
        </form>
        @foreach ($users as $user)
            {{ $user->text }}
        @endforeach
    </div>
</div>
<script>
    $(document).ready(function(){
        $('#contactform').on('submit', function(e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: '/sendmail',
                data: $('#contactform').serialize(),
                success: function(result){
                    console.log(result);
                }
            });
        });
    });
</script>
</body>
</html>Не в сети
Спасибо. Что-то я затупил... Не подскажите как теперь добавить эти данные в мою бд?
Не в сети
Все, плавит. Сам добавил)
Спасибо огромное за помощь)
Не в сети
Что-то по типу такого. И работать лучше с моделями,а не с фасадом DB
$article = Article::find($data['id']);
$article->name = $data['name'];
$article->img = $data['img'];
$article->text = $data['text'];
$user->articles()->save($article); Я если честно сам только сегодня тему с аяксом и ларавель начал проходить/ Вот тут глянь, правда тут немного посложнее:
https://www.youtube.com/watch?v=tRcUybG … o2ldxWWtJR
Изменено maximilianno (01.11.2017 13:57:50)
Не в сети
Страницы 1