[英]Laravel:How to send Ajax to controller without form
我在網站上使用了一個jQuery插件。 我想先驗證一個表單,然后再向控制器發送另一個數據,但是不通過表單。 首先驗證是已經返回成功反饋。 但是,當第二個發送時,沒有任何反饋返回。 這是我的代碼
route.php
Route::controller('designs', 'DesignsController');
DesignsController.php
public function postTest() {
$validator = Validator::make(Input::all(), Design::$rules);
if ($validator->passes()) {
$response = array(
'status' => 'success'
);
return Response::json( $response );
}
$response = array(
'status' => 'fail'
);
return Response::json( $response );
}
public function postSaveimage() {
//Save Image complete return $success=1
if($success)
$response = array(
'status' => 'save image success'
);
else
$response = array(
'status' => 'Fail'
);
return Response::json( $response );
}
jQuery的
$('#design_form').on( 'submit' ,function() {
//Validate First form data
$.post(
$( this ).prop( 'action' ),
{
"_token": $( this ).find( 'input[name=_token]' ).val(),
"category_id": $( '#form_category_id' ).val(),
"title": $( '#form_title' ).val(),
"user_id": $( '#form_user_id' ).val(),
},
function( data ) {
//if validate fail
if(data.status=='fail')
{
alert('data.status');
}
//if validate pass
else
{
//Sent second data
$.post("designs/saveimage",
{
"_token": $( this ).find( 'input[name=_token]' ).val(),
'base64_image': yourDesigner.getProductDataURL()
}, function(data) {
if(data) {
alert(JSON.stringify(data));
}
else {
alert('fail!');
}
});
}
},
'json'
);
return false;
});
$('#design_form').on( 'submit' ,function() {
var _this = this;
//Validate First form data
$.post(
$( this ).prop( 'action' ),
{
"_token": $( this ).find( 'input[name=_token]' ).val(),
"category_id": $( '#form_category_id' ).val(),
"title": $( '#form_title' ).val(),
"user_id": $( '#form_user_id' ).val(),
},
function( data ) {
//if validate fail
if(data.status=='fail')
{
alert('data.status');
}
//if validate pass
else
{
//Sent second data
$.post("designs/saveimage",
{
"_token": $( _this ).find( 'input[name=_token]' ).val(),
'base64_image': yourDesigner.getProductDataURL()
}, function(data) {
if(data) {
alert(JSON.stringify(data));
}
else {
alert('fail!');
}
});
}
},
'json'
);
return false;
});
添加新行:
var _this = this;
並在第二次發送:
"_token": $( _this ).find( 'input[name=_token]' ).val()
在第二個ajax帖子上,您必須指示主持人
如果在js文件中,則必須指定主機
$.post("http://www.host.com/public/designs/saveimage")
如果在視野中
$.post("{{URL::to('designs/saveimage')}}");
您應使用firefox中的firebug或google chrome中的控制台檢查發布的位置以及路由是否正確。 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.