J
J
Junior2018-04-25 19:42:58
AJAX
Junior, 2018-04-25 19:42:58

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

3 answer(s)
J
JimmDiGreez, 2018-04-25
@IT-Programmer

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);
?>

A
Alexey Dzyuba, 2018-04-25
@Alex_Dz

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>

F
frees2, 2018-04-25
@frees2

How to implement Load more button in js ajax request?
From the function, we send a request to the file being loaded, for example, we get new information from some third-party tape, process it and send it back again, then we can send it back again ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question