Upload file with ajax then list them - javascript

As I’m wrot in the title my aim is to upload a file via a form by AJAX and return the elements uploaded in a div.
This is form HTML:
<form method="post" action="add.php" enctype="multipart/form-data" id="form-add">
<input type="file" name="file" /><br />
<button type="submit">Envoyer</button>
</form>
This is the traitement that I used in PHP to make the AJAX request
if (isAjax()){
$dir_ext_img = 'img/type_files';
$req = $pdo->prepare('SELECT * FROM upload WHERE idU= ? ORDER BY idF DESC');
$req->execute([$idU]);
$file_being_up = $req->fetch();
?>
<div class="element_upload <?= $file_being_up->idF; ?>">
<img src="<?= $dir_ext_img .'/'. $file_being_up->extension; ?>.svg">
<a href="<?=$file_being_up->dir; ?>" class='name_file' target='_blank'><?= $file_being_up->nameF.'.'.$file_being_up->extension ; ?></a>
<a href="delete.php?idF=<?= $file_being_up->idF; ?>" class='delete'>Supprimer</a>
</div>
<?php
} else{
header('Location: account.php');
}
This is the function isAjax code:
function isAjax(){
return isset($_SERVER['HTTP_X_REQUESTES_WITH']) && $_SERVER['HTTP_X_REQUESTES_WITH'] == 'XMLHttpRequest';
}
This is my script JS in jQuery:
$('#form-add').on('submit', function (e) {
e.preventDefault();
var $form = $(this);
var formdata = (window.FormData) ? new FormData($form[0]) : null;
var data = (formdata !== null) ? formdata : $form.serialize();
var url = $form.attr('action');
$form.find('button').text('Chargement...');
$.ajax({
url: url,
type: $form.attr('method'),
contentType: false,
processData: false,
data: data })
.done(function(data, text, jqxhr){
$('.container').prepend(jqxhr.responseText);
$form.find('button').text('Envoyer');
});
});
The probleme is that I don’t have in return the response of the div that I’ve create in the script PHP, however I receive a full page with the new div inside.
Whereas I want only the previous div create in PHP to put it on the page where I want.
Is anybody know what can I do to have juste a new div with the file uploaded ?

Related

Updating div content with jQuery ajax function over PHP

I am trying to update my div content (#update_div) by sending the value of two input fields to a php file (search_value.php) using the .ajax() function from jQuery.
It works, if I just redirect the two values of the input fields using the html form POST method. So the search_value.php should be correct.
My HTML Code:
<form id="my_form">
<input id="food" name="food">
<input id="amount" value="amount in gram" name="amount">
<input type="button" value="Update" id="submit" name="submit" />
</form>
<div id="update_div">
</div>
My Javascript Code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'GET',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data);
}
});
});
My PHP Code:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $GET_['food'];
$amount = $GET_['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
I do not really get a feedback by clicking the button. Maybe you guys can tell me why?
For GET request, there should not be data part, make it as a query string as below js code:
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php?food='+ food + '&amount='+amount,
type: 'GET',
datatype: "html",
success: function(data)
{
$('#update_div').html(data);
},
failure : function(ex)
{
console.log(ex);
}
});
});
And use $_GET instead of $GET_ in php
Are you running your code after the page has loaded? I've made that mistake several times, and if you're not, I suggest wrapping the whole thing in a $(function(){ /* Everything you have */ });
I prefer using post
in your php script replace $GET_ by $_POST
<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');
$food = $_POST['food'];
$amount = $_POST['amount'];
$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";
$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>
in your javascript code the result is found in data.responseText
here the new script
$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'POST',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data.responseText);
}
});
});
Tested and your JavaScript code works. The issue may be in the PHP code.
Have you tried correcting the "$_GET" as suggested by others?

File and text upload from php page using ajax and store in mysql

Hi i'm currently developing a php page which has an file upload feature. my form sends over 2 hidden values which is an order id and sender id and the file. I have to use ajax as i can't make it refresh after upload. The file upload has to be in my upload/files folder and i need to store the order id , sender id and filename in mysql.My ajax is getting the order id and sender id when i serialize but not the file. i tried seraching on this site for solutions and came acrross FormData object way to no success and also few other methods. the error in my console is always undefined sender_id, file order_id. It doesnt get the values from the html form. Thanks for helping.
MY php, html form
<form method="POST " id="form1" name="form1" enctype='multipart/form-data' >
<input type="hidden" name="sender_id" value="<?php echo $_SESSION['user_session']?>">
<input type="hidden" name="order_id" value="<?php echo $_GET['oid']?>">
<?php //echo var_dump($sellerinfo);?>
<div>
<div>
<textarea name="comments" placeholder="Leave Comments Here..." style="width:800px; height:100px;"></textarea>
<div class="row">
<input type="file" id="file" name="fileupload">
<input type="reset" value="Reset">
<a type="file" href="" class="button" id="fileupload" name="fileupload"> UPLOAD FILE </a>
<br>
<a id="comment" href="" class="button">Post</a>
<input type="reset" value="Reset">
</form>
File.js (ajax file)
$("#fileupload").click(function(e){
alert("inside ajax");
var formData = $("#form1").serialize()
alert(formData);
var formData = new FormData();
var file_data = $('#file').prop('files')[0];
formData.append('file', file_data);
alert(formData);
$.ajax({
url: '../modules/Comment/fileupload.php',
type: 'POST',
dataType:"json",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
error: function (result) {
console.log(result);
alert('ERROR RUNNING INSERTSCRIPT');
},
success: function (result) {
alert(result)
if (result['result'] == true) {
alert("success");
order_id = document.form1.order_id.value;
$('#comment_logs').load("../modules/comment/file_logs.php?",{oid:order_id} );
}
else if (result['result'] == false) {
alert('ERROR');
}
},
});
});
My php script that is supposed to upload and insert data inside database.
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
require('commentclass.php');
$connect = new connect(); // new connect class OBJECT
$conn = $connect->get_connection(); // getting Connection from Connect Object
$sender_id=$_POST['sender_id'];
$order_id=$_POST['order_id'];
$Filename=basename( $_FILES['Filename']['name']);
define ('SITE_ROOT', realpath(dirname(__FILE__)));
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], '../../uploads/files/' . $_FILES['file']['name'])) ;
{
echo "The file " . basename($_FILES['Filename']['name']) . " has been uploaded, and your information has been added to the directory";
$sql = "INSERT INTO files(order_id,send_by,file_name) VALUES ('" . $order_id . "','" . $sender_id . "','" . $Filename . "')";
$result = mysqli_query($conn, $sql);
$data = array();
if ($result) {
$data['result'] = true;
echo json_encode($data);
}
else
{
$data['result'] = true;
echo json_encode($data);
}
}
}
?>
Sorry for the long post, hope someone can help . Thanks in advance

Upload image and text by same form

When I upload image and text by separate form, its work well. But Its not work when I add together.
My form text upload by js and image upload by a php file.
And I think my problem in my form.
If I upload together with js, What change in my js and submit.php, which also add below.
Here is my form code that not work together
<form action="" method="post" id="cmntfrm" enctype="multipart/form-data">
<fieldset id="cmntfs">
<legend class="pyct">
What's your mind
</legend>
<input type="hidden" name="username" size="22" tabindex="1" id="author" value="'.$pname.'"/>
<input type="hidden" name="email" size="22" tabindex="2" id="email" value="'.$email.'"/>
<p><textarea name="comment" rows="10" tabindex="4" id="comment"></textarea></p>
<div id="ajaxuploadfrm">
<form action="uploadpostimg.php" method="post" enctype="multipart/form-data">
<b>Select an image (Maximum 1mb)</b>
<input type="file" name="url" id="url" />
</form>
</div>
<p><input type="submit" name="submit" value="Post comment" tabindex="5" id="submit"/></span></p>
</fieldset>
<input type="hidden" name="parent_id" id="parent_id" value="0" />
<input type="hidden" name="tutid2" id="tutid" value="'.$tutid2.'" />
</form>
js
$(document).ready(function(){
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputEmail = $("#email");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment");
var commentCountList = $("#updatecommentNum");
var error = $("#error");
error.fadeOut();
function updateCommentbox(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=update&tutid="+ tutid,
complete: function(data){
commentList.prepend(data.responseText);
commentList.fadeIn(2000);
}
});
}
function updateCommentnum(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=updatenum&tutid="+ tutid,
complete: function(data){
commentCountList.html(data.responseText);
commentList.fadeIn(2000);
}
});
}
function error_message(){
error.fadeIn();
}
function checkForm(){
if(inputAuthor.attr("value") && inputComment.attr("value") && inputEmail.attr("value"))
return true;
else
return false;
}
//on submit event
$("#cmntfrm").submit(function(){
error.fadeOut();
if(checkForm()){
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var email = inputEmail.attr("value");
var comment = inputComment.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
//we deactivate submit button while sending
$("#submit").attr({ disabled:true, value:"Sending..." });
$("#submit").blur();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=insert&author="+ author + "&url="+ url + "&email="+ email + "&comment="+ comment + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
commentList.prepend(data.responseText);
updateCommentbox();
updateCommentnum();
//reactivate the send button
$("#submit").attr({ disabled:false, value:"Submit Comment!" });
$( '#cmntfrm' ).each(function(){
this.reset();
});
}
});
}
else //alert("Please fill all fields!");
error_message();
//we prevent the refresh of the page after submitting the form
return false;
});
});
Submit.php
<?php header('Content-Type: charset=utf-8'); ?>
<?php
include("db.php");
include_once("include/session.php");
switch($_POST['action']){
case "update":
echo updateComment($_POST['tutid']);
break;
case "updatenum":
echo updateNumComment($_POST['tutid']);
break;
case "insert":
date_default_timezone_set('Asia/Dhaka');
echo insertComment($_POST['author'], $_POST['comment'], $_FILES['url']['name'], $_POST['email'], $_POST['tutid'], $_POST['parent_id'], $date = date("M j, y; g:i a"));
break;
}
function updateNumComment($tutid) {
//Detail here
}
function updateComment($tutid) {
//Detail here
}
function insertComment($username, $description, $url, $email, $qazi_id, $parent_id, $date ){
global $dbh;
//Upload image script that not work here when i try together so i took it at separate file and then tried with above form
$output_dir = "comimage/";
$allowedExts = array("jpg", "jpeg", "gif", "png","JPG");
$extension = #end(explode(".", $_FILES["url"]["name"]));
if(isset($_FILES["url"]["name"]))
{
//Filter the file types , if you want.
if ((($_FILES["url"]["type"] == "image/gif")
|| ($_FILES["url"]["type"] == "image/jpeg")
|| ($_FILES["url"]["type"] == "image/JPG")
|| ($_FILES["url"]["type"] == "image/png")
|| ($_FILES["url"]["type"] == "image/pjpeg"))
&& ($_FILES["url"]["size"] < 504800)
&& in_array($extension, $allowedExts))
{
if ($_FILES["url"]["error"] > 0)
{
echo "Return Code: " . $_FILES["url"]["error"] . "<br>";
}
if (file_exists($output_dir. $_FILES["url"]["name"]))
{
unlink($output_dir. $_FILES["url"]["name"]);
}
else
{
$pic=$_FILES["url"]["name"];
$conv=explode(".",$pic);
$ext=$conv['1'];
$user = $_SESSION['username'];
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["url"] ["tmp_name"],$output_dir.$user.".".$ext);
$pic=$output_dir.$user.".".$ext;
$u_imgurl=$user.".".$ext;
}
}
else{echo '<strong>Warning !</strong> File not Uploaded, Check image' ;}
}
//Submit main comment
if ($parent_id == 0){
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub = "Comment to";
$query = "INSERT INTO comments_lite VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
} else {
if ($parent_id >= 1){
global $dbh;
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub2 = "Reply to";
$query = "INSERT INTO comments_reply VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
}
}
}
?>
on click of submit you can put the code in js you have to make change in the js file
$.post('phpapgename.php',data:jquerydata,function(){
})
in the .php page you can put your query to submit your data.
You cannot have nested form. Try to avoid it and separate out the forms as below. And while submitting any form if you data from other form, create a hidden fields in this form and submit it.
Another suggestion: Since you're working with javascript anyway, outsource the upload-form to an invisible div and make it pop up by clicking/hovering an upload-button or entering the last field of form1 or whatever.

Ajax and PHP photo file uploader

I'm trying to create little photo uploader with PHP and Ajax. So i'm not a php guy and i have some problems with that, always Something went wrong with your upload! status. But when i set this as form action i have success action. Can anyboody help?
HTML:
<form onsubmit="return submitForm()" method="POST" enctype="multipart/form-data">
<input type="file" name="pic" id="pic" multiple/>
<input type="submit" value="Upload" for="pic"/>
</form>
PHP:
<?php
$demo_mode = false;
$upload_dir = 'uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
and JS:
function submitForm() {
console.log("submit event");
$.ajax({
type: "POST",
url: "post_file.php",
enctype: 'multipart/form-data'
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
Much Thx!
You can't transfer file data through AJAX (like that anyway). It used to be impossible, and so iframe hacks were used to get around it, but now with HTML5 you can do it using FormData. Take a look at this: Using HTML5 file uploads with AJAX and jQuery

PHP file upload, sending formdata object

I want to upload a file, send it to javascript formData object and than via ajax to some php script which will put the file into database. It works fine when i upload a file in profile php, send it to formData object in javascript and send it back to profile.php. Problem is that when i want to send formData object to some other php script which isn't profile.php, it doesn't work.
Here is my code:
profile.php
<form role="form" id="editUserProfile" method="post" action="" enctype="multipart/form-data">
<input type="file" id="filename" name="filename" class="file-input" accept="image/*"/></a>
<button type="submit">Save</button
</form>
javascript.js
$('#editUserProfile').validate({
submitHandler: function (form) {
var aFormData = new FormData();
aFormData.append("filename", $('#filename').get(0).files[0]);
$.ajax({
type: "POST",
url: "script.php",
data: aFormData,
success: function(data){
window.location.reload(true);
}
})
}
});
And than I want to check in some other php (script.php) script if file was uploaded.
if(is_uploaded_file($_FILES['filename']['tmp_name']) && getimagesize($_FILES['filename']['tmp_name']) != false){
$size = getimagesize($_FILES['filename']['tmp_name']);
$type = $size['mime'];
$imgfp = fopen($_FILES['filename']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['filename']['name'];
$maxsize = 99999999;
if($_FILES['userfile']['size'] < $maxsize ){
$dbh = new PDO("mysql:host=localhost;dbname=test", 'root');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO table (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");
$stmt->bindParam(1, $type);
$stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
$stmt->bindParam(3, $size);
$stmt->bindParam(4, $name);
$stmt->execute();
}else{
throw new Exception("File Size Error");
}
}
Added to jQuery.ajax and it works now:
processData: false,
contentType: false,

Categories