Two distinct forms doing just one POST through PHP and AJAX - php

I've made two pages, each one with a form sending a selected image to localhost through a ajax script pointing to a save.php (containing the code to rename, realocate, and update MySQL with the destination folder/filename.
The first form works fine. But when the second page loads and the file is selected, nothing more happens. Like I was unable to use the $_FILES variable twice.
Here the html of the first page (The second one is the same, but I changed the f_chassi to f_nmotor.
$(document).ready(function(){
$("#btn").on('click', function(){
var data = new FormData();
data.append('f_chassi', $('#f_chassi')[0].files[0]);
$.ajax({
url: 'salvar.php',
data: data,
processData: false,
contentType: false,
type: 'POST',
});
});
});
function filePreview(input) {
if (input.files) {
var reader = new FileReader();
reader.onload = function (e) {
$('#fotoPreview + img').remove();
$('#fotoPreview').before('<center><img src="'+e.target.result+'" width="75%"/></center>');
}
reader.readAsDataURL(input.files[0]);
}
}
$("#f_chassi").change(function () {
filePreview(this);
});
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<body>
<div id="wrapper">
<div class="titulo">O.S. <?php echo $_SESSION['novaOS']; ?></div>
<div id="novaos">
<div class="subtitulo">
<?php
echo "Placa: <i>".$_SESSION['placa']."</i>";
?>
</div>
<div class="subtitulo">FOTO CHASSI</div>
<form method="post" enctype="multipart/form-data" id="fotoPreview" action="fotoNumMotor.php">
<input type="file" name="f_chassi" id="f_chassi" accept="image/*" capture="camera">
<button type="button" id="btn">SALVAR</button>
<div>
<input type="submit" value="PRÓXIMA">
</div>
</form>
</div>
</div>
</body>
Here is the save.php code:
<?php
if (!empty($_FILES['f_chassi'])){
$dir_img = "../uploads/fotos/";
$prefix = time()."_";
$fn = $prefix."chassi_".$_FILES['f_chassi']['name'];
$src = $dir_img.$fn;
move_uploaded_file ($_FILES['f_chassi']['tmp_name'], $src);
$chassi = $src;
mysql_query ("UPDATE imagens SET chassi='$chassi' WHERE idp='".$_SESSION['novaOS']."'");
}
if (!empty($_FILES['f_nmotor'])){
$dir_img = "../uploads/fotos/";
$prefix = time()."_";
$fn = $prefix."nmotor_".$_FILES['f_nmotor']['name'];
$src = $dir_img.$fn;
move_uploaded_file ($_FILES['f_nmotor']['tmp_name'], $src);
$nmotor = $src;
mysql_query ("UPDATE imagens SET nmotor='$nmotor' WHERE idp='".$_SESSION['novaOS']."'");
}?>

I solved the problem changing the script to this:
<script type="text/javascript">
$(function(){
$('form').submit(function(){
var dados = new FormData();
dados.append('fotoNumMotor', $('#f_nmotor').prop('files')[0]);
$.ajax({
url: 'salvar.php',
data: dados,
type: 'POST',
processData: false,
cache: false,
contentType: false
});
});
});
</script>
Also, thanks to #JeremyHarris for calling my attention to the .append variables.

Related

Print the filename of the inputted file without refreshing the page

I'm trying to display the filename of the file that I submitted without refreshing the page using JQUERY, AJAX and PHP. But for some reason, it is not displaying.
Here's my HTML form
<form>
<input type="file" id="stegoImage" name="stegoImage">
</form>
<button type="button" id="desteganize" name="desteganize">DESTEGANIZE</button>
<div id="result"></div>
Here's my JQuery and AJAX
$(document).ready(function(){
$('#desteganize').click(function(){
var stegoImage = $("#stegoImage").prop("files")[0];
var form = new formData();
form.append("stegoImage", stegoImage);
$.ajax({
url: 'process.php',
type: 'POST',
data: form,
contentType: false,
processData:false,
success:function(result){
$("#result").html(result);
}
})
});
});
And Here's my PHP code (process.php)
$filename = $_FILES['stegoImage']['name'];
echo $filename;
$(document).ready(function() {
$('input[type="file"]').change(function(e) {
var fname = e.target.files[0].name;
$("h4").text(fname);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="file">
<h4></h4>

Display Two Images on One Click. PHP, AJAX

As I Have 2 Div Boxes. One is Input and the other one is Output Div Box as Shown in the Image Below.:
Now What I am doing is I am uploading the Image using the Help of PHP. And uploading same image on two folders named Input and Output.
What I want is When I Click Submit Button the image from input folder should be shown on Input Box and the Output Folder Image to be shown In Output Folder.
I am able to show the Input folder Image but not able to show the Output folder Image in output Div.
Here is my HTML Code :
<div class="container">
<div class="row">
<div class="col-md-6">
<h2 class="inputImage-text text-center">Input Image</h2>
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<div id="targetLayer">No Image</div>
<div id="uploadFormLayer">
<input name="fileToUpload" type="file" class="inputFile" /><br />
<input type="submit" value="Submit" class="btnSubmit btn btn-primary" />
</div>
</form>
</div>
<div class="col-md-6">
<h2 class="outputImage-text text-center">Output Image</h2>
<div class="outputDiv">
</div>
</div>
</div>
</div>
Here is my php Script:
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$sourcePath = $_FILES['fileToUpload']['tmp_name'];
$targetPath = "input/".$_FILES['fileToUpload']['name'];
$outputImage = "output/".$_FILES['fileToUpload']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
copy($targetPath, $outputImage)
?>
<img class="image-preview" src="<?php echo $targetPath; ?>" class="upload-preview" />
<?php
}
}
}
?>
and Here is the AJAX Code :
<script type="text/javascript">
$(document).ready(function(e) {
$("#uploadForm").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#targetLayer").html(data);
},
error: function() {}
});
}));
});
</script>
Use dataType option to accept the response in JSON format.
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
dataType: "json",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data.input_file);
$(".outputDiv").html(data.output_file);
},
error: function()
{
}
});
}));
});
</script>
Return both input and output files in an array format as follows
<?php
$uploadedFiles = [];
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$sourcePath = $_FILES['fileToUpload']['tmp_name'];
$targetPath = "input/".$_FILES['fileToUpload']['name'];
$outputImage = "output/".$_FILES['fileToUpload']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
copy($targetPath, $outputImage);
$uploadedFiles['input_file'] = '<img class="image-preview" src="'.$targetPath.'" class="upload-preview" />';
$uploadedFiles['output_file'] = '<img class="image-preview" src="'.$outputImage.'" class="upload-preview" />';
}
}
}
echo json_encode($uploadedFiles);
?>
Refer to this documentation regarding dataType
Add this with in your script
$(".outputDiv").html(data);
I have changed your php, html and jquery. You need to add jsonarray instead of html because it would be easy to put multiple data in json array and can get it easily in jquery .
In html i have added img tag to display image in output.
In php script, I have removed html and added json array for both the images.
In jquery script, I have replaced all img tag with src.
<div class="container">
<div class="row">
<div class="col-md-6">
<h2 class="inputImage-text text-center">Input Image</h2>
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<div id="targetLayer">No Image <img src="" id="intput-file-view"/></div>
<div id="uploadFormLayer">
<input name="fileToUpload" type="file" class="inputFile" /><br/>
<input type="submit" value="Submit" class="btnSubmit btn btn-primary" />
</div>
</form>
</div>
<div class="col-md-6">
<h2 class="outputImage-text text-center">Output Image</h2>
<div class="outputDiv">
<img src="" id="output-file-view"/>
</div>
</div>
</div>
</div>
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['fileToUpload']['tmp_name'])) {
$sourcePath = $_FILES['fileToUpload']['tmp_name'];
$targetPath = "input/".$_FILES['fileToUpload']['name'];
$outputImage = "output/".$_FILES['fileToUpload']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
copy($targetPath, $outputImage);
echo json_encode(array("inputImage"=>$targetPath,"outputPath"=>$outputImage));
exit;
}
echo json_encode(array("inputImage"=>"","outputPath"=>""));
exit;
}
}
?>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
var response=JSON.parse(data);
if(response.inputImage != "" && response.outputPath != ""){
$("#intput-file-view").attr("src",response.inputImage);
$("#output-file-view").attr("src",response.outputPath);
}
},
error: function()
{
}
});
}));
});
</script>

jQuery ajax post using FormData() append data element can't find the appended data element after post

I use the code from talkerscode.com to implement file upload using drag and drop. The code is working. Now I would like to add additional input value during in the same ajax post. I add an input tag called "user_id" in the following html code. And I append the element into the formdata object. After the change drag and drop upload still work, but the PHP code complain the $_POST["user_id"] is not defined. Here is my code. Please help!
<html>
<!-- code original from talkerscode.com -->
<head>
<link rel="stylesheet" type="text/css" href="upload_style.css">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="wrapper">
<input type="text" name="user_id", id="user_id" value="1228">
<input type="file">
<div id="drop-area">
<h3 class="drop-text">Drag and Drop Images Here</h3>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function()
{
$("#drop-area").on('dragenter', function (e){
e.preventDefault();
$(this).css('background', '#BBD5B8');
});
$("#drop-area").on('dragover', function (e){
e.preventDefault();
});
$("#drop-area").on('drop', function (e){
$(this).css('background', '#D8F9D3');
e.preventDefault();
var image = e.originalEvent.dataTransfer.files;
createFormData(image);
});
});
function createFormData(image)
{
var formImage = new FormData();
formImage.append('userImage', image[0]);
formData.append('user_id', $('#user_id').val());
uploadFormData(formImage);
}
function uploadFormData(formData)
{
$.ajax({
url: "upload_image.php",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData: false,
success: function(data){
$('#drop-area').html(data);
}});
}
</script>
----------------PHP code -------------------
<?php
if(is_array($_FILES))
{
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$sourcePath = $_FILES['userImage']['tmp_name'];
$targetPath = "images/".$_FILES['userImage']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
?>
<img src="<?php echo $targetPath; ?>">
<p> user_id = <?php echo $_POST["user_id"] ?> </p>
<?php
exit();
}
}
}
?>
-----------------------------------------------
function createFormData(image) {
var formImage = new FormData();
formImage.append('userImage', image[0]);
formData.append('user_id', $('#user_id').val()); //change formData to formImage
uploadFormData(formImage);
}
From:
formData.append('user_id', $('#user_id').val());
to:
formImage.append('user_id', $('#user_id').val());

PHP Jquery Ajax POST call, not work

As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>

Upload files with Ajax and Jquery

I've been trying to figure out how to upload a file through ajax for the past several hours and nothing.
Here's the code:
HTML:
<form action="" method="post" id="uploadForm" enctype="multipart/form-data">
<input type="file" name="image" id="image">
<input type="submit">
</form>
JS:
<script>
jQuery(document).ready(function(){
jQuery('form#uploadForm').on('submit', function(e){
e.preventDefault();
var file = jQuery('#image')[0].files[0];
var form_data = new FormData( jQuery("form#uploadForm")[0] );
form_data.append( 'image', file );
jQuery.ajax({
url: 'index.php?a=do',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: form_data,
success: function(response) {
console.log(response);
},
});
return false;
});
});
</script>
PHP:
<?php
$a = isset($_GET['a']) ? $_GET['a'] : '';
if($a <> '') {
echo "result - ";
var_dump($_POST);
die();
}
?>
As a result I get an empty array, however if I leave the file field empty, then I get:
result - array(1) {
["image"]=>
string(9) "undefined"
}
I've tried serialize(), serializeObject(), serializeArray(), $.param and every damn time I get "undefined function" error in console.
I went through dozens of similar questions on stackoverflow and nothing helped. I tried doing $.post instead of $.ajax and the "data" field which contains form_data is empty.
I need this for a Wordpress plugin and I'm trying to avoid using 3rd party JS plugins for the upload part.
$_FILES is where you check for uploaded files not $_POST.
Also in your code you actually upload the file twice as it is in the form you instantiated the form data object with then you add it again with append.
Do either
var form_data = new FormData( jQuery("form#uploadForm")[0] );
or
var form_data = new FormData();
form_data.append( 'image', file );
<html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
}
});
}));
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>

Categories