0

I am studing Ajax using JavaScript and want to create an Ajax post method in Laravel 5.4. These are my files...

Routes

Route::group(['prefix' => 'admin'],function(){
    Route::post('/ccat','PagesContrpllerController@ccat')->name('ccat');
    Route::resource('/products' , 'ProductController');
});     

ProductCategoryController

public function ccat(Request $request){
    return 'hello this is post method';
}

JavaScript

function sendfunc(name , level , parent){
    let xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4 && xhr.status==200) {
             console.log(this.responseText);
         }
    }

    xhr.open("POST", "ccat", true);
    xhr.setRequestHeader("Content-type", "application/x-www-formurlencoded");
    xhr.send("fname=Henry&lname=Ford");
}

I expect the 'hello this is the post method' in the console but instead it returns:

POST http://localhost:8000/admin/product/ccat 404 (Not Found)

What's happening in the console? Even when I change the URL to: http://localhost:8000/admin/ccat` it returns:

POST http://localhost:8000/admin/ccat 500 (Internal Server Error)

Thanks for any help and ignoring the bad coding. :)

1 Answer 1

0

I found my mistake that is the missing csrf_token so I add:

<meta name="csrf-token" content="{{ csrf_token() }}" />  

to header of page and get the csrf_token in javascript and send it to post route by:
xhr.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content );
and its worked. hope be useful for someone else

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.