php ajax报404,AJAX - 404 with Slim PHP

I have worked with Slim Framework ;)

Look, this is how I have managed to make Ajax work with Slim framework.

First, you have to declare the routes both get and post (when I first tried declaring post only, it didn't work):

GET:

$app->get('/your/url',$permission(),function() use ($app){

//here you can check whether it is an ajax call

})->name('your.url');

POST:

$app->post('/your/url',$permission(),function() use ($app){

//get the data:

$request = $app->request;/*getting post data*/

$var1 = $request->post('var1');

$var2 = $request->post('var2');

//echo '| For log and testing purposes you can echo out the gotten values. Var1: '.$var1.'. Var2: '.$var2;

//DO YOUR STUFF here, for example, database processing with Eloquent ORM

$saved=$user->save();

if($saved){ echo '[success]';}else{echo '[error]';}/*http://stackoverflow.com/a/27878102/1883256*/

})->name('your.url.post');

Now, from the view side, make your ajax like this:

/*Referencias: https://www.codecourse.com/forum/topics/use-jquery-ajax-post-with-the-authentication-series/527*/

/*Permissions*/

$(function() {

$('#your_element').change(function(){

var var1 = this.val1;

var var2 = this.val2;

console.log('Value1 is: '+var1+' and value2 is: '+var2);

$.ajax({

data: {var1: var1,var2: var2,{{ csrf_key }}: "{{ csrf_token }}"},

type: "POST",

dataType: "json",

headers: { "cache-control": "no-cache" },

url: "/your/url" //add ../your/url if needed

});//ajax end

});

});

});

That's it.

It is also important that you send the csrf token if you're using it in your forms.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值