如何使用AJAX POST到Slim框架?

问题描述:

I'm using slim framework with eloquent to talk to the db. I'm trying to make a simple post ajax request that posts the data to db. so I have this route:

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

which is resolved by this controller

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


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

I tried something like this:

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

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

but I don't think this is the right way to do this. I'm still pretty new to this so pardon me if I'm missing something obvious. I can't find a good example of how to ajax stuff with slim, and I've been stuck on how to do this for a few hours now, so I'd greatly appreciate it if someone could point me in the right direction

我正在使用苗条的框架与eloquent交谈数据库。 我正在尝试制作一个简单的发布ajax请求,将数据发布到db。 我有这条路线: p>

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

由此控制器解析 p>

  public function postYell($ request,$ response)
 {
 $ yell = Yell :: create([
'body'=> $ request-> getParam('  yellBody'),
'user_id'=> $ _SESSION ['user'],
]); 
 
 
返回$ response-> withRedirect($ _ SERVER ['HTTP_REFERER']); 
}  
  code>  pre> 
 
 

我尝试过这样的事情: p>

  $(“。postYell”)。submit(function()  {
 $ .ajax(
 {
 url:“/ yell”,
 type:'POST',
 data:{
“_method”:'POST',
},
成功:  function()
 {
 console.log(“it Work”); 
} 
}); 
 
 console.log(“失败”); 
}); 
  code  >  pre> 
 
 

但我不认为这是正确的方法。 如果我遗漏了一些显而易见的东西,我仍然很陌生。 我找不到一个很好的例子,说明如何使用纤薄的东西,我已经被困在如何做几个小时了,所以如果有人能指出我正确的方向,我会非常感激 div>

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

And then in your controller, don't redirect when it is through 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'));
    }
}

Then follow up with the configuration in your AJAX request to send the correct data value (jQuery.ajax automatically adds the X-Requested-With: XMLHttpRequest as documented here under "headers")

$('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!');
        }
    });
});

As per Slim3 documentation

if ($request->isXhr()) {
        return $response;
    }

is a great way to ascertain if the request was from a JQuery AJAX call

vote up