user333121 user333121 - 1 year ago 97
jQuery Question

Why can't I get form inputs using ajax and laravel

I'm trying to parse the data that I send from my ajax form. But for some reason I cannot extract the information from the form in the php controller. Here's what I'm doing.

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', 'class' => 'mover'))}}
<input type="hidden" name="charID" class="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: $form.find('.charID').val(),
type: method,
success: function (response) {

Here is the controller:

public function move() {
if(Auth::check()) {
Log::info(Input::get('charID')); //When I check the logs this is blank
$person = Character::where('id', '=', Input::get('charID'))->first();
$person->map = 100000000;
$response = array('status' => 'success', 'text' => 'Your character has been moved!');
return Response::json($response);
else {
return Redirect::action('PageController@showHome');

When I check the console log on submit I see the data "charID", so its being extracted by the form correctly, but I can't seem to get it in the laravel controller. Strange thing is I use the Input::get() function in other parts of my controller. So it's just this function.

Any help appreciated!

Answer Source

You're accessing response[test] instead of response[text].

Other things of note:

Your use of exit(); is redundant and will never be hit because you are returning above it.

Also, exit is a language construct and it can be called without parens if no status is passed. So if you are to use it without an argument, just use exit;.

Your ajax method could be optimised a bit more and it seems you also have another problem with your data, which needs to be sent as a key value pair.

You could do it as an inline string in the form of a GET request, or as an object like { "charID": $(this).find("input[name=charID]").val() },.

$("#mover").on("submit", function (e) {


    "url": this.action, // <-- we can use native javascript
    "dataType": "json",
    "data": $(this).serialize(), // <-- collects your form data
    "type": this.method,
    "success": function (data) {
      if (data.success !== "undefined" && data.success === 200) {


I would recommend against using the Form helper class. It isn't very readable after-the-fact. You don't save that much time using it compared to writing out the HTML form definition anyway.

Let's optimise your controller so it's easier to understand as well:

public function move () 
    if (Auth::check()) {

        Log::info(($charID = request('charID'))); 

        $person = Character::where('id', '=', $charID)->first();
        $person->map = 100000000;

        return response()->json([
            'success' => 200, // success
            'text' => 'Your character has been moved!'

    } else {

        return response()->json([
            'success' => 401 // unauthorised


For a variable you're accessing more than once, I use a neat trick with parens (). If you wrap an assignment in parens e.g. ($charID = request('charID')) you can still use it's output in-line, with the added benefit that you now have access to it further into your script.

I'm opting for the helper methods like request() and redirect() instead of their class counterparts and the use of array() is a bit old hat - but that's just my opinion - I'd use square brackets [].

Your response when the user isn't authenticated is useless here assuming this controller action is only meant to handle posts from AJAX requests (if I'm not mistaken). Since it can't force your asynchronous request to redirect you. Instead we return the proper HTTP response code 401 to represent that the user was unauthorised.

You could also look up PSR-2 standards for your code structure, as that is what is used as an industry standard nowadays.

Lastly, if you are using the web middleware (with CSRF protection) on the controller here. You need to send a CSRF token with the request. You can do that by popping {{ csrf_field() }} into the form. The form helper may be doing this for you.

But another problem you would have stumbled into if you were not using $(this).serialize() in the AJAX setup is that the _token field would never have been sent along with the request.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download