0

i'm completely new to WordPress ajax . i'm working on new custom template . there is a custom form which stores data on custom database . for search section i need to use Ajax . then i found one way , that is create new template page which called json.php for example . it echoing the data in json formating .

is that way correct way for using ajax ? what's the better way ? anyone can help me please ?

1 Answer 1

0

then i found one way , that is create new template page which called json.php for example . it echoing the data in json formating .

No. You should never make direct requests to php files inside a theme or plugin, and you don't need to create page templates to handle AJAX requests.

If you need to handle a form, make the request to the same page that served the form and inspect the POST/GET variables.

If you need to make an AJAX request using javascript, do it to the REST API. You can register an endpoint URL with a pretty url that will respond with JSON that can be easily processed in javascript.

When registering the endpoint, you tell it the name you want for the URL, e.g. /wp-json/hossein/v1/searchdatabase, and you tell it a function to call when it's used. That function is where you do the searching of your database, and you return the data you want to send to the browser.

2
  • you save me from darkness bro ! tnx a lot and be lucky ...
    – hossein
    Commented May 5, 2021 at 14:52
  • if this answers your question could you mark it as the correct answer? it's the tick/check under the voting controls
    – Tom J Nowell
    Commented May 5, 2021 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.