I'm trying to retrieve an user's data from my database and put it in a form inside a modal in order to edit it. I've tried using the JQuery .post method to get a Json, but it fails and sends me a 500 Internal Server Error. I'm using an example on the internet as reference but I can't get it to work, I think the request is not getting any data to send, as some tests I made showed. I'm using the Laravel 4 framework, here's the JQuery code:
<script>
$(document).ready(function()
{
$('.edit').click(function()
{
$('[name=user]').val($(this).attr('id'));
var faction="<?php echo URL::to('getuser/data'); ?>";
var fdata = $('#val').serialize();
$.post(faction,fdata,function(json)
{
if(json.success)
{
$('#formEdit input[name="name_edit"]').val(json.name);
$('#formEdit input[name="lastname_edit"]').val(json.lastname);
$('#formEdit input[name="mlastname_edit"]').val(json.mlastname);
$('#formEdit input[name="email_edit"]').val(json.email);
$('#formEdit input[name="username_edit"]').val(json.username);
if(json.level==true)
{
$('#level.prop').prop('checked','true');
}
else
{
$('#level').removeAttr('checked');
}
}
}).fail(function(msg) {
alert(msg.status + " " + msg.statusText);
});
});
});
</script>
This is the button that calls the modal and sends the post request:
<span class="btn btn-info">{{HTML::link('#Edit','Editar',array('class'=>'edit','id'=>$user->id,'data-toggle'=>'modal','title'=>$user->name))}}</span>
And this is the controller:
<?php
class getuserController extends BaseController
{
public function postData()
{
$user_id=Input::get('user');
$user=User::find($user_id);
$data=array(
'success'=>true,
'id'=>$user->id,
'name'=>$user->name,
'lastname'=>$user->lastname,
'mlastname'=>$user->mlastname,
'email'=>$user->email,
'username'=>$user->username,
'level'=>$user->$user->level
);
return Response::json($data);
}
}
答案 0 :(得分:0)
将Ajax与Laravel结合使用需要发送_token。这可以通过在每个页面上将令牌作为元标记<meta name="csrf_token" content="{{ csrf_token() }}">
轻松完成。
然后在设置表单数据时使用var token = $("meta[name='csrf_token']").attr('content');
我喜欢下面的事情:
$(document).on('click', ".config", function() {
var id = $(this).data('id');
var token = $("meta[name='csrf_token']").attr('content');
$.ajax({
url: '/dashboard/ajax/load',
type: 'POST',
data: { id: id, _token: token },
success: function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data);
$(obj).each(function(key, value) {
var options = '<option value="' +value.id+ '">' +value.name+ '</option>';
$("#new_sub_element").append(options);
});
}
});
可以将值的设置解析为您的模态窗口...希望这可以帮助您:)
答案 1 :(得分:0)
我的代码工作正常,我错过了隐藏文字字段name = 'user'
和id = val
,其中存储了用户的ID,这就是为什么它没有发送任何value
;我的控制器中也出现语法错误,在$user->level
,我写了两次,这很简单,有点令人尴尬,但我很高兴我可以解决它。