Kvothe_0077
Kvothe_0077

Reputation: 107

Error passing data to php using AJAX(Laravel)

Good afternoon, I am trying to pass data from my form to the controller using Ajax, however I cannot do it correctly, what am I doing wrong?

Javascript

$("#btn_enviar").click(function() {

    title = document.getElementById("title").value;
    url_clean = document.getElementById("url_clean").value;
    content = document.getElementById("content").value;
    CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

    $.ajax({
        url     :  'dashboard/post/{data}',
        type    :  'post',
        dataType:  'json',
        data    :   {'CSRF_TOKEN':CSRF_TOKEN, 'title':title, 'url_clean':url_clean, 'content':content},
        success :   function (data) {
            alert('send');
        },
        error   :   function() {
            alert('error');
        }
    });

 });

Routes

<?php

use Illuminate\Support\Facades\Route;



Route::get('/', function () {
    return view('dashboard.posts.posts');
});

Route::resource('dashboard/post','dashboard\PostController');

Route::post('dashboard/post/{data}', 'dashboard\PostController@store');

when I click on the button, the console shows me the following error:

enter image description here

This has the validation rules for the submitted data

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostPost extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|min:5|max:500',
            'url_clean' => 'required|min:5|max:500',
            'content' => 'required|min:5' 
        ];
    }
}

This is the controller I'm trying to send the data to (PostController)

<?php

namespace App\Http\Controllers\dashboard;

use App\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\StorePostPost;
use Illuminate\Support\Facades\Route;

class PostController extends Controller
{
    public function index(){

        return view("dashboard.posts.create");
    }

    public function create(){

        return view("dashboard.posts.create");
    }

    public function store(StorePostPost $request){
        
        dd($request->all());

    }
}

Upvotes: 0

Views: 121

Answers (6)

Can you please provider is with the code in the store function in the controller?

The answer from @sta is correct but probably your controller code does not give the correct response back.

Also worth mentioning. You forget to add the laravel methode. So you should add '_method' :'POST' to your data object

And off topic, why should u get all the value out a form via a getelementbyid? If you Get the naming correctly u can also do it like this:

Let data = New FormData($('#form_id')) ;

Something like this. Don't have tested it to be honest.

edit: okay so this is how i think you should do it: Routes.php >

Route::resource('dashboard/post','dashboard\PostController');

the reason i dont include your custom url to store is that in the case you showed you dont even need it. in the resource there i already a store which you can call by ajax. If you ever need to change the store url use this:

Route::resource('dashboard/post','dashboard\PostController',['except'=>['store']]);

Route::post('dashboard/post/{data}', 'dashboard\PostController@store');

here i exclude the store from the resource routes so you don't have 2 routes pointing at the exact same function.

PostController.php

    public function store(StorePostPost $request){
        
        logger($request->all();
        return response()->json();

    }

i log you request which will now be found in the file /storage/logs/LOGNAME.log then i send back an empty json response with a 200 status. which is default. so this should come in the succes function.

Now your javascript:

$("#btn_enviar").click(function() {

    title = document.getElementById("title").value;
    url_clean = document.getElementById("url_clean").value;
    content = document.getElementById("content").value;
    CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

    $.ajax({
        url     :  '/dashboard/post',
        type    :  'post',
        dataType:  'json',
        data    :   {
           '_token':CSRF_TOKEN, 
           '_method':'POST',
           'title':title,
           'url_clean':url_clean,
           'content':content
        },
        success :   function (data) {
            alert('send');
        },
        error   :   function() {
            alert('error');
        }
    });

 });

now if you realy want to pass a parameter to you url by ajax you should use this:

        url     :  `/dashboard/post/${data}`,

or

        url     :  '/dashboard/post/' + data,

but in this case data is not defined in the code you give so it is kinda obvious why that doesn't work

Upvotes: 0

Aravindh
Aravindh

Reputation: 9

Give your full url to ajax url param. You are using resource routes, so in get route, your url will be base_url+/dashboard/post.

In post ajax it is calling your current page url and appending given url path.

Upvotes: 0

STA
STA

Reputation: 34688

On POST route, you don't need to define the parameter {data}, because it pass through POST Request, so change it to :

Route::post('dashboard/post/', 'dashboard\PostController@store');

And your Ajax :

$.ajax({
    url     :  '/dashboard/post/',
    type    :  'post',
    dataType:  'json',
    traditional: true,
    data    :   {'CSRF_TOKEN':CSRF_TOKEN, 'title':title, 'url_clean':url_clean, 'content':content},
    success :   function (data) {
        alert('send');
    },
    error   :   function() {
        alert('error');
    }
});

Upvotes: 1

Med.ZAIRI
Med.ZAIRI

Reputation: 190

1- Remove the {data} from the url in ajax (it's not needed there) like:

url     :  '/dashboard/post/',

2- as I know, laravel csrf_token field should be _token in the data fields,like:

data    :   {'_token':CSRF_TOKEN, 'title':title, 'url_clean'..

Upvotes: 0

Mustafa Poya
Mustafa Poya

Reputation: 3027

as the image shown the error the url path dashboard/post/{data} the {data} is a parameter value which have to be passed to the function.
2) the dashboard/post/{data} is repeating as 'dashboard/post/dashboard/post/{data}' which you need to set the url : 'dashboard/post/{data}' to url : '/dashboard/post/{data}' and {data} should be a value like object_id or something else.

Upvotes: 0

justrusty
justrusty

Reputation: 847

You are using a relative URL. Try url: '/dashboard/post/{data}' with a leading slash

Upvotes: 0

Related Questions