Data selection is one of the basic requirements when creating a dynamic website.
Mainly data is fetched from the database on page refresh but without page refresh require to send AJAX request.
I am using the Axios package to send the AJAX request.
In this tutorial, I show how you can fetch records from MySQL database using Vue.js and PHP with the Axios package.

Contents
1. Table structure
I am using users table in the example.
CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(100) NOT NULL, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Configuration
Create a new config.php file for the database configuration.
Completed Code
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
3. Download & Include
- Download Axios package from GitHub. or you can also use CDN (https://unpkg.com/axios/dist/axios.min.js).
- Now, include
axios.min.jswithvue.jsin the<head>section.
<script src="vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
4. HTML
Create two buttons and a textbox.
On the first button define @click='allRecords()' and on the second define @click='recordByID()' events.
Add v-model='userid' in the textbox.
Use v-for='user in users' on <tr> to list records.
- The first button is used to send a GET request without a parameter.
- The second button is used to send a GET request with parameters.
Completed Code
<div id='myapp'>
<!-- Select All records -->
<input type='button' @click='allRecords()' value='Select All users'>
<br><br>
<!-- Select record by ID -->
<input type='text' v-model='userid' placeholder="Enter Userid between 1 - 24">
<input type='button' @click='recordByID()' value='Select user by ID'>
<br><br>
<!-- List records -->
<table border='1' width='80%' style='border-collapse: collapse;'>
<tr>
<th>Username</th>
<th>Name</th>
<th>Email</th>
</tr>
<tr v-for='user in users'>
<td>{{ user.username }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
</tr>
</table>
</div>
5. PHP
Create a new ajaxfile.php.
Fetch records from the users table and initialize $response Array.
Assign " id =".$_GET['userid'] to $where if $_GET['userid'] is passed.
Return $response in JSON response.
Completed Code
<?php
include "config.php";
$condition = "1";
if(isset($_GET['userid'])){
$condition = " id=".$_GET['userid'];
}
$userData = mysqli_query($con,"select * from users WHERE ".$condition);
$response = array();
while($row = mysqli_fetch_assoc($userData)){
$response[] = $row;
}
echo json_encode($response);
exit;
6. Script
Syntax – Axios GET request without parameter –
axios.get('path')
.then(function(response){
// Handle response
}).catch(function(error){
// Error handling
});
Syntax – Axios GET request with parameter –
axios.get('path',{
params:{
parameter1: value,
parameter2: value,
....
}
})
.then(function(response){
// Handle response
}).catch(function(error){
// Error handling
});
OR
axios.get('path?variable1=value1&variable2=value2&...')
.then(function(response){
// Handle response
}).catch(function(error){
// Error handling
});
Define two variable users and userid.
Define two methods –
- allRecords – Send AJAX request to fetch all records and assign
response.datatoapp.users. Here,app.userspointing to defineddatavariable. - recordByID – Pass the textbox value
this.useridinparams: {. Assign
userid: this.userid }response.datainapp.userson successful callback.
Completed Code
var app = new Vue({
el: '#myapp',
data: {
users: "",
userid: 0
},
methods: {
allRecords: function(){
axios.get('ajaxfile.php')
.then(function (response) {
app.users = response.data;
})
.catch(function (error) {
console.log(error);
});
},
recordByID: function(){
if(this.userid > 0){
axios.get('ajaxfile.php', {
params: {
userid: this.userid
}
})
.then(function (response) {
app.users = response.data;
})
.catch(function (error) {
console.log(error);
});
}
}
}
})
7. Demo
8. Conclusion
Use params option to pass data to AJAX request or you can directly pass it with the path.
Hello Yogesh
thank for this wonderful tutorial.
I have a probleme , i copied this source but when i try the form i have not the username, name,email, are not displayed, only the rows of the table diplayed but see empty.
Thank for your help
Hello Yogesh,
just to say that I tested the site online, and it does not work either
Regards.
sorry I forgot to put the link
http://laruche-asso.nexgate.ch/test/index2.html
thank for help Yogesh
Hi Yogesh ,
I put an echo on the json encode and it seems to work
i have this output from ajaxfile.php
{“id”:”1″,”username”:”yssyogesh”,”name”:”Yogesh singh”,”email”:”yssyogesh_gmail.com”}{“id”:”2″,”username”:”sonarika”,”name”:”Sonarika”,”email”:”sonarika_gmail.com”}{“id”:”3″,”username”:”vishal”,”name”:”Vishal Sahu”,”email”:”vishal_gmail.com”} etc..
but this data do not show in the div
thank Yogesh to take time to explain why your code does not work in my localhost
Hi Yogesh,
I modified the ajaxfile.php file a bit and it works now. ( i use PDO)
at the end of the script before the loop :
$result = [];
and
congratulations for your excellent tutorial !
Hi Serna,
I have the same problem with ajaxfile.php, I would try your solution, but I haven’t understud you modification in ajaxfile.php
Could you explain what you made?
Many thanks
Aldo
Hi! I’m having trouble getting this to run. I keep getting a 404 error:
spread.js:25 GET http://localhost:8080/ajaxfile.php?username=janeDoe&password=1234 404 (Not Found)
It seems there is something wrong with the line of code where it says axios.get(….).
Here’s my code:
login: function(){
axios.get(‘ajaxfile.php’ , {
params: {
username: this.username,
password: this.password
}
})
.then(function (response) {
//app.users = response.data;
// console.log(response);
console.log(‘success : ‘ + JSON.stringify(response.data) );
})
.catch(function (error) {
console.log(error);
});
},
someone please help! I’ve been working on this for hours…..Thank you
Thank you for this tutorial i find it very useful for me because i try to learn some code.
1)Can please anyone tell me how to make the text at the form as a dropmenu? I dont want to write 1,2,3….. but to have a dropmenu?
2)Also is it possible to remove button and show the results instantly without press the button when select a user id at dropmenu?
Thank you!
Really good tutorial – this is very helpful! 🙂
Good Tutorial for VueJS beginners, It helped lots for me.
Thanks, great start for me moving from jQuery ajax to Vue/axios 🙂
Is there a Create and Update tutorials as well?
Or is it just to use POST?
Greetings
Henning
./imgpath/(php-code-value).png
Thank you for this. I’m transition from a “functions” (I think it’s called) PHP mindset of PHP 4,5,7 and been eager to learn a JS Framework. This article has really helped me get a better handle on Vuejs/ JS Frameworks.
Thanks very much. 🙂
Hi,
thanks for this great tutorial! 🙂
I don’t think this topic could be explained any easier!
–> Except for the code snippets and a github link would not hurt!
Hi Yogesh,
I’m having some difficulties, I never worked with PHP before.
I have done exactly as you did, but for some reason instead of returning values from a database it returns the content of the ajaxfile.php itself inside response.data . Do you have any idea why it is doing this?
Thanks for your videos, they were really helpful to learn PHP with Vue.
Have you solved this problem? I have the same problem.
Grettings Yogesh!
I’m having a problem echoing the json_encode result into my VueJS app.
It’s printing the file rather than the json_encode result.
What am I doing wrong?
This is the console log result:
success : ” false);\r\n\r\n$result = $conn->query(\”SELECT * FROM `menu_temas`\”);\r\n$menu_temas = array();\r\n\r\nwhile ($row = $result->fetch_assoc()) {\r\n $menu_temas[] = $row;\r\n}\r\n\r\necho json_encode($menu_temas);\r\nexit;”
Thank you for the tutorial, it was very clear 🙂
Thanks for this tutorial, but finally i only get “network error” from axios.. running the php scripts manually works fine. Maybe i’ll find a solution sometimes