user333121 user333121 - 5 months ago 14
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">
<tr>
<th>Name</th>
<th>Map</th>
<th>Move</th>
</tr>
@foreach($chars as $char)
<tr>
<td>{{$char['name']}}</td>
<td>{{$char['map']}}</td>
<td>
{{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>
{{Form::close()}}
</td>
</tr>
@endforeach
</table>




Here is the javascript ajax processing:

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




Here is the controller:

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


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

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

$('.mover')

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

class="charID"

then, in your submit handler:

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