Uploading Image with Bio to PHP via AJAX jQuery - php

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.

Related

How to upload image from VueJS to phpMyAdmin with axios?

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.

How to send php variable into angularjs function (different files)

I have a variable in php file reg.php. I want to send that variable into .js file in different place (app.reg.js). I tried a lot of solutions but they didn't work. I have to admit that I'm a new programmist, and this is my first own project in angularjs.
How my app exactly works :
In index.html i use routing to get to register.html (this working well).
register.html has a form app.reg.js sending it into reg.php
App.reg.js :
http://www.chopapp.com/#kpwad4zs (i'm getting ALL THE TIME "your post is not properly formatted as code -.-).
reg.php (it works fine! Just need variable $loginExist from it :
http://www.chopapp.com/#yvqivk5m
I would like to send variable from reg.php to the app.reg.js file. How to do this? I think i tried all of the solutions from here but non of them worked...
php file
session_start();
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$login = $request->login;
$password = $request->password;
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connect = new mysqli($host,$db_user,$db_password,$db_name);
if($connect->connect_errno!=0)
{
throw new Exception(mysqli_connect_errno());
} else {
//Does login exist?
$result = $connect->query("SELECT id FROM `users` WHERE login = '" . mysql_real_escape_string($login) . "'");
$login_count = $result->num_rows;
if($login_count>0) {
$loginExist = true;
}
else {
$loginExist = false;
$password = $login . $password;
$password = password_hash($password, PASSWORD_DEFAULT);
//$sql = "INSERT INTO users (login, password) VALUES ('$login','$password')";
$sql = "INSERT INTO users (login, password)VALUES('" . mysql_real_escape_string($login) . "', '" . mysql_real_escape_string($password) . "')";
if($connect->query($sql) === TRUE) {
echo "ok!";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
$connect->close();
}
} catch(Exception $e) {
echo 'Server error!';
}
echo json_encode(['res' => $loginExist]);
?>
js file
app.controller('regCtrl', function ($scope, $window, $http) {
$scope.send = function () {
var form = {
password: scopeToPasswordImput,
login: scopteToLoginImput
};
$http({
url:'reg1.php',
method: "POST",
data: form
}).then(function (response) {
if (response) {
//I Want to use php variable in this section
//$window.alert("");
console.log(response.data.res);
} else {
console.log("Network response was not ok.");
window.location.href = '/';
}
})
};
});

Error trying to search a video AJAX

I have created a code that allows you to search videos from the database. But everytime I write the video I want to search, in console, error appears... I really dont know why it doesnt print the result...
Could you help me?
I need help real fast
AJAX
$(document).ready(function($) {
var Search = function(title){ return $.post( "./include/php/busqueda_videos.php", { "title" : title }); }
$("#input_search").on('keyup', function(event) {
var output = "";
$(".videos_container").html("");
event.preventDefault();
var input = $("#input_search").val();
Search(input).done(function(response) {
if(response.success) {
$.each(response.videos, function(key, value) { var output = "<div class='video_main_container'><div class='video_container'><div class='video_thumb'><a data-id='"+value['id']+"'><img src='"+value['image']+"' alt='' /></a></div><div class='video_info'><p class='title'>"+value['title']+"</p><p class='usuario'>"+value['user']+"</p></div></div></div>"; });
$(".videos_container").html(output);
} else {
console.log("Error");
}
}).fail(function(jqXHR, textStatus, errorThrown) { console.log("Hubo un error"); });
});
});
PHP
<?php
if(isset($_POST['title'])) {
get_infvideo($_POST['title']);
} else {
$message = sprintf("No valid");
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $message, true, 403);
}
function get_infvideo($title) {
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseña = "";
$conexion = new PDO($dsn, $usuario, $contraseña);
$resultado = null;
$jsondata = array();
$videos = array();
$text ="";
if($title!="") {
$title= explode(" ", $title);
for($i=0; $i<count($title);$i++) {
if($text!="") {
$text .= " AND (title LIKE '%".$title[$i]."%' or user LIKE '%".$title[$i]."%')";
} else {
$text .= " (titulo LIKE '%".$titulo[$i]."%' or user LIKE '%".$title[$i]."%')";
}
}
}
if($conexion){
$sql = "SELECT * FROM video WHERE ".$text;
if($resultado = $conexion->query($sql)) {
while($fila = $resultado->fetch()) {
$fila['id'] = $fila['id'];
$fila['user'] = $fila['user'];
$fila['image'] = $fila['image'];
$jsondata['success'] = true;
array_push($videos, $fila);
$jsondata['videos'] = $videos;
}
} else {
$jsondata['success'] = false;
$jsondata['message'] = $sql;
}
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata, JSON_FORCE_OBJECT);
}
exit();
?>
The idea is to print the video (with his id, image, user, title) that you have searched...

check database connection after button is click

I am building a website that has a reservation. I use ajax to send information from forms into the another page which insert the information into my database. To make it even useful, I want to make a test connection into my database. After a user fills up all the fields required he will click the submit button and a test connection must check first before sending the data. And when the connection fails, it will tell the user that the connection is not set(maybe his internet connection is lost, or the server itself is failing). In that way, the website prevents prompting the user that their reservation data is sent, but actually NOT.
EDITED:
Here's my running and fixed code:
$("#esubmit2").click(function(){
var event2 = document.getElementsByName("eevent2")[0].value;
var engager2 = document.getElementsByName("eengager2")[0].value;
var contact2 = document.getElementsByName("econtact2")[0].value;
var eadd2 = document.getElementsByName("eeadd2")[0].value;
var venue2 = document.getElementsByName("evenue2")[0].value;
var datein2 = document.getElementsByName("edatein2")[0].value;
var message2 = document.getElementsByName("emessage2")[0].value;
var reg2 = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(event2 == "" || event2 == " "){
$("#eevent2").focus();
return false;
}
else if(engager2 == "" || engager2 == " "){
$("#eengager2").focus();
return false;
}
else if(contact2 == "" || contact2 == " "){
$("#econtact2").focus();
return false;
}
else if(venue2 == "Venue:"){
$("#evenue2").focus();
return false;
}
else if(datein2 == "" || datein2 == " "){
$("#edatein2").focus();
return false;
}
else if(message2 == "" || datein2 == " "){
$("#emessage2").focus();
return false;
}
else if(eadd2 != ""){
if(reg2.test(eadd2) == false){
$("#eeadd2").focus();
$("#eeadd2").css("backgroundColor","#800517");
$("#eeadd2").css("color","#FFFFFF");
return false;
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
})
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string,
success: function(json) {
if(json == 1){
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").val("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
return false;
}
else{
alert("Sorry for the inconvenience but the connection to our database failed.\nPlease check you internet connection or refresh you page.\n\nIf one of the above failed please report to our admin.\nThank You.");
return false;
}
}//end success function
}); //end ajax call
return false; // IMPORTANT
}
submitreserve_eventpc.php:
if($test){
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message2')");
$ok = 1;
}
else{
$ok = 0;
}
echo json_encode($ok);
If there's any improvement that you see please edit. For now this met my needs :)
You should do something like this.
Your php.file
<?php
$con=mysql_connect('localhost','root','root');
if($con){
// do insertion data here into the database
$sql = "Insert into table query";
if($sql){
echo "Data inserted successfully";
}else{
echo "Sorry! some error occured ".mysql_error();
}
}else{
echo "Unable to connect to the server";
}
?>
You could try something like this.
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string
}).done(function(data) {
data = $.parseJSON(data);
message = data.message;
if (message == "success")
{
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").text("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
$("#esubmit2").blur();
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
} else {
console.log(message);
}
});
return false; // IMPORTANT
}
In your PHP file could be changed to what is below.
$myDatabase = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$myDatabase)
{
$message = 'Could not connect: ' . mysql_error();
} else {
$event2 = $_POST['eevent2'];
$engager2 = $_POST['eengager2'];
$contact2 = $_POST['econtact2'];
$eadd2 = $_POST['eeadd2'];
$venue2 = $_POST['evenue2'];
$datein2 = $_POST['edatein2'];
$message2 = $_POST['emessage2'];
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message‌​2')");
$message = 'success';
}
$response = array('message' => $message);
echo json_encode($response); // This is the data that your AJAX function gets in .done

Ajax form request

I have a issue with my ajax form submission.I am dynamically submitting a form and using php at the server side to process it.This is the ajax success function.
$.ajax({
type: "POST",
url: "register.php",
data: "uname="+uname+"&eid="+eid+"&pwd="+pass+"&cpwd="+cpass+"&country="+coun+"&contact="+contact,
dataType: "html",
success: function(data){
if(data!="error")
{
//alert(data);
$("#user_status", window.parent.document).html("Welcome "+data+" | <a href='forum/logout.php'>Logout</a>");
if(window.parent.document.getElementById('post_user_name'))
$("#post_user_name", window.parent.document).html(msg);
parent.$.fancybox.close();
}
if(data=="error")
{
//alert(data);
$("#status").html("<span><center><font class='formright err_msg' style='width:176px;'>The user is already register with us.</font><center></span>");
return false;
}
Now if the user is valid he is logged in and f not there has to be an error like "Already exists".The valid part works fine but for invalid I return an error from the php file but still my error message doesn't show up and just error is printed on the screen.I am using fancybox for my forms(jquery fancybox)
PHP code is
if($_POST['pwd']==$_POST['cpwd'])
{
$username = $_POST['uname'];
$email = $_POST['eid'];
$password = md5($_POST['pwd']);
$cpassword = $_POST['cpwd'];
$contact_no = $_POST['contact'];
$country = $_POST['country'];
$cnt = $checkUser['cnt'];
if($cnt!=0)
{
echo "error";
//exit;
/*$_SESSION['error_msg'] = 'Email Address already exists';
redirect_to_link("index.html");*/
}
else
{
//echo "entered here";
$userArray = array();
//$user = return_post_value($_POST['uname']);
$userArray['uname'] = return_post_value($_POST['uname']);
$userArray['email'] = return_post_value($_POST['eid']);
$userArray['password'] = md5(return_post_value($_POST['pwd']));
$userArray['contact_no'] = return_post_value($_POST['contact']);
$userArray['country'] = return_post_value($_POST['country']);
//print_r($userArray);
//exit;
$userObj->addUserValue($userArray);
$_SESSION['username']= $userArray['uname'];
echo $userArray['uname'];
// return $user;
}
The echo $userArray['uname']; part works but echo "error" doesn't.Checked in Firebug response header,i can see the error word returned.
Can anyone throw some light on it?
Thanks
Use this to compare if($.trim(data)!="error")
And don't recheck for if($.trim(data)=="error")
use
if($.trim(data)!="error")
{
//
}
else{
//
}

Categories