2016-11-21 71 views
0

我正在使用苗條的框架與雄辯說話數據庫。我試圖做一個簡單的張貼ajax請求數據到數據庫。 所以我有這樣的路線:如何使用AJAX發佈到Slim框架?

//post yell 
$app->post('/yell', 'UserController:postYell')->setName('yell'); 

這是由該控制器

public function postYell($request, $response) 
{ 
$yell = Yell::create([ 
    'body' => $request->getParam('yellBody'), 
    'user_id' => $_SESSION['user'], 
]); 


return $response->withRedirect($_SERVER['HTTP_REFERER']); 
} 

我想是這樣解決的:

$(".postYell").submit(function(){ 
    $.ajax(
    { 
     url: "/yell", 
     type: 'POST', 
     data: { 
      "_method": 'POST', 
     }, 
     success: function() 
     { 
      console.log("it Work"); 
     } 
    }); 

    console.log("It failed"); 
}); 

,但我不認爲這是正確的這樣做的方法。如果我錯過了一些明顯的東西,我對這件事還是很新的,所以請原諒我。我找不到一個很好的例子,說明如何使用ajax瘦身,而且我一直在困擾着如何在幾個小時內完成這個任務,所以如果有人能夠指出我正確的方向,我將不勝感激

+1

首先你忘了防止默認提交事件,第二要重定向在你的PHP ajaxed功能 – madalinivascu

+1

你的第二個控制檯日誌是在提交處理程序的根目錄,這樣它會隨時登錄「它沒有」 –

回答

3
// Make sure you specify a valid callable with two ':' 
$app->post('/yell', 'UserController::postYell')->setName('yell'); 

然後在你的控制器時,它是通過XHR,不重定向:

public function postYell(Request $request, Response $response) : Response 
{ 
    $yell = Yell::create([ 
     'body' => $request->getParam('yellBody'), 
     'user_id' => $_SESSION['user'] 
    ]); 

    if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') { 
     return $response; 
    } else { 
     return $response->withRedirect($request->getHeader('Referer')); 
    } 
} 

然後在你的AJAX請求發送正確的數據值(jQuery的配置跟進。 ajax自動將X-Requested-With: XMLHttpRequest添加爲「標題」下的here文檔)

$('form.postYell').submit(function (e) { 
    // prevent the page from submitting like normal 
    e.preventDefault(); 

    $.ajax({ 
     url: '/yell', 
     type: 'POST', 
     data: $(this).serialize(), 
     success: function() { 
      console.log('it worked!'); 
     }, 
     error: function() { 
      console.log('it failed!'); 
     } 
    }); 
});