We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Get data from AJAX request

Hello!

I need to get data (just string) from my frontend. Send it to backend with this code:

$.post('/order/proceed', "data", function(data) {
    //Bla-bla-bla
});

And, well, I'm stuck - what request should be in controller? I mean $this->request->...?

Thank you!



85.5k
edited Nov '15

data as a string it has to be :

$.post('/order/proceed?data=somevalue', function(data) {
    //Bla-bla-bla
});

and then $request->getPost("data");

if data is object :


var data = {};
data.name = 'koko';
data.age = 15;

$.post('/order/proceed', data , function(data) {
    //Bla-bla-bla
});

in this case you will have $_POST['age'], And $_POST['name'];

https://docs.phalcon.io/en/latest/api/Phalcon_Http_Request.html

Actually you are wrong. getPost("data") is $_POST("data"), if you want retreive data from URL then use getQuery.

In the second option(json as body) use getJsonRawBody, if you would send some form(or formdata) then you can use getPost().



85.5k
edited Nov '15

mm yea, it is get in my first example, so $this->request->get('data')

mm yea, it is get in my first example, so $this->request->get('data')

Well only get may be vulnerable cuz it will find in POST,SESSION too.



8.1k
Accepted
answer

Send "just string" via post ajax request isn't good practice :) You can stringify post object at first.

$.post('/order/proceed', JSON.stringify({nameOfData : 'my_string'}), function(data) {
    //Bla-bla-bla
});

Then in controller

public function myAction ()
{
     $post_data = $this->request->getJsonRawBody();
}

Guys, thank you all very much! :)