How to POST to Slim framework with AJAX? - php

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

// 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

Related

OpenCart 3 - AJAX Query is not working (Invalid token session)

I try to make POST-request to method of admin controller using AJAX (from admin part). My JS code:
<script>
$(".remove-request-btn").on('click', function () {
let request_id = $(this).data('request-id');
let confirm_result = confirm('Are you sure you want to delete this request?');
if (confirm_result) {
$.ajax({
url: 'index.php?route=extension/x_feedback/settings/removeRequest&token={{ token }}',
method: 'post',
dataType: 'json',
data: {request_id: 11},
success: function(data) {
if (data.status === 'ok') {
location.reload();
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
My method:
public function removeRequest()
{
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode(
[
'status' => 'ok'
]
));
}
I expect json in the response but get following:
I tried to add admin into the url like '/admin/index.php?route=extension/x_feedback/button/feedbackRequest&token={{ token }}'
But it doesn't help. Can you help me please what I'm doing wrong? Thank you!
1-please add bellow code into controller method
$data['token'] = $this->session->data['user_token'];
2- use javascript into .twig file - not external js file.
In OC3 is used user_token instead token
so you must use this url:
url: 'index.php?route=extension/x_feedback/settings/removeRequest&user_token={{ user_token }}',
And do not forget declare user_token in the corresponding controller file:
$data['user_token'] = $this->session->data['user_token'];

Passing data via ajax issues

I'm trying to pass data to my laravel controller function via Ajax. At this point I just want to return the data being sent to verify ajax is working. I can "GET" with ajax, but when I try to "POST" ajax brakes.
Could someone please tell me what I'm doing wrong? Thank you.
Here is my ajax code...
var startMapLocation = { startCity: "Cleveland", startStat: "Oh" };
$.ajax({
type: "POST",
url: url,
data: startMapLocation,
success: function(data, status) {
//alert(data);
console.log("success:", data);
},
error: function() {
alert("Ajax Broke!" + status);
}
});
My laravel function is...
public function postphp( Request $request)
{
$a = $request->all();
$city = $a["startCity"];
return json_encode( $city );
}
Thanks every one for your help. To resolve this issue, I first had to verify that my route was a post route not a get route.
Route::post('/postphp', 'GSResultController#postphp');
I also need to get my csrf-token and add it to the ajax call.
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
This fixed my problem.

FUELPHP Ajax request without jquery

I have looked everywhere, I found, that FUELPHP not handle Ajax requests, native and easily, as does RubyOnRails for example.
There must be done manually through jquery, unless I'm missing something I see is this: you have to use preventDefault () for the submit event of the form to create a post, product or whatever, and use the $ function post () to send the relevant parameters, which I think is ridiculous for a framework that claims to be based on the best ideas from other frameworks.
Please tell me if I'm wrong, I like FUELPHP, and I'm thinking about choosing it as PHP framework, but I want to be clear about this.
why not you can handle ajax in fuelphp like this.
.01. create ajax request in your view or public/assets/ create javascript file,
<script> $('.login').on('click',function(){
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
alert("loading");
}, false);
return xhr;
},
url: "<?php echo \Uri::create('auth/login'); ?>",
type: "POST",
dataType: 'json'
data: {'username':$('#username').val(), 'password':$('#password').val()},
success: function (data) {
alert(data.status);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
});
</script>
.02. after that you can handle post data in classes/controller/ create auth.php and login method like this,
<?php
class Controller_Auth extends \Controller_Template {
function action_login() {
if (\Input::is_ajax()) {
if (\Input::param('username') and \Input::param('password')) {
$username = \Input::param('username');
$password = md5(\Input::param('password'));
//check password and username or anything
$msg = 'fail';
return json_encode(array('status' => $msg));
}
}
...
}
}
?>
you can handle data like this. i think you got something. and this is helpful.

php yii 2.0 new action in controller page not found 404

I'm using Yii 2.0 basic version and I need some help.
I created one ajax function like this:
function eliminarColaborador(id) {
$.ajax({
type: "GET",
async: false,
url: "<?= urldecode(Url::toRoute(['colaborador/ajaxEliminarColaborador'])) ?>",
dataType: 'json',
data: {
'id': id
},
complete: function ()
{
},
success: function (data) {
if (data !== null)
{
// SUCCESS
}
else
{
// ERROR
}
}
});
}
My action in controller:
public function actionAjaxEliminarColaborador($id) {
if (Yii::$app->request->isAjax) {
$continuar = false;
if(isset($id) && $id > 0) {
var_dump($model); die;
$continuar = true;
}
echo CJSON::encode(array('continuar'=>$continuar));
Yii::$app->end();
}
}
I'm getting this erro in firebug: Not Found (#404): Page not found.
I tried everything, but i can't figure out what's the problem.
If I change ajax url to urldecode(Url::toRoute(['colaborador/delete'])) the error is gone and all works just fine.
Maybe I need to declare in ColaboradorController my new action ajaxEliminarColaborador, but I don't know how.
What is wrong?
controller
public function actionAjaxEliminarColaborador(){}
ajax
urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador']))
It should be <?= urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador'])) ?>. Here you can learn why.
Change the ajax response with:
url: '/colaborador/ajaxEliminarColaborador/$id',
data: {id: $id,_csrf: yii.getCsrfToken()},
Try to remove the word 'ajax' on your url.

cakephp, jquery, .ajax()

I've been stuck with the retrieving of my sent variable trough an ajax POST function. Could you help me out?
My Jquery code:
$.ajaxSetup ({
cache: false
});
var selected = new Array();
$(document).ready(function() {
$('.value').click(function () {
if($(this).hasClass('strong'))
{
selected.splice(selected.indexOf(this.innerHTML), 1);
submitData(selected);
$(this).removeClass('strong');
}
else
{
selected.push(this.innerHTML);
submitData(selected);
$(this).addClass('strong')
}
});
});
function submitData(arDat) {
var arrayData = {"param1" : JSON.stringify(arDat)};
$.ajax({
type: 'POST',
url: 'http://localhost.local/coconut/trunk/challenges/values',
data: arrayData,
dataType: 'json',
success: function(data){
console.log(arrayData);
},
error: function(message){
alert(message);
}
});
}
My CakePHP Controller function:
function values() {
if ($this->RequestHandler->isAjax()) {
$this->autoRender = false;
Configure::write('debug', 0);
$params = json_decode($_POST['param1']);
//$result = json_encode($params);
$this->set('submitValue', $params);
} else {
$this->redirect(array('controller' => 'challenges', 'action' => 'index'));
}
}
And in a view.ctp file:
<?php debug($submitValue); ?>
But I get the following error:
Notice (8): Undefined variable: submitValue
In firebug I see this:
Parametersapplication/x-www-form-urlencoded
param1 ["Business","Life","Health"]
Source
param1=%5B%22Business%22%2C%22Life%22%2C%22Health%22%5D
Does anyone know what I'm doing wrong?
Thanks!
Edit:
A bit more clarification about what I want.. I want to use $this->set('submitValue', $params); (so $submitValue) elsewhere in another view.
The CakePHP function 'isAjax()' checks to see if a request is a Prototype Ajax request.
You aren't using Prototype, you're using jQuery - so presumably it's always returning false, and so submitValue is never set.

Categories