Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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!



50.9k
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.phalconphp.com/en/latest/api/Phalcon%5Http%5Request.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().



50.9k
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.



7.0k
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! :)