HTTP Request Error With Onchange JS Function
I am trying to add a state feature to a ticketing system built in Laravel that will maintain if a ticket is open, closed, on-hold, etc.
I have the states table created, and I can reference that table in my view.
The view has a drop-down menu with all the possible states, and I would like to update the ticket's state when a new state is selected from the drop-down menu.
Currently, I have an onchange JavaScript function running, but I am having an issue submitting the POST request from the JavaScript function. When redirecting to the POST route, I receive the error: MethodNotAllowedHttpException.
The post route works correctly if I make each state its own form button.
The last time I received this error was because I forgot to pass the CSRF token into a form. However, I have no idea how to do this with a JavaScript function.
I'm sure there is a way to accomplish what I am trying to do, but I'm not sure how to do it.
Thanks for any help!
This is my View
<form name="stateForm" action="{{ url($claim->path() . '/state') }}">
<select id="stateList" onchange="stateChange(this.form)">
@foreach($states as $state)
<option id="{{ url($claim->path() . '/state/' . $state->id) }}" value="{{ $state->id }}">{{ $state->name }}</option>
@endforeach
</select>
</form>
JavaScript called on change
function stateChange(stateForm, URL)
{
var selIndex = stateForm.stateList.selectedIndex;
var URL = stateForm.stateList.options[selIndex].id;
window.location.href = URL;
}
Laravel route
Route::post('/claims/{claim}/state/{stateID}', '[email protected]');
Working code using forms and buttons
<div class="btn-group">
@foreach( $states as $state)
<form method="post" action="{{ url($claim->path() . '/state/'. $state->id) }}">
{{ csrf_field() }}
<button>
{{ $state->name }}
</button>
</form>
@endforeach
</div>
Answer
window.location.href = URL;
is a get request that basically redirects
You need to change your route to a GET request instead
Route::get('/claims/{claim}/state/{stateID}', '[email protected]');
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM