I am converting a procedural PHP application into a RESTful Laravel/jQuery application. I have done some extensive research, but all suggestions have failed and are included below.
In the old version creation of a new record was done by GETting the page URL with ?Add as a GET variable:
<div class="dropdown">
<button id="BtnID">File</button>
<div class="dropdown-content">
<a href="./?Add">Add New</a>
<a href="...">More menu items</a>
</div>
</div>
As per Laravel standards I am attempting to POST a request to the page, so I have altered the menu as:
<div class="dropdown">
<button id="BtnID">File</button>
<div class="dropdown-content">
<form id="AddNew">
<!--<a id="Add" href="#">Add New</a>-->
<!--input type='button' id='Add' value='Add New' /><!--Suggested change - also not working-->
<input type='submit' id='Add' value='Add New' /><!--Another suggested change - also not working-->
</form>
<a href="...">More menu items</a>
</div>
</div>
jQuery:
$('#Add').on('click',function(e) {
e.preventDefault;
if(confirm('some text'))
$('#AddNew').submit();
return false;
});
$('#AddNew').append(CSRF);
$('#AddNew').attr('action','./');
$('#AddNew').attr('method','post');
Can anyone help me figure out why this form refuses to POST the request? The confirmation message appears and then navigates to the correct page, but application makes a GET request to it?
I have noticed the CSRF token input is not displayed in the URL, as I would expect for a GET request.
EDIT
As requested here are the routes associated to this page:
// Route::get('/SubDirectory/ThisPage/','ThisController@index'); Usually forwards to first page, but commented out for testing this
Route::get('/SubDirectory/ThisPage/{PageNr}', 'ThisController@edit');
Route::post('/SubDirectory/ThisPage/', 'ThisController@add');
Route::delete('/SubDirectory/ThisPage/{ID}', 'ThisController@destroy');
Route::patch('/SubDirectory/ThisPage/{ID}', 'ThisController@update');
3
Answers
I have discovered this doesn't like using './' as the action target. I changed the action attribute to the full URL '/SubDirectory/ThisPage' and this now works.
HTML forms are submitted using inputs or buttons with submit types. You should not use links to submit forms, yet if you are so keen on submitting a form with a link you can use a link with attribute
onclick="form.submit();"
. Note that if you use this method, it will not work for users that do not support javascript.I think you are missing CSRF token which is causing issue. Working example is here