0

I'm a beginner in AJAX Jquery. My form will contain an array of values named dualistbox_demo1[] that the user has selected. However, it seems that the ajax function is not storing the values into my database.

My form in blade template:

{{Form::open(array('url' => 'schools/assign',"id"=>"demoform"))}}
<select multiple="multiple" size="10" name="duallistbox_demo1[]">

@foreach($user as $key => $value) 
  <option value="{{ $value->id}}">{{ $value->FirstName }} {{ $value->LastName }}</option>
@endforeach
</select>

{{ Form::submit('Submit', array('class' => 'btn btn-default btn-block')) }}
{{ Form::close() }}

This is my js script:

<script>
$("#demoform").submit(function() {
  $.ajax({
    url: 'action',
    type: 'POST',
    data: ('[name="duallistbox_demo1[]"]').val(),
    success : function(data)
    {
      console.log(data);
    }
  });
});
</script>

My routes.php:

Route::post('/schools/assign', function(){
if(Request::ajax()){
    $AC = new AccessControlEntry();
    $AC->UserID     =   Input::get('duallistbox_demo1');
    $AC->save(); 
}
});

I really can't figure out what/where did I went wrong. Any help is greatly appreciated!

0

1 Answer 1

1

You are trying to call the val method on a String object. Missing $/jQuery in:

data: ('[name="duallistbox_demo1[]"]').val(),

Apart from that you should pass a identifier:value pair:

data: {
  'duallistbox_demo1': $('[name="duallistbox_demo1[]"]').val(),
}

Since val for a a multiple select returns an array you might want to call the join method for converting the array to a string.

Sign up to request clarification or add additional context in comments.

2 Comments

I've just read on the join method, and found out that the implode function is an alias of join. So I've add on these codes to convert the array to string: $selectedadmins = $('[name="duallistbox_demo1[]"]').val(); $stringadmins = implode(",", $selectedadmins); So inside my $.ajax function, data: { 'duallistbox_demo1': $('stringadmins'), }, Storing into database still doesn't work. Did I do it wrongly? Really have hard time understanding Ajax jquery @undefined
@AnneTan data: { 'duallistbox_demo1': $('stringadmins'), }, is not what I have suggested, you can't pass a jQuery object in that way, you should pass the value as a string, stringifing a jQuery object results in "can't convert a circular structure to JSON" error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.