We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 24629
    • 370 Posts
    Hi,
    I'm thinking of building a tool, service, to which i'll send some data with an ajax call and it returns an array of objects. (it will be a storelocator, but thats not relevant for the question).
    What would be the best way of communicating with modx from my Ajax call?
    - I can write a snippet, put it on a page and use that url for my ajax call. Seems a bit clunky to me
    - i could setup a REST server and (ab)use the GET to send my data and receive my objects back?
    Or maybe there is another typical MODx way of doing this?

    Tnx
    RDG
      • 38850
      • 110 Posts
      If you need to script something to "send back data" then you're obviously dealing with code, no matter how you do it. So coding through a snippet that is linked to a resource is certainly possible. The MODX docs have specific instructions on setting up a RESTful API, you can go that route.
      You can also use the MODX API directly and bypass the entire manager and resources and everything by just putting your code in it's own PHP file like /root/myapi.php. You can find docs on using the MODX API (if you even need it?).

      Remember, a resource can return any data type, so the ability of your resource to return JSON data is just built right in. It's not that clunky, you don't have to select a template, just leave the template empty, then set the data type to JSON, then use your snippet to handle calls to that endpoint. You never know, you might like it!
        • 24629
        • 370 Posts
        Hi Vigilante,
        I setup a RESTful API and that works. I just can't figure out how to get the $_GET in my read() function it seems to to take only an $id . thats why i broke off that route. Any idea howto get the $_GET vars in the 'MyControllerRestClass' ?? The RTFM is not very extensive on the subject.
        Putting a snippet on a resource certainly isn't 'bad', and it is the way i'm doing it now. but because the endpoints show up as resources in the tree it just didn't feel elegant. Maybe ill just create a resource 'service' and put all my resourced endpoints beneath it smiley
        I was merely wandering if MODX maybe had something i was overlooking, built in to make this happen.
        I'll have a look at the MODX API. I never used that approach so it will be a challange.
        tnx
        RDG
          • 38850
          • 110 Posts
          There are many ways to do anything. Some people might create and entire Context to organize their API endpoints. Or you could create a resource as a parent with all endpoints under it. Then for snippets you could create a category for API and put all your API snippets under that.

          I'm not sure about GET with the REST stuff, I would think that in your PHP code you can just access $_GET directly?