Shawn Javadi Shawn Javadi - 18 days ago 8
Ajax Question

How to POST to Slim framework with AJAX?

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

Answer
// 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!');
        }
    });
});