if isset post with jquery (upload file) - php

When i remove "if(isset($_POST['_upload_profile_image'])){}" from users.php. Code is working and uploading.
How can i do this with 'isset($_POST'.
MY JQUERY
$("#upload_profile_image").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "/particley/global/post/users.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function (html) {
if (html == 'true') {
//
} else {
//
}
}
});
}));
MY PHP
if(isset($_POST['_upload_profile_image'])){
$upload = ($_FILES['image']['tmp_name']);
if ($users->upload($upload) === TRUE) {
echo 'true';
} else {
echo 'false';
}
}

Is there any element in your form having name _upload_profile_image, If not then remove this line
if(isset($_POST['_upload_profile_image'])){
or replace with
if(isset($_FILE['image']) && !empty($_FILE['image'])){

Please replace this with your ph code
if(!empty($_FILES['image'])){
$upload = ($_FILES['image']['tmp_name']);
if ($users->upload($upload) === TRUE) {
echo 'true';
} else {
echo 'false';
}
}

For File upload There are various methods available to check files exist or not you can use any of them.
if (!empty($_FILES['image']['name'])) {
if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) { ... }
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
In your case you can use any of them :
if(!empty($_FILES['image'])){
$upload = ($_FILES['image']['tmp_name']);
if ($users->upload($upload) === TRUE) {
echo 'true';
} else {
echo 'false';
}
}

Related

How to delete a file from a directory folder with php?

I'm echoing out users images from a folder, i don't have the names of the images stored. so i'm trying to take the src of the image file on .image_delete_btn click and pass that to delete_image.php where it can delete the file. I can't see why this isn't working. any suggestions are much appreciated.
PS: no errors, the delete_image.php script simply returns NULL, but the ajax request is being called. But I don't think the data is being passed.
HTML/PHP: (displays images from folder)
for ($i=0; $i<count($files); $i++){
$image = $files[$i];
$supported_file = array(
'gif',
'jpg',
'jpeg',
'png'
);
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (in_array($ext, $supported_file)) {
echo '<div class="card company_photo_card">';
echo '<div class="image_delete_btn flaticon-error"></div>';
echo '<div class="img_hover_effect">';
echo '<img src="'.$image .'" alt="Random image" class="company_photos" />';
echo '</div>';
echo '</div>';
} else {
continue;
}
}
AJAX:
$('.image_delete_btn').click(function() {
var filename = $(this).next("div").first("img").attr("src");
$('.loading_gif').show();
m = confirm("Are you sure you want to delete this image?");
if (m == true) {
$.ajax({
type: 'POST',
url: 'confirm/delete_image.php',
data: {
filename: filename
},
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function(response) {
$('.loading_gif').hide();
$(filename).fadeOut();
},
error: function(data) {
switch (data.info) {
case 'delete_error':
delete_error();
break;
case 'delete_success':
delete_success();
break;
}
}
});
} else {
$('.loading_gif').hide();
}
});
delete_image.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$filename = $_POST['filename'];
$file = basename($ImageData);
if (file_exists($filename)) {
unlink($filename);
$response["message"] = 'delete_success';
$errors++;
}
var_dump($filename);
echo json_encode($response);
exit();
}else{
echo"acces denied";
}
?>

Ajax code doesn't work inside of jquery form validation

I want to write (register section) code that can check if email have been used in past or the login is empty.
The code is working fine, but my ajax code dont run at all.
I checked everything, path to php file is good, variables are good etc. Don't how to solve it.
Code:
$('.login').submit(function(e) {
e.preventDefault();
var error = 0;
var self = $(this);
var $name = self.find('[type=name]');
var $email = self.find('[type=email]');
var $pass = self.find('[type=password]');
var emailRegex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (!emailRegex.test($email.val())) {
createErrTult("Błąd! Email ma zły format!", $email)
error++;
}
//MY AJAX CODE
var email = $email.val();
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
}
});
if ($name.val().length > 1 && $name.val() != $name.attr('placeholder')) {
$name.removeClass('invalid_field');
} else {
createErrTult('Error! Wrong name!', $name)
error++;
}
if ($pass.val().length > 1 && $pass.val() != $pass.attr('placeholder')) {
$pass.removeClass('invalid_field');
} else {
createErrTult('Error! Wrong password!', $pass)
error++;
}
if (error != 0) return;
self.find('[type=submit]').attr('disabled', 'disabled');
self.children().fadeOut(300, function() {
$(this).remove()
})
$('<p class="login__title">sign in <br><span class="login-edition">welcome to A.Movie</span></p><p class="success">You have successfully<br> signed in!</p>').appendTo(self)
.hide().delay(300).fadeIn();
// var formInput = self.serialize();
// $.post(self.attr('action'),formInput, function(data){}); // end post
});
php:
<?php
include ("config.php");
if($action == "emailcheck"){
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo json_encode($dodano);
}
?>
First, you should try adding error callback:
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
type: 'POST',
success: function(odp) {
if (odp == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
},
error: function(xhr, textStatus, error) // THOSE ROWS
{
alert(error);
}
});
This may alert you about some occured error.
Second, you can try to use json instead of plain text:
Client-side:
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
'email': email
},
dataType: 'json', // THIS ROW
type: 'POST',
success: function(odp) {
if (odp['result'] == 1) {
createErrTult("Błąd! taki email już istnieje w bazie!", $email)
error++;
}
},
error: function(xhr, textStatus, error)
{
alert(error);
}
});
Server-side:
<?php
include ("config.php");
if (isset($_GET['action'])){
$action = $_GET['action'];
if($action == "emailcheck") {
if(isset($_GET['email'])) {
$email = $_GET['email'];
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo (json_encode(array("result" => $dodano))); // THIS ROW
}
}
}
}
?>
before everything check you config.php file path .. In your case config.php should be in the same path with rejestracja.php and try this.. lets start with ajax
$.ajax({
url: '../inc/rejestracja.php?action=emailcheck',
data: {
email: email
},
type: 'GET',
success: function(odp) {
if (odp == 1) {
alert('Email exists');
}else{
alert('Email dosen\'t exists');
}
}
});
then in php
<?php
include ("config.php");
if (isset($_GET['action'])){
$action = $_GET['action'];
if($action == "emailcheck"){
if(isset($_GET['email'])){
$email = $_GET['email'];
//sprawdzamy czy był już dodany plus
$test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
if ($test > 0) {
$dodano = 1;
echo ($dodano);
}
}
}
?>
you should get alert with ('Email exists')

Check folder existence Ajax - php

I want to check existence of a folder called $subdomaine in the directory \cms\sites\ on the keyup.
Here is my script:
<script>
$(document).ready(function(){
$('#subdomain').keyup(subdomain_check);
});
function subdomain_check(){
var subdomain = $('#subdomain').val();
if(subdomain == "" || subdomain.length < 4){
$('#subdomain').css('border', '3px #CCC solid');
$('#tick').hide();
}else{
jQuery.ajax({
type: "POST",
url: "ajax.php",
data: 'subdomain='+ subdomain,
cache: false,
success: function(response){
if(response == 1){
$('#subdomain').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
}else{
$('#subdomain').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
}
</script>
ajax.php :
<?php
$dirname = $_SESSION["subdomain"];
$filename = DOCUMENT_ROOT."sites/".$dirname;
if (!file_exists($filename)) {
echo "The directory $dirname exists.";
exit;
}
How do I check the existence of the folder at the input ?
Thanks
Try this, you need to use is_dir() function to check given file name is directory.
if (is_dir($filename)) {
echo "The directory $dirname exists.";
exit;
}
For your ajax response,
if (is_dir($filename)) {
echo 1;
}else{
echo 0;
}
better way---
NB: change $_SESSION to $_POST too.
<?php
$dirname = $_POST["subdomain"]; //look this
$dir = DOCUMENT_ROOT."sites/".$dirname;
if(file_exists($dir) && is_dir($dir)){
echo "The directory $dirname exists.";
exit;
}
?>

jquery.ajax json wrong?

hey i have a problem submitting my data via jquery and back:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
});
so,
ONE of those if-conditions must be true, because of:
checkAvailability.php:
if(isset($_POST['data'])) {
define('SECURE', true);
include "storescripts/connect_to_mysql.php";
require 'AvailabilityChecker.php';
$config = array(etc..);
$availabilityChecker = new AvailabilityChecker($config);
$data = $_POST['data'];
$data = json_decode($data,true);
preg_match( '/(\d+(\.\d+)?)/', $data['x'] , $m);
$x = $m[0];
if($availabilityChecker->check_availability($x)) {
echo json_encode(array("error" => "is ok", "result"=>1));
} else {
echo json_encode(array("error" => "not ok", "result"=>0));
}
}
data.result have to be 1 OR 0.
anybody can tell me why there is no alert-message? greetings!
UPDATE:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
now i get first the fail-1 alert and than the fail-2 alert, so both if-conditions are false, why?
You need to specify the dataType, otherwise jquery will instead try to guess what you are trying to do. In this case it is incorrectly guessing text/html rather than application/json.
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: 'json',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
You should also properly set the content-type header in php, before you echo the json.
header('Content-type: application/json');
You can get away with doing either-or, but i'd suggest doing both.
a solution can be
success: function(d) {
data = jQuery.parseJSON(d);
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
this becouse $.ajax will no decode the result text from the page for you.
what the php code is doin in fact is to print a json string to the stream.
Note that the the output passed to success can be any sort of text (also xml code on simply text)
You need to set the correct content type header in your php file:
header('Content-Type: application/json');
//snip
echo json_encode(array("error" => "is ok", "result"=>1));

check if php-clause true or false using jquery

hey there i have this script´s:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: "json",
data: 'username=' + $(this).data('id'),
success: function(data) {
if (result == 1) {
$("#select-err").text(data.error ? data.error : "");
}
else {
$("#select-err").text(data.error ? data.error : "");
}
}
});
in checkAvailability.php:
$availabilityChecker = new AvailabilityChecker($config);
if($availabilityChecker->check_availability($_POST['username'])) {
echo json_encode(array("error" => "is ok"));
$result = 1;
} else {
echo json_encode(array("error" => "Wrong chose"));
$result = 0;
}
while testing i found out that this is not the correct way to check if a php-clause is true or false, so i need your help...could anyone show me how to check this via jquery? greetings and thanks!
UPDATE:
i changed to:
$availabilityChecker = new AvailabilityChecker($config);
if($availabilityChecker->check_availability($_POST['username'])) {
echo 1;
} else {
echo 0;
}
and:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: "json",
data: 'username=' + $(this).data('id'),
success: function(data){
if(data == 1){
$("#select-err").text(data.error ? data.error : "is ok");
}
else{
$("#select-err").text(data.error ? data.error : "not ok");
}
}
});
it works, BUT:
if data == 1, on my page "1" is displayed, why and how can i fix this?
Instead of doing this
if (result == 1) {
do this
if (data.result == 1) {
inside your success callback javascript file.
Then in your PHP file instead of these:
echo json_encode(array("error" => "is ok"));
echo json_encode(array("error" => "Wrong chose"));
do these instead:
echo json_encode(array("error" => "is ok", "result"=>1));
echo json_encode(array("error" => "Wrong chose", "result"=>0));
What I did is I included result as a property in the JSON coming from AJAX call. So instead of only having the error property you also have the result property in the JSON.
in php change to this
$availabilityChecker = new AvailabilityChecker($config);
if($availabilityChecker->check_availability($_POST['username'])) {
echo json_encode(array("error" => "is ok" , "result"=>1));
} else {
echo json_encode(array("error" => "Wrong chose" , "result"=>0));
}
and in jquery
check as
if(data.result==1){
// do the same
}else{
}
Don't echo json_encode(array("error" => "is ok")); in php in if-else statement, just echo result in both cases.
In you ajax it on success callback, it will return everything that is on ur php page i.e. result which may be 1 or 0. SO check if data==1 or data==0 instead of result.

Categories