1

I am trying to pass my id from ajax to my controller. I mostly see that it is being done through the url but is there any other way i could do this without using the URL?

View

          </div>
          <div class="form-group">
<label for="select" class="col-lg-2 control-label">Item</label>
<div class="col-lg-10">
<select class="form-control" id="item" name="item" mulitple>
<option >
</option>
</select>

</select>
</div>
</div>


$('#item').change(function()
        {    
             id =$(this).val();
            alert(id);
        }

        )

Controller

public function store(Request $request)

{
    $id = $request->id;
    $item = Item::all()->where('id',$id)->first();

}
XamarinDevil
  • 873
  • 5
  • 17
  • 38
  • Your input in the markup has an ID of Item and your script is targeting id=food. Also your label is targeting "select" which does not exist. And you have a select nesting within another select (that wont work) – happymacarts Oct 24 '17 at 22:42
  • @happymacarts sorry i just edited that to what i have currently – XamarinDevil Oct 24 '17 at 22:42
  • I see no ajax request in this code. Do you intend to include it in the "Change" function? – happymacarts Oct 24 '17 at 22:45
  • Yes..because i am fetching the id of the items dynamically. I am able to output the id's respectively but the issue now is `passing it to the controller` – XamarinDevil Oct 24 '17 at 22:47
  • @happymacarts well i only included a small part of the script. That is where i am fetching the id of the selected items – XamarinDevil Oct 24 '17 at 22:47

1 Answers1

0

Since you are using jquery, you can use jquery's ajax method to send out variables or data to your controller on laravel. Just be sure to read on form method spoofing from the laravel docs in any case at all, check it out here.

Jquery's ajax documentation goes here.

Here's how it'd look like:

function usersManagementAjax(requestType, url, userData, modalSelector, modalFailedSelector){
modalSelector.modal('hide');
$.ajax({
    type: requestType,
    url: url,
    data: userData,
    dataType: "json",
    success: function(data){
        modalSuccess.modal('show');
    },
    error: function(data){
        if(data.responseJSON.errors.contactNumber){
            contactGrp.removeClass('has-success');
            contactGrp.addClass('has-error');
            contactGrpError.removeClass('hidden');
            contactError = true;
            contactErrorText.text(data.responseJSON.errors.contactNumber[0]);
            isValid();
        }

        if(data.responseJSON.errors.email){
            emailGrp.removeClass('has-success');
            emailGrp.addClass('has-error');
            emailGrpError.removeClass('hidden');
            emailError = true;
            emailErrorText.text(data.responseJSON.errors.email[0]);
            isValid();
        }
        modalFailedSelector.modal('show');
    }
}); }

And here's how a function in a controller would look like:

 public function update(Request $request)
{
    $userId = $request->id;
    $updateRules = [
        'name' => 'required|string|max:255',
        'email' => [
            'required',
            'string',
            'email',
            'max:120',
            Rule::unique('users')->ignore($userId)
        ],
        'college' => 'required|string|min:1|max:1',
        'contactNumber' => [
            'required',
            'string',
            'min:11',
            'max:11',
            Rule::unique('users')->ignore($userId)
        ]
    ];

    $validation = Validator::make(Input::all(), $updateRules);
    if($validation->fails()){
        return Response::json(
            array('errors' => $validation->getMessageBag()->toArray()), 404);
    }

    else{
        $user = User::find($userId);
        $user->name = $request->name;
        if(Auth::user()->role->role != "Admin"){
            $user->roleID = Role::$defaultRoleId;
        }

        else{
            $user->roleID = $request->role;
        }
        $user->collegeID = $request->college;
        $user->contactNumber = $request->contactNumber;
        $user->email = $request->email;
        $user->save();

        return response()->json($user);
    }
}

Be aware that this is just a code sample and I have only meant to give you an idea on how to work around this. These are some code snippets from my current project.

EDIT: I forgot to mention that for ajax requests to work on a laravel project, you must include a X-CSRF-TOKEN for every ajax request. (Or you can simply remove the VerifyCsrfToken middleware) Link about this goes here.

jjjmnz
  • 49
  • 1
  • 6
  • you can also add `````` to your layout.blade.php file Sometimes depending on your setup you may need to use this ```$(document).ready(function() { $.ajaxSetup({ headers : { 'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content') } }); })``` – happymacarts Oct 24 '17 at 22:54
  • Yep. I'm currently using this method mentioned by happymacarts. Forgot to include it in my reply. Thanks! – jjjmnz Oct 24 '17 at 22:55
  • I don't really know how your answer solves my question here – XamarinDevil Oct 24 '17 at 22:56
  • Which id are you referring to anyways? The html select's id? – jjjmnz Oct 24 '17 at 22:59
  • Yes the html select id. i want to pass the id of any item which is selected to my controller – XamarinDevil Oct 24 '17 at 23:00
  • Or do you mean the currently selected option? If that's so, go check this out [link] (https://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown) here. – jjjmnz Oct 24 '17 at 23:01
  • The issue is not getting the id of the selected item but it is passing the id of the selected item to the controller – XamarinDevil Oct 24 '17 at 23:03
  • https://stackoverflow.com/a/2888447/6840113 then have an ajax request that would send this variable to your laravel controller. – jjjmnz Oct 24 '17 at 23:05