how to display alert/echo messages in ajax - javascript

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");
}
});

Related

Passing PHP array from external php file to script tags on the main page

Am trying to pass a variable from an external php script to scripts tag in the main page but the main_page.php is returning an undefined variable which is the array that i intend to pass from PHP to js. Its a university units registration system, any help will be greatly appreciated.
my javascript is
<script>
var m=<?php echo json_encode($ar) ?>;
alert(m[0]);
</script>
And my PHP file with the array variable ($ar) is this
<?php
$course=$semester="";
$course_err=$semester_err="";
$link = mysqli_connect("localhost","root","","courses");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["name"]))){
$course_err= "course is not set";
} else {
$course=($_POST["name"]);
}
if(empty(trim($_POST["email"]))){
$semester_err= "semester is not set";
} else {
$semester=($_POST["email"]);
}
}
if(empty($course_err || $semester_err)){
$sql="SELECT `$semester` FROM `$course`";
$retval=mysqli_query($link,$sql);
if(mysqli_num_rows($retval)>0){
while ($row= mysqli_fetch_assoc($retval)){
echo "<form method='post' name='units'>";
echo "<li class='list-group-item' style='background:#663300;color:#fff'>
<input type='checkbox' id='firstnit'><p style='color:#fff;font-
size:1.2em;'>{$row[$semester]}</p></li><br>";
echo "</form>";
$ar=array($row);
$_SESSION["tempArray"]=$ar;
echo json_encode($ar);
}
}else{
echo "<li class='list-group-item' style='color:#111;'>0 units
registered</li>";
}
echo "<script>alert('The units have been added to the iframe with success');
</script>";
echo "<br/>";
echo "<button onclick='Array()' class='btn'>Submit Units</button>";
}
?>

Upload file path from array to database

I currently am able to save multiple individual files to folder using an array. Now I would like to add the individual file paths from the folder into a database.
How would I be able to get the individual paths of each file uploaded to folder?
From there how would I insert those individual paths into my database into separate fields?
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<input type="submit" value="Upload all files">
</form>
</body>
</html>
PHP:
<?php
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
$imageFileType = pathinfo($path,PATHINFO_EXTENSION);
$path = 'uploads/' . $_FILES['my-file']['name'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
$conn_info = "host=d port= dbname= user= password=";
$dbconn = pg_connect($conn_info)
or die('could not connect:' . pg_last_error());
echo"<br/>sucessful connection";
$query = "INSERT INTO photo2 (path) VALUES ('".$path."') ;";
$result = pg_query($dbconn, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "<br/> error with query: " . $errormessage;
exit();
}
echo "<br/> file uploaded to PostgreSQL";
pg_close();
?>
Get the path in for loop. And also write insert query in loop.
Database connection code has to be before for loop.
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$name_array[$i])){
// get path
$path = "uploads/".$name_array[$i];
echo $name_array[$i]." upload is complete<br>";
// Insert query comes here
$query = "INSERT INTO photo2 (path) VALUES ('".$path."') ;";
pg_query($dbconn, $query);
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
There is the full code you need. I think it's may help you sir.
<?php
$conn_info = "host=d port= dbname= user= password=";
$dbconn = pg_connect($conn_info) or die('could not connect:' . pg_last_error());
echo "<br/>sucessful connection";
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
// you don't need this lines of code
// $imageFileType = pathinfo($path, PATHINFO_EXTENSION);
// $path = 'uploads/' . $_FILES['my-file']['name'] . '.' . $imageFileType;
for($i=0;$i<count($tmp_name_array);$i++) {
$path = "uploads/" . $name_array[$i];
if(move_uploaded_file($tmp_name_array[$i], $path)){
$query = "INSERT INTO photo2 (path) VALUES ('".$path."');";
$result = pg_query($dbconn, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "<br/> error with query: " . $errormessage;
exit();
} else {
echo $name_array[$i]." upload is complete<br>";
}
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
echo "<br/> file uploaded to PostgreSQL";
pg_close();
?>

deleting a file from directory using checkbox

I want to delete files from a directory using check-box for selecting files and button event for deleting selected ones.
so basically I want it looks like this:
the problem, I retrieve the files via php but I put this checkbox via jquery
and I dont know how to relate these elements with each other
How can I delete these selected files?
My code is down here:
$dir = 'C:\directory\of\files\here';
$files1 = scandir($dir);
$cnt = count($files1);
//var_dump($cnt);
echo "<h1><u> delete files from directory </u></h1>";
echo "<div class='container'>";
for($n=0; $n< $cnt; $n++)
{
if ( ($files1[$n])!= '.' && $files1[$n] != '..')
{
print_r("<input type='checkbox' />".($files1[$n])."<br/> ");
}
}
echo "</br>";
echo " <button>DELETE</button>";
echo "</div>";
?>
<html>
<head>
<script>
$(function() {
$( "input[type=submit], a, button" )
.button()
.click(function( event ) {
event.preventDefault();
});
</script>
</head>
<body>
</body>
</html>
Here is your main file
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8/>
<title>delete</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js"></script>
</head>
<body>
<form id="myform">
<?php
$filesss = array_diff(scandir(__DIR__), array('..', '.'));
foreach ($filesss as $file) {
echo "<label>";
echo "<input type='checkbox' name='file[]' value='$file'>";
echo "$file </label><br>";
}
?>
<button type="submit">delete</button>
</form>
<script>
$(document).ready(function () {
$("#myform").submit(function (event) {
$.ajax({
type: 'POST',
url: 'delete.php',
data: $(this).serialize(),
success: function () {
alert("success");
}
});
event.preventDefault();
});
});
</script>
</body>
</html>
and your delete file
<?php
foreach ($_POST['file'] as $file) {
if (file_exists($file)) {
unlink($file);
}
}
Basically what you do with this code is that you collect file paths from the page and you send via ajax to delete.php what deletes the files (with unlink).
But ALWAYS use form and input validation especially when you want do delete files!
You'll need to set a <form> tag, which creates a form.
Then you'll need to set a name and value to the checkboxes.
Last but not least, when the form is submitted, PHP checks if $_POST['filenames'] is set, if yes, it loops the array and deletes all the files that are selected.
<?php
$dir = 'C:\directory\of\files\here';
if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if( isset( $_POST['filesnames'] ) ) {
foreach( $_POST['filesnames'] as $key => $file ) {
unlink( $dir . '\\' . $file );
}
echo 'Files deleted';
}
else {
echo 'No files selected';
}
}
$files1 = scandir($dir);
$cnt = count($files1);
//var_dump($cnt);
echo "<h1><u> delete files from directory </u></h1>";
echo "<div class='container'>";
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
for($n=0; $n< $cnt; $n++)
{
if ( ($files1[$n])!= '.' && $files1[$n] != '..')
{
print_r("<input name='filesnames[]' value='".($files1[$n])."' type='checkbox' />".($files1[$n])."<br/> ");
}
}
echo "</br>";
echo " <submit>DELETE</submit>";
echo "</form>";
echo "</div>";
?>
you can do something like this
<?php
$dir = 'C:\directory\of\files\here';
if($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach($_POST['files'] as $file) {
$file = addslashes($file);
if(is_readable($file)) {
unlink($file);
}
}
} else {
$files = scandir($dir);
}
?>
<html>
<head>
<script>
$(document).ready(function() {
$('#deleteFiles').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: location.href,
}).done(function() {
alert('Done !!!');
});
})
});
</head>
<body>
<h1><u> delete files from directory </u></h1>
<div class="container">
<form action="#" method="post" id="deleteFiles">
<?php foreach($files as $file): ?>
<?php if($file === '.' || $file === '..') { continue; } ?>
<lable>
<input type="checkbox" name="files[]" value="<?php echo $file; ?>">
$<?php echo $file; ?>
</lable>
<?php endforeach; ?>
<input type="submit" value="Delete">
</form>
</body>
</html>

Can not add a Comment using jquery php ajax

I want to add comment on pressing enter and want to store it to my database with the specific t_id for it so that i can show it on the page after submission but when i enter text and press enter it does nothing.and i am also suspicious about my add_comment.php fule query because t_id is forgien key in comments table and primary in topics i am at very beginer level in jquery,php and ajax...Any Help will be appreciated.
Here is my Jquery From Send.php
$(document).ready(function(){
$('a').on('click',function(e){
$('#Comments').html('<textarea id="D_Comment" name="D_Comment"></textarea>');
$('a').on('input',function(ev){
$('#Enter_Comments').on('click',function(event){
var d_comnt = $('#D_Comment').val();
if (event.which == 13) {
alert("You Hit Enter");
e.preventDefault();
$.ajax({
url : "ajax/add_comment.php",
type : "POST",
data : {D_Comment : d_comnt},
success : function(data){
console.log(data);
},
error : function(data){
alert(data);
}
});
}
});
// ev.preventDefault();
// return false;
});
//e.preventDefault();
return false;
});
});
and my html from send.php on same page with php showing post from database
<section id="Main_Content">
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$last_id = mysql_real_escape_string($_GET['t_id']);
$sql = "SELECT * FROM Topics WHERE t_id = '".$last_id."'";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo "<article>";
// echo $row['t_id'];
echo "<h2>".$row['name']."</h2>"."<br/>";
//echo "<a href='#'>".$row['date']."</a>";
// echo "<a href='#'>".$row['date']."</a>";
echo "<p> Posted on ".$row['date']."</p>"."<br/>" ;
echo "<p>".$row['detail']."</p>"."<br/>" ;
echo "<a href='t_id=".$row['t_id']."' id='Enter_Comments'>"."Enter Comment". "</a>";
echo "</article>";
?>
<div id="Comments"></div>
</section>
and my add_comment.php fiel is
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$d_cmnt = mysql_real_escape_string($_POST['D_Comment']);
$t_id = mysql_real_escape_string($_GET['t_id']);
$sql = "INSERT INTO comments (comment,t_id,date) VALUES('$d_cmnt','$t_id',Now())";
$query = mysql_query($sql);
if ($query) {
echo "Success";
}
else{
echo "Error";
}
?>

Image upload with ajax and php is failing (no error log)

The following code I'm using to upload images is failing for some reason...
Here is the HTML
<form id="image_upload" enctype="multipart/form-data" action="uploadImage.php" method="post" name="prof_picture">
<input id="image1" style="display:none;" name="image" accept="image/jpeg" type="file">
<input id="image2" value="Submit" type="submit" style="display:none;">
</form>
PHP (uploadImage.php)
include('../sqlconnection.php');
define ("MAX_SIZE","1000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "profile/uploads"; //Image upload directory
$filename = stripslashes($_FILES['image']['name'][0]);
echo $filename;
$size=filesize($_FILES['image']['tmp_name'][0]);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'][0], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
}
JS
$('#image1').on('change', function() {
$("#image").attr('src',"profile/loading.gif");
$("#image_upload").ajaxForm({
target: '#image'
}).submit();
});
What I know for sure:
1º The php script is being achieved correctly because I failed part of the code on purpose and attained an error message regarding an internal php error.
2º The query is being done correctly (or at least by its syntax).
3º The javascript function related to #image is also working.
I only want to upload one image that the user selects (even if he selects 100 other items). But as I said, I don't even get an error message on the log... Any ideas on this one? Thank you very much!
EDIT
I've changed the code a bit
$ext = strtolower($ext);
if(in_array($ext,$valid_formats)){
if ($size < (MAX_SIZE*1024)){
$image_name=time().$user_id."--pfi-".$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname)){
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}else echo '<span class="imgList">This message appears </span>';
}else echo '<span class="imgList">You have exceeded the size limit!</span>';
}else echo '<span class="imgList">Unknown extension!</span>';
For some reason it now stops at if(move_uploaded_file($_FILES['image']['tmp_name'], $newname)). I've var_dump'ed this and it is indeed "false" but I can't get to understand why. Here is var_dump($_FILES):
array(1) { ["image"]=> array(5) { ["name"]=> string(21) "060424_hubble_big.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpZYaDkm" ["error"]=> int(0) ["size"]=> int(35641) } }
EDIT 2
Warning:
move_uploaded_file(profile/uploads/1388794617.png):
failed to open stream: No such file or directory in
profile/uploadProfilePicture.php on line 37
Warning: move_uploaded_file(): Unable to move '/tmp/phppFfoL4' to
'profile/uploads/1388794617.png' in
profile/uploadProfilePicture.php on line 37
how should I specify $uploaddir or even $newname?
Edit
This is what I used. Notice the commented out conditional statements.
<?php
// include('../sqlconnection.php');
define ("MAX_SIZE","1000000000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
// if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
// {
$uploaddir = "profile/uploads/"; //Image upload directory
$filename = stripslashes($_FILES['image']['name']);
echo $filename;
$size=filesize($_FILES['image']['tmp_name']);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
// mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
// }
Original answer
Ok, I found the problem. Remove all [0] in your PHP and it will now work. Those are used for arrays and since you're only using it for single file uploads, is why it failed.
Sidenote: You may want to add a / at the end of $uploaddir = "profile/uploads"; as in $uploaddir = "profile/uploads/";
The following doesn't have the [0]'s and have tested it as pure PHP with no JS.
include('../sqlconnection.php');
define ("MAX_SIZE","1000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "profile/uploads"; //Image upload directory
$filename = stripslashes($_FILES['image']['name']);
echo $filename;
$size=filesize($_FILES['image']['tmp_name']);
echo $filename;
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['image']['tmp_name'], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("UPDATE table SET image='$image_name' WHERE id='$user_id'");
}
else
{
echo '<span class="imgList">failed</span>'; }
}
else
{
echo '<span class="imgList">failed</span>';
}
}
else
{
echo '<span class="imgList">failed</span>';
}
}

Categories

Resources