how use ajax to custom page template

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 ?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x