How to upload image from VueJS to phpMyAdmin with axios? - php

In my owner.vue, the admins are allowed to add owner into the table called "owner". For now, the owner's name can be successfully add into the database, while the column of it for image is empty. I wanted to make the admin able to add image into it together with the owner's name.
Owner.vue
//template
<v-text-field v-model="ob_person_name" label="Owner name" outlined required></v-text-field>
<input type="file" ref="ob_personal_document">
<v-btn text #click="createContact()">Confirm</v-btn>
//script
<script>
export default {
data: function () {
return{
ob_person_name:'',
ob_acc_type:""
}
},
methods: {
createContact: function(){
if(this.$refs.form.validate()){
this.ob_personal_document = this.$refs.ob_personal_document.files[0];
let formData = new FormData();
formData.append('ob_person_name', this.ob_person_name)
formData.append('ob_personal_document', this.ob_personal_document);
var owner = {};
formData.forEach(function(value, key){
owner[key] = value;
});
this.axios({
method: 'post',
url: 'http://www.example.com/process.php?action=create',
data: formData,
config: {
headers: {
'Content-Type':
'multipart/form-data'
}}
}).then(function (response) {
console.log(response)
this.newOwner.push(owner)
}).catch((error) => {
console.warn(error.message);
})
}
}
</script>
process.php
<?php
$host = '111.22.222.111';
$dbname = 'test';
$username = 'username';
$password = "password";
$conn = mysqli_connect($host, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed!" .mysqli_connect_error());
}
$result = array('error'=>false);
$action = '';
if(isset($_GET['action'])){
$action = $_GET['action'];
}
if($action == 'read'){
$sql = $conn->query("SELECT * FROM owners");
$owners = array();
while($row = $sql->fetch_assoc()){
array_push($owners, $row);
}
$result['owners'] = $owners;
}
if($action == 'create'){
$ob_person_name= $_POST['ob_person_name'];
$ob_personal_document = $_FILES['ob_personal_document'];
$sql = $conn->query("INSERT INTO owners (ob_person_name, ob_personal_document)
VALUES('$ob_person_name', '$ob_personal_document')");
if($sql){
$result['message'] = "Owner added successfully!";
}
else {
$result['error'] = true;
$result['message'] = "Failed to add owner";
}
}
The result of the image in phpMyAdmin shows "Array" as the image below.
the outcome of the ob_personal_document

I've solved the problem such by posting the image to the server's database and create folder directory and created another file.php
file.php
<?php
$ob_personal_document = $_FILES['ob_personal_document']['name'];
$valid_extensions = array("jpg","jpeg","png","pdf");
$extension = pathinfo($ob_personal_document, PATHINFO_EXTENSION);
if(in_array(strtolower($extension),$valid_extensions) ) {
if(move_uploaded_file($_FILES['ob_personal_document']['tmp_name'], "uploads/".$ob_personal_document)){
echo 1;
}else{
echo 0;
}
}else{
echo 0;
}
exit;
owner.vue
//template
<input type="file" id="ob_personal_document" ref="ob_personal_document" />
<button type="button" #click='uploadFile()' >Upload file</button>
//add another function after createContact
uploadFile: function(){
this.ob_personal_document = this.$refs.ob_personal_document.files[0];
let formData = new FormData();
formData.append('ob_personal_document', this.ob_personal_document);
this.axios.post('file.php', formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
if(!response.data){
alert('File not uploaded.');
}else{
alert('File uploaded successfully.');
}
})
.catch(function (error) {
console.log(error);
});
},
In this case, I've also added the name of the "image" to phpMyAdmin column to get the image that is same with the image's name in the storage.

Related

Uploading Image with Bio to PHP via AJAX jQuery

I want to upload User images via AJAX to PHP Database. I tried multiple tutorials and other examples but nothing worked for my code. The codes work when used without AJAX but since I don't wish my users to see the upload page and stay on the same page that's why the thought of adding AJAX to the code. So have been trying this code for the past few hours but nothing worked in my favor. The files are not getting uploaded nor the data in the database is getting updated.
file: test.php
<script>
function triggerClick(e) { document.querySelector('#profileImage').click(); }
function displayImage(e) { if (e.files[0]) {
var reader = new FileReader();
reader.onload = function(e){
document.querySelector('#profileDisplay').setAttribute('src', e.target.result);
}
reader.readAsDataURL(e.files[0]); } }
$(document).on('click',"#UploadImage", function(){
var fd = new FormData();
var profileImage = $('#profileImage')[0].files[0];
//fd.append('profileImage',profileImage);
var bio = document.getElementById( "bio" ).value;
$.ajax({
url:"include/Upload.php",
method:"POST",
data: fd,
contentType: false,
processData: false,
success:function(data){
alert(data);
if(data == "Login Successful") {
}
else {
alert(data);
}
}
})
});
</script>
File : Upload .php
<?php
session_start();
include('connection.php');
$msg = "";
$msg_class = "";
$Username = $_SESSION['Username'];
//echo var_dump($Username);
$conn = mysqli_connect("localhost", "root", "1234567890", "test");
$Status = stripslashes($_POST['bio']);
echo var_dump($Status);
$profileImageName = $Username. '-' . time() . '-' . $_FILES['profileImage']['name'];
echo var_dump($profileImageName);
$target_dir = "../UserImages/";
$target_file = $target_dir . basename($profileImageName);
if($_FILES['profileImage']['size'] > 200000) {
$msg = "Image size should not be greated than 200Kb";
$msg_class = "alert-danger";
}
// check if file exists
if(file_exists($target_file)) {
$msg = "File already exists";
$msg_class = "alert-danger";
}
// Upload image only if no errors
if (empty($error)) {
if(move_uploaded_file($_FILES["profileImage"]["tmp_name"], $target_file)) {
$sql = "UPDATE users_login SET Image='$profileImageName', Status='$Status' WHERE Username='$Username'";
echo var_dump($sql);
//header("location: profiles.php")
if(mysqli_query($conn, $sql)){
session_start();
$query="select * from $dbtable WHERE Username = '".$Username."' ";
echo $query;
$result2=#mysqli_query($connection,$query);
$row=mysqli_fetch_assoc($result2);
$_SESSION['ProfileImage']= $row['Image'];
print_r($_SESSION['ProfileImage']);
$_SESSION['Status']= $row['Status'];
$msg = "Image uploaded and saved in the Database";
$msg_class = "alert-success";
} else {
$msg = "There was an error in the database";
$msg_class = "alert-danger";
}
} else {
$error = "There was an error uploading the file";
$msg = "alert-danger";
}
}
?>
Removing those comments // worked and had to add another append line for bio and it worked. It wasn't working yesterday that's why I commented // on it. It's working properly now! Here's my new code that made it work...
var fd = new FormData();
var profileImage = $('#profileImage')[0].files[0];
fd.append('profileImage',profileImage);
var bio = document.getElementById( "bio" ).value;
fd.append('bio', bio);
Credits to: Ken Lee & charlietfl for their comments.

How to redirect from view to another view

I try to make an authentication using angualrJS and php. I tested it by console.log, when the password is incorrect I get error message, and when the password is correct I don't get anything, in this case, I want to be riderected to other view, how can I do please:
app.js
app.controller('loginCtrl', function($scope, $location,$state,$http,$window){
$scope.submit = function()
{
data = {
'NomClient' : $scope.NomClient,
'mdp' : $scope.mdp
};
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config)
{
// $window.location.href = '#/admin';
console.log(data);
})
.error(function(data, status, headers, config)
{
console.log('error');
});
}
});
login.php
<?php
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "test");
if(count($data) > 0)
{
$NomClient=mysqli_real_escape_string($connect, $data->NomClient);
$mdp=mysqli_real_escape_string($connect, $data->mdp);
$query = 'SELECT * FROM `client` WHERE NomClient = "'.$NomClient.'" AND mdp= "'.$mdp.'"';
$q = mysqli_query($connect , $query);
if(mysqli_num_rows($q) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
}
else
{
echo 'The username or password are incorrect!';
}
}
?>
As you see, I have a comment line in app.js: // $window.location.href = '#/admin'; I put it as comment because when I put it, it redirects me to admin view however the password is incorrect.
Thanks in advance
With AngularJS you can use the $location service
$Location - Documentation
Try using:
$location.path("your new path here")
For an example: please refer to the following answer to another post:
https://stackoverflow.com/a/14387747/7018180
Try this code in login.php
if(mysqli_num_rows($q) > 0 )
{
$_SESSION["logged_in"] = true;
$_SESSION["naam"] = $NomClient;
$result['code'] = 200;
$result['message'] ='Logged In';
}
else
{
$result['code'] = 603;
$result['message'] ='The username or password are incorrect!';
}
$resultstring = json_encode($result);
$resultstring = str_replace("null",'""',$resultstring);
echo $resultstring ;
die;
And check result code in js if it is 200 then it will be in succes other wise in error.
Change .success\.error to .then(), Change your code like :
$http.post('http://localhost/deb/login.php', data).then(function(response) {
console.log(response.data);
$window.location.href = '#/admin';
}, function(error) {
console.log('error');
});
.success is a property of $http service so if there would be some value in data variable the $window.location is eventually going to get called.. so to improve that you can use if condition inside $http service which would check the passed username and password with the response that it would get from the service and then in if condition you can redirect it to another page.
app.service('AuthenticationService', function ($http, $window){
this.login = function (username, password) {
return $http({
url: 'http://localhost/deb/login.php',
method: 'POST',
params: {
NomClient : username,
mdp : password
}
})
};
});
app.controller('loginCtrl', function ($scope, $state, $http, $window, AuthenticationService, $remember) {
$scope.submit = function()
{
AuthenticationService.login($scope.NomClient,$scope.mdp)
.then(function(response) {
if (response.data.NomClient == $scope.NomClient && response.data.mdp == $scope.mdp)
{
$state.go('application.home');
}
else {
alert('Credentials do not match our records. Please try again.');
}
})
}
});
and instead of $window.location you can use $state.go functionality of angularJS. It would redirect your page to the specific state that would be mentioned and it would look for that state in route file and would execute that state along with its templateUrl and controller.
Here's properly working code for your question tested properly. if you are still looking for a solution
app.js
app.controller('loginCtrl', function ($scope, $http,$state) {
$scope.submit = function ()
{
$scope.data = {
username: $scope.username,
password: $scope.password
}
$http.post('http://localhost/HTML5Application/public_html/login.php', {serviceData: $scope.data})
.success(function (data) {
alert(data);
$state.go('newState');
})
.error(function (data) {
alert("problem with service call");
});
};
});
login.php
$data = json_decode(file_get_contents("php://input"));
$connect = mysqli_connect("localhost", "root", "", "embroidery");
if (count($data) > 0) {
$username = mysqli_real_escape_string($connect, $data->serviceData->username);
$password = mysqli_real_escape_string($connect, $data->serviceData->password);
$query = 'SELECT * FROM `client` WHERE username = "' . $username . '" AND password= "' . $password . '"';
$q = mysqli_query($connect, $query);
if (mysqli_num_rows($q) > 0) {
$_SESSION["logged_in"] = true;
$_SESSION["name"] = $username;
echo $_SESSION["name"];
} else {
echo 'The username or password are incorrect!';
}
}
?>
login.html
<div class="list list-inset" ng-controller="loginCtrl">
<label class="item item-input">
<input type="text" placeholder="Username" required="" ng-model="username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="password">
</label>
<button class="button button-block button-positive" name="submit" ng-click="submit()">Login</button>
</div>
Thank you all, this is the solution of this question, solved by "Mr_Perfect":
we have just to add a condittion in suceess:
$http.post('http://localhost/deb/login.php', data)
.success(function(data, status, headers, config,result)
{
console.log(data);
if(data.code == 200){
$state.go('admin');
}
})
.error(function(data, status, headers, config, rsult)
{
console.log('error');
});
Thanks to you all

Check Barcode valid from phonegab android to remote phpfile

I can read Qrcode and what i want is to check if the text in qrcode is in remote database. I have a php file where I do some process to check if database is in mysql. But it does not work. below my code
/*part of js file
scan: function() {
console.log('scanning');
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan( function (result) {
var rs= result;
$.ajax({
type: 'POST',
data: rs,
url: 'http://url/page.php',
success: function(data){
console.log(data);
document.getElementById("info").innerHTML = data;
},
error: function(){
console.log(data);
alert('error');
}
});
return false;
}, function (error) {
console.log("Scanning failed: ", error);
} );
}
/* My php file
<?php
// Create connection
$conn = mysql_connect($servername, $username, $password);
mysql_select_db("database", $conn);
$result=$_POST['result'] ; //value from qrcode scanned by device
$sql="SELECT * FROM tabe WHERE code = '$result' ";
$rs = mysql_query($sql,$conn);
$count=mysql_num_rows($rs);
if($count == 1) {
echo "ok";
}
else
{
return "No Ok";
}
?>

how to use ajax in wordpress to show database columns using php and Json

I'm new using ajax and I have a code to display from wordpress some information from database columns.
I have this PHP code to connect with the database and create the JSON file:
<?php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
?>
In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()
<script type="text/javascript"> function doLogin(){
data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: "Mywebsiteurl.php",
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
} </script>
I need to show in <div id="forma"> a kind of list usign html, for example:
Id: VALUE ID
Name: VALUE NAME
and more information...
When i try to print in my website the required information using $('#forma').html(data); I obtain error or just an empty space.
How can I fix it? thanks.
In WordPress we need to hook the ajax hook to your check_user function here.
add_action('wp_ajax_your_action_from_js', 'your_function');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');
Check below code for how it is done regarding your context.
In functions.php
function check_user() {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
}
add_action('wp_ajax_check_user', 'check_user');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_check_user', 'check_user');
In your JS called file.
In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.
<script type="text/javascript">
function doLogin(){
data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: ajax_url,
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/
CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins
WordPress has specific methods to enable ajax requests.
// registering ajax request for Logged users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// registering ajax request also for public area
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback()
{
// Your code here
wp_die(); // this is required to terminate immediately and return a proper response
}
To call it:
jQuery(document).ready(function($) {
var data = {action: "my_action", username: jQuery("#user").val(), password: jQuery("#pass").val()}
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: data,
method: 'POST',
success: function(response) {
console.log(response);
},
error: function(a,b,c) {
}
});
});
Source: https://codex.wordpress.org/AJAX_in_Plugins

Ajax display response in blank page

After submitting a form with ajax the returned result appears on a new page. The chrome console returns me an error in almost every element: it is not a function validates, but php insert them and shows the result displayed in this new page.
$(document).ready(function () {
$('#newsletter').submit(function(e){
var $this = $(this);
e.preventDefault();
$response = $('#response'),
$mail = $('#email'),
testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
hasError = false;
$response.find('p').remove();
if (!testmail.test($mail.val())) {
$response.html('<p class="error">Please enter a valid email</p>');
hasError = true;
}
if (hasError === false) {
$response.find('p').remove();
$response.addClass('loading');
$.ajax({
type: "POST",
dataType: 'json',
cache: false,
url: $this.attr('action'),
data: $this.serialize()
}).done(function (data) {
console.log(data);
$response.removeClass('loading');
$response.html('<p>'+data.message+'</p>');
}).fail(function() {
$response.removeClass('loading');
$response.html('<p>An error occurred, please try again</p>');
})
}
return false;
});
});
php code
<?php
$host = "";
$dbname = "";
$user = "";
$pass = "";
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$datetime = date('Y-m-d H:i:s');
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
if (empty($email)) {
$status = "error";
$message = "The email address field must not be blank";
} else if (!preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email)) {
$status = "error";
$message = "You must fill the field with a valid email address";
} else {
$existingSignup = $db->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
$existingSignup->execute();
$data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;
if (!$data_exists) {
$sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
$q = $db->prepare($sql);
$q->execute(
array(
':email' => $email,
':datetime' => $datetime
));
if ($q) {
$status = "success";
$message = "You have been successfully subscribed";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already subscribed";
}
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
$db = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
The error displayed: undefinied is not a function in
$response = $('#response'),
$mail = $('#email'),
var $this = $(this);
Message displayed in blank page:
{"status":"success","message":"You have been successfully subscribed"}
Solved. Now works fine in another way, but I would like to know the mistake.
This works
(function ($, window, document, undefined) {
'use strict';
var $form = $('#newsletter');
var $response = $('#response');
$form.submit(function (e) {
var formData = {
'news' : $('input[name="news"]').val(),
'email' : $('input[name="email"]').val(),
};
$.ajax({
type : 'POST',
url : 'news.php',
data : formData,
dataType : 'json',
encode : true
}).done(function (data) {
if (!data.success) {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
} else {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
}
}).fail(function (data) {
response.html('<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));

Categories