user333121 user333121 - 1 year ago 48
Javascript Question

Getting different results from the same form in laravel

I'm trying to create an ajax form using laravel. The display is a table with names and next to the names are buttons enclosed by forms to do actions.

Here is the html:

<div style="margin-top: 100px;">
<h2>Character settings</h2>
<table class="table table-striped table-bordered table-hover">
@foreach($chars as $char)
{{Form::open(array('action' => 'UsersController@move', 'id' => 'mover'))}}
<input type="hidden" name="charID" id="charID" value="{{$char['id']}}" />
<button type="submit" class="btn btn-small btn-info">Move</button>

Here is the javascript ajax processing:

$('#mover').on('submit', function(e){
var $form = $( this ),
method = $form.attr( "method" );
url: "{{action('UsersController@move')}}",
dataType: "json",
data: $('#charID').val(),
type: method,
success: function (response) {

Here is the controller:

public function move() {
return Response::json(array('test' => 'test'));

The table looks like:
Image here

If I click the first button for Sambte, it works and I see "test" in the console. But when I click the 2nd link it doesn't send as ajax and sends me to a new page with the json object as the content of that page so I see {"test":"test"} in the new page it brought me to.

I can't figure out what's wrong. Hopefully its a small error somewhere.

Thank you

Answer Source

ID's are unique, you need to use a class on the form instead.

'class' => 'mover'

Then just use the class instead of the ID in the selector


Sidenote, the same needs to be done for the charID, here's how I'd tackle that:


then, in your submit handler:

data: $form.find('.charID').val()