Question

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 ?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top