Ajax file upload not working in Chrome - javascript

I tested this script in Safari, and there it works, but I tried in Chrome, and there it does not work, and doesn't print the $status. What's the problem?
HTML file:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<span id="success"></span>
<form id="upload" method="post" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="file" name="imagefile" id="imagefile">
<input type="submit" name="uploadsubmit" id="uploadsubmit">
</form>
<script>
$(document).ready(function(){
$('#upload').on('submit', function(e) {
e.preventDefault();
var username = $('#username').val();
if (username == '') {
alert("Empty!");
} else {
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
$('#success').html(data);
alert("Success!");
}
});
}
});
});
</script>
PHP file:
<?php
$connect = mysqli_connect("localhost", "root", "", "db");
$con=mysqli_connect("localhost","root","","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$status = '';
if(isset($_POST['uploadsubmit'])) {
$username = $_POST["username"];
if($_FILES['imagefile']['name'] != '') {
$target = "/images";
$target = $target . basename($_FILES['imagefile']['name']);
if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $target)) {
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (username,images)
VALUES ('".$username."','".$target."')");
mysqli_close($con);
$status = "Successfull upload with image!";
$imagefile = pathinfo($target, PATHINFO_EXTENSION);
$check = getimagesize($target);
if ($check !== false) {
echo "This file is image - " . $check["mime"] . ".<br>";
$uploadOk = 1;
} else {
echo "This file is not image!";
$uploadOk = 0;
}
} else {
$status = "Sorry, we have problem!";
}
} else {
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (username,images)
VALUES ('".$username."','no')");
mysqli_close($con);
$status = 'Successfull upload without image!';
}
echo "Status: {$status}";
}
?>

Related

Email Live Checking PHP and Mysql

I have an issue im stuck for 3 days. Im trying to check in DB if the email the user is entering is already registered and avoid registering in duplicate. But this doesn't seem to work fine
here is my code:
This is in the HTML
<script type="text/javascript">
$(document).ready(function() {
$("#cf_email").keyup(function(e) {
var uname = $(this).val();
if (uname == "")
{
$("#msg").html("");
$("#Submit").attr("disabled", true);
}
else
{
$("#msg").html("Verificando, espere...");
$.ajax({
url: "check_availability.php",
data: {Email: uname},
type: "POST",
success: function(data) {
if(data.status == true) {
$("#msg").html('<span class="text-danger">Email ya registrado!</span>');
$("#Submit").attr("disabled", true);
} else {
$("#msg").html('<span class="text-success">Email Disponible para Registrar!</span>');
$("#Submit").attr("disabled", false);
}
}
});
}
});
});
</script>
<right><form id="register" action="contact.php" method="post">
<p><label>E-mail para Registro</label></p>
<input type="text" name="cf_email" id="cf_email" title="Email" class="demoInputBox" placeholder="Email Valido" required><div id="msg" class="form-group"></div>
</form></right>
this is the check_availability.php
$con = mysqli_connect($host, $user, $pass, $db) or die("Error " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST["cf_email"]) && $_POST['cf_email'] != '')
{
$response = array();
$cfmail = mysqli_real_escape_string($con,$_POST['cf_email']);
$sql = "select Email from Bares where Email='".$cfmail."'";
$res = mysqli_query($con, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'email already exists.';
}
else
{
$response['status'] = true;
$response['msg'] = 'email is available.';
}
echo json_encode($response);
}
?>
it doesn't matter which email i introduce in the textfield because always says its available even if the email is registered already in the database
In your JS you're processing a string, not an object. You need to parse it:
success: function(data) {
dataObj = JSON.parse(data);
if(dataObj.status == true) {
....
This is an Example with mysqli OOP try it will work without Problem:
PHP:
<?php $mysqli=new mysqli($host, $user, $pass, $db); mysqli_set_charset($mysqli,'utf8');
if (!empty($_POST['cf_email'])){
extract($_POST);
$sql=$mysqli->query("select Email from Bares where Email='".$cf_email."'");
if($sql->num_row>0){
$status=1;
}
else{
$status=0;
}
echo $status;
die;}
?>
HTML:
<right>
<form id="register" action="contact.php" method="post">
<p><label>E-mail para Registro</label></p>
<input type="text" name="cf_email" id="cf_email" title="Email" class="demoInputBox" placeholder="Email Valido" required>
<input type="submit" id="submit">
<div id="msg" class="form-group"></div>
</form>
</right>
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#cf_email").keyup(function(e) {
var uname = $(this).val();
if (uname == "") {
$("#msg").html("");
$("#submit").attr('disabled', true);
} else {
$.ajax({
url: "check_availability.php",
data: $(this).serialize(),
type: "POST",
success: function(data) {
if (data == 1) {
$("#msg").html('<span class="text-danger">Email ya registrado!</span>');
$("#submit").attr('disabled', true);
} else {
$("#msg").html('<span class="text-success">Email Disponible para Registrar!</span>');
$("#submit").attr('disabled', false);
}
}
});
}
});
});
</script>

Posting image from php to javascript [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 6 years ago.
I have tried to convert my php code using php to javascript ajax. Could you please correct me what supposed to gone wrong since my php code is still activate.
html code:
<form method="post" enctype="multipart/form-data" action="testadd.php">
<input type="file" name="image" id="image">
<br/>
<input type="submit" name="submit" value="upload" id="submit">
</form>
php:
<?php
if(isset($_POST['submit'])){
if(getimagesize($_FILES['image']['tmp_name']) == false){
echo "Please select an image";
echo "<br/>";
}else{
$image = addslashes($_FILES['image']['tmp_name']);
$name = addslashes($_FILES['image']['name']);
$image = file_get_contents($image);
$image = base64_encode($image);
saveImage($name, $image);
}
}
displayImage();
function saveImage($name, $image){
$con = new PDO("mysql:host=localhost; dbname=testimages", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->query("INSERT INTO images(id, name, image) VALUES(38836929, '$name', '$image') ON DUPLICATE KEY UPDATE image='$image', name='$name'");
$stmt->execute();
}
function displayImage(){
$con = new PDO("mysql:host=localhost; dbname=testimages", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->query("SELECT * FROM images");
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_OBJ)){
echo '<img height="24" width="24" src="data:image;base64,' . $result->image . '">';
echo '<br/>';
echo $result->name . ' ';
}
}
?>
javascript:
$(document).ready(function(){
$("#submit").click(function(){
var image = document.getElementById("image").value;
alert(" " + image);
if(image == ""){
alert("please select image");
}else{
$.ajax({
type: "POST",
url: "testadd.php",
data: "image=" + image,
success: function(data){
if(data == success){
alert("test");
}else{
alert("fail");
}
}
});
}
return false;
});
});
Could you please check what supposed to be the problem in order to be fixed.
AJAX must have content Type , ProcessData to upload the image files
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
success : function(data){
//Do stuff for ahed process....
}
});

Checking if username is available before submitting a form

I want to check if the username is taken before the form is submitted.
As far as I can understand I have to use AJAX to get data from my database in javascript. How do I send the username to the PHP file?
This is my form:
<form id="loginForm" action="register.php" method="post">
<p>Register:</p>
<p style="text-align: left;">Full name: <br><input type="text" name="name" required/></p>
<p style="text-align: left;">Email: <br><input type="text" name="email" required/></p>
//Username
<p style="text-align: left;">Username: <br><input id="username" type="text" name="username" onkeyup="validateUsername(value);" required/></p>
<span id="usernameError" style="display:none;border:1px solid red;">Username can only contain a-z, 0-9 and must be at least 6 characters loong</span>
<span id="usernameTaken" style="display:none;border:1px solid red;">Username taken</span>
<p style="text-align: left;">Password: <br><input type="password" name="password" required/></p>
<input type="submit" value="Register">
</form>
This is the validateUsername() function:
function validateUsername(username) {
var re = /[a-zA-Z0-9]/;
alert(username.length);
if(re.test(username) && username.length > 5) {
document.getElementById('username').style.backgroundColor = "green";
document.getElementById('usernameError').style.display= "none";
--error;
} else {
document.getElementById('username').style.backgroundColor = "red";
document.getElementById('usernameError').style.display= "block";
++error;
}
//here i want to check if the user name is taken
}
If the username is taken, I want to display the 'usernameTaken' span.
Otherwise, I want to hide it.
Here is the PHP file that checks if the username is already in the database:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'MyPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
}
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
}
$username = //The username;
$username = mysqli_real_escape_string($link,$username);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count == 0) {
//if the username is NOT taken
return true;
} else {
//if the username IS taken
return false;
}
mysqli_close($link);
?>
How is this done?
JS - JQUERY AJAX
$.ajax({
url: 'register.php', data: {action: 'isUserNameTaken', params: [username]},
type: 'post',
success: function(data) {
//Do Something
}
});
PHP
<?php
function isUserNameTaken($username) {
//Do Something;
}
if(!empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'isUserNameTaken':
$username = '';
if(!empty($_POST['params'])) {
$username = $_POST['params'][0];
}
isUserNameTaken($username);
break;
}
}
?>
You could do it this way:
On client side:
function validateUsername(){
if(//test username input for length...) {
$.ajax({
type: 'POST',
url: 'validate.php',
data: { username: username },
success: function(response) {
if(response==0){
//username is valid
}
elseif(response==1){
//username is already taken
}
elseif(response==2){
//connection failed
}
}
});
}
else{
//display "username is too short" error
}
}
validate.php:
<?php
session_start();
define('DB_NAME', 'madsanker_dk_db');
define('DB_USER', 'madsanker_dk');
define('DB_PASSWORD', 'MyPassword');
define('DB_HOST', 'mysql43.unoeuro.com');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' .mysqli_error());
echo json_encode(2);
}
else{
$db_selected = mysqli_select_db( $link, DB_NAME);
if (!$db_selected) {
die('Could not connect: ' .mysqli_connect_error());
echo json_encode(2);
}
else{
$username = $_POST["username"];
$username = mysqli_real_escape_string($link,$username);
$sql = "SELECT * FROM mainLogin WHERE username = '$username'";
$result = mysqli_query($link, $sql);
$count = mysqli_num_rows($result);
if($count == 0) {
//if the username is NOT taken
echo json_encode(0);
}else {
//if the username IS taken
echo json_encode(1);
}
mysqli_close($link);
}
}
?>
You can also make this function validateUsername by calling it with onkeyup function in jquery so every time a user types something into the input field, the username will be checked....

how to display alert/echo messages in ajax

Hi i have a simple form and implemented an ajax script. My question is how to display the echo messages form the other php file which is user-file-upload.php?
I would also like to ask if i am doing ajax the right way. I am a total noob right now in ajax. Hope you could help me in the right direction. Thanks
Here is my form
echo "<form action='portal-files/user-file-upload.php' method='post' enctype='multipart/form-data' id='test_ajax'>";
echo "<input type='hidden' name='MAX_FILE_SIZE' value='100000' />";
echo "<input type='hidden' name='admin_id' value='$user->id' />";
echo "<select name='id' id='form-option' class='test-only'>";
echo '<option selected="selected">' .'Choose a User'. '</option>';
foreach ($registeredUsers as $key => $value) {
$registered = JFactory::getUser($value);
echo '<option value="'.$registered->id.'">'.$registered->name.'</option>';
}
echo "</select>";
echo "<input name='uploadedfile' type='file' id='custom-file-input' class='test-only' /> <br/>";
echo '<input type="submit" name="submit" value="Upload" id="custom-submit-input" disabled="disabled" >';
echo '<span id="display_file"></span>';
echo '<span id="display_user" style="visibility:hidden"></span>';
echo "</form>";
Here is the user-file-upload.php
<script src="https://cdn.rawgit.com/t4t5/sweetalert/master/dist/sweetalert.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/t4t5/sweetalert/master/dist/sweetalert.css">
<?php
define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define( 'JPATH_BASE', realpath(dirname(__FILE__).DS.'..' ));
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$target_dir = "../portal-files/";
$target_file = $target_dir . basename($_FILES["uploadedfile"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["uploadedfile"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "doc" && $imageFileType != "docx" && $imageFileType != "xlsx") {
echo "Sorry, only DOC, DOCX, XLXS.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["uploadedfile"]["name"]). " has been uploaded.";
if(isset($_POST['id']))
{
$selectedValue = $_POST['id'];
$adminabc = $_POST['admin_id'];
$imageFileName = basename( $_FILES["uploadedfile"]["name"]);
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = "INSERT INTO joom_fss_user_files (user_id,admin_id) VALUES ($selectedValue,$adminabc)";
$db->setQuery($query);
$result = $db->execute();
$db = JFactory::getDbo();
$query_user = $db->getQuery(true);
$query_user = "INSERT INTO joom_fss_files (user_id,admin_id,file_type,file_name,path_url) VALUES ($selectedValue,$adminabc,'$imageFileType','$imageFileName', '$target_file')";
$db->setQuery($query_user);
$result = $db->execute();
sweetAlert("You have successfuly uploaded a file.");
}
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Here is my jquery script
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
jQuery(document).ready(function() {
jQuery('#test_ajax').ajaxForm(function() {
e.preventDefault();
});
});
</script>
I think you should use this way, response is everything that you echo in .php page.
$("#test_ajax").ajaxForm({
success: function(response, textStatus, xhr, form) {
alert(response); //alert
$('#some-container').html(response); //show in html element
},
error: function(xhr, textStatus, errorThrown) {
console.log("in ajaxForm error");
},
complete: function(xhr, textStatus) {
console.log("in ajaxForm complete");
}
});

How to connect correct link directory files

I wanted to do is connect some files in different folder inside elogFiles folder. My problem is i dont know how to connect the files inside of another folder files.
here is the family tree of my files:
http://s38.photobucket.com/user/eloginko/media/folder_zpsa156e2a5.png.html
My problem the links is not correct.
Both code are not related. And the user.php is asking for connection from inside the dbc folder database.php and myScript.js wants to find user.php where is located inside the view folder.
myScript.js: " url: 'js/../view/user.php',"
user.php: "include_once('view/../dbc/database.php');"
can anyone help me correct the correct directory links.
user.php
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$email = $_POST['email'];
$pass = $_POST['password'];
if(!empty($email) && !empty($pass)){
$st = $db->prepare("SELECT * from user WHERE email=? AND password=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
echo "1";
exit;
} else {
echo "Incorrect Email or Password";
}
}else{
echo "Please enter Email and Password";
}
?>
myScript.js
$(document).ready(function() {
$('div#show:empty').hide();
$('#login').click(function(){
var email = $('#lemail').val();
var password = $('#lpassword').val();
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'js/../view/user.php',
success: function(data)
{
if (Number(data) == 1)
{
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
}
else
{
$('div#show:empty').show();
$('#show').html(data);
}
}
});
return false;
});
});
As your hierarchy is presently, provided, if you are on your http://localhost/elogFiles/view/user.php, you just need to go level one up ../
user.php
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$email = $_POST['email'];
$pass = $_POST['password'];
$response['status'] = '';
$response['message'] = '';
if(!empty($email) && !empty($pass)){
$st = $db->prepare("SELECT * from user WHERE email=? AND password=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
$response['status'] = 'OK';
} else {
$response['status'] = 'ERROR';
$response['message'] = 'Username/Password not found';
}
}else {
$response['status'] = 'ERROR';
$response['message'] = 'Please input username/password';
}
echo json_encode($response);
exit;
?>
Since, user.php processes the AJAX request, point the AJAX url attribute to this file. Consider this example:
myScript.js
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'http://localhost/elogFiles/view/user.php',
dataType: 'JSON',
success: function(data) {
if (data.status == 'OK') {
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
} else {
$('div#show:empty').show();
$('#show').html(data.message);
}
}
});

Categories

Resources