Answer the question
In order to leave comments, you need to log in
How to execute php function via ajax and then return response from php?
I decided to create a blog where the admin posts all sorts of different news. Each news has a number of likes and views, and when I click on the like button, it is set, but the page is completely reloaded. More recently, I learned that using ajax you can execute a php script without refreshing the page. And I had a question "how?". I rummaged through the entire Internet, but did not find the answer, or if I did, I simply did not understand. Could anyone know how to write a code example for me and have php return and display data on the page after executing a script like:
<?php
if($like=='1'){
echo 'Liked!';
}else{
echo 'An error has occurred!';
}
?>
Answer the question
In order to leave comments, you need to log in
Ajax is used through js, but from the point of view of the backend, it is just a request that needs to be answered. Of course, it is better to answer not with layout, but with something convenient and understandable in js code, for example, json with data.
I suggest starting from here:
https://learn.javascript.ru/fetch
Regarding the php code, I suggest this option:
<?php
//... some code about 'like'
echo json_encode($likeProcessingResult);
?>
Hello. All you need to do is send a request from a javascript to some URL (roughly speaking, a page). In the javascript file, make a request via XMLHttpRequest (google right now the articles from MDN - the creators of the firefox browser - everything is very well written there), in this request in the code write the json that you pass to the server from the front (for example, like "{"likesCount": 42 }"). For example, you made a request to the php file server.php, where you have code with an UPDATE function (if using MySQL) that updates the likes on articles. You need to parse this json and insert likesCount into this function.
And on the page itself, on the front, you can display likes, for example,
<span class="likes-count"><?php echo $likesCount ?></span>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question