Upload AJAX with input text and input file in PHP - javascript

In the JS site in have to send an ajax containing an input file to upload AND input texts
var formdata = new FormData();
formdata.append("id",$('#id').val());
formdata.append("upload_url",$('#upload_url').val());
formdata.append("type",$('#type').val());
formdata.append("file",$('#upload').prop('files')[0]);
formdata.append("label",$('#label').val());
formdata.append("filter_from",$('#filter_from').val());
formdata.append("filter_to",$('#filter_to').val());
formdata.append("zone_geographique",$('#zone_geographique').val());
formdata.append("actif",$('#actif').val());
formdata.append("leafs",$('#affectedLeafs').val());
$.ajax({
url: 'form.php?action=formation_save',
data: formdata,
processData: false,
contentType: false,
type: 'POST',
success: function() {
$('.formationSection > div').slideToggle();
}
});
But when , in the PHP side in the formation_save file, I do a $_POST, PHP returns me NULL.
and when I do also a file_get_contents("php://input");
PHP returns also me NULL
But Why ? How to make it working ?
PHP code
<?php
$postValues = $_POST;
$phpinput = file_get_contents("php://input");
var_dump($postValues);var_dump($phpinput);

Related

upload a file using jquery post and php

trying to upload a file without using a form and using $.post to transfer the file
I suppose the problem is on php side, but I'm not sure
<input type='file' id='inpfile'>
$(inpfile).on('change', function(){
var fd = new FormData();
var file = $(inpfile)[0].files[0];
fd.append('file', file);
fd = JSON.stringify(fd);
$.post('pro.php', {fn: 'upload', args: [fd]}, function(data){
console.log(data);
});
});
pro.php
if(isset($_POST['fn'], $_POST['args'])){
$fn = $_POST['fn']; $args = $_POST['args'];
$fn(...$args);
}
function upload($fd){
$fd = json_decode($fd);
$fname = $fd->file;
$destination = 'upload/' . $fname;
move_uploaded_file($fname, $destination);
}
you cannot upload file simply with $.post method and form data when changed to string cannot send file. you need to add contentType:false and processData:false, and remove this code fd = JSON.stringify(fd); Moreover, your jquery does not recognize the change since you have not addressed it properly. it should be $('#inpfile').on('change', function()
instead of just $(inpfile).on('change', function()
you can try this code.
<input type='file' id='inpfile'>
$('#inpfile').on('change', function(){
var fd = new FormData();
var files = $('#inpfile')[0].files;
fd.append('file',files[0]);
$.ajax({
url: 'pro.php',
method: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
//your code.....
}
});
});
and in the PHP server side you check it with files method instead of post method. that is
if(isset($_FILES['file']['fd'])){
your code.......
}

upload image from multiple form with ajax and php

in PHP page with multiple form tag to register user information.
using ajax to collect data and post to register PHP page now i want to upload image to server folder but i failed.
my html code:
<label for="upimage" class="btn btn-sm btn-primary mb-75 mr-75">Upload Image</label>
<input type="file" id="upimage" hidden accept="image/*" name="image"/>
Javascript Code:
let data1 = document.getElementById('data1').value,
data2 = document.getElementById('data1').value,
data3 = document.getElementById('data1').value,
upimage = document.getElementById('upimage').value;
$.ajax({
url:"././newregister.php",
method:"POST",
data:{action:'newregister', data1:data1, data2:data2,
data3:data3, upimage:upimage},
success:function(data){
alert(data);
}
});
newregister php code:
$uploads_dir = './uploads';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
echo "Sucsess";
}
else
{
echo "Error" . $_FILES["file"]["error"] ;
}
ERR: Undefined index: file in .... on line ....
Given by POST method uploads
Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
Your current solution lacks enctype, that's why your file is not getting uploaded to the server and therefore isn't in the superglobal variable $_FILES.
As ferikeem already said. Wrap your data in a FormData Object and send it that way.
See: https://stackoverflow.com/a/5976031/10887013
JavaScript
let fd = new FormData();
fd.append("you_file_key_here", $("#upimage")[0].files[0]);
fd.append("data1", $("#data1")[0].value);
fd.append("data2", $("#data2")[0].value);
fd.append("data3", $("#data3")[0].value);
$.ajax({
url: "././newregister.php",
method: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
alert(data);
}
});
$_FILES["file"], here is your problem.
In $_FILES array key "file" doesn't exists. As I see you need to change $_FILES["file"] with $_FILES["upimage"].

jQuery AJAX - send file and variable to PHP in single request

I have the following HTML form for uploading a file (picture):
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
I use the following JavaScript/jQuery to send form data and a variable value to PHP script:
var variable1= 1;
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: {form_data, number: variable1},
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
The PHP script (upload.php) looks like this:
$filename;
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
$filename = $_FILES['file']['name'];
}
echo $filename;
When I run this code, PHP throws some undefined index errors. If I use only "data: form_data" in ajax request (without variable1), then the file uploads successfully, but I need to send the variable too. How can I do this?
You can also append the number key => value to to the form data as
form_data.append('number', variable1);
Then in Ajax call
data: form_data,
why don't you append this value like this
form_data.append('number', variable1);
Append the variable to form_data
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('number', variable1); // append variable
In ajax
processData: false,
data: form_data, // data
type: 'post',
I am following your code because I need FILES image data and multiple variables in PHP script for insertion operation in the database. But I am unable to access any single variable in the php script. I did below to access your number variable. Please correct me.
//upload.php
if(isset($_GET['number'])){
$num = $_GET['number'];
echo $num;
}else{
echo 'not set';
}

Javascript and PHP. Sending Multiple Array to PHP Using Ajax and Convert it to PHP Array

I need some help. I am trying to send multiply array of width and length to php, straight forward. I don't want to save it to any HTML field, however it's not working. I am getting the width and length from html text are and convert it to a number and then add it to an array in javascript.
Here is the code for that
var widthL = [];
var lengthL = [];
var widths = document.wall.width.value;
var lengths = document.wall.length.value;
var wNumber = Number(widths);
var lNumber = Number(lengths);
widthL.push(JSON.stringify(wNumber));
lengthL.push(JSON.stringify(lNumber));
This is the Ajax code I am using to send it to PHP
$.ajax( {
type: "POST",
url: "./Summary.php",
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
In PHP I am using this code to receive it. But I am not getting things back.
<?php
$lengths = json_decode($_POST['lengths']);
$widths = json_decode($_POST['widths']);
echo 'This is the width: '.$widtsL;
echo 'This is the length: '.$lengths;
?>
I was hopping that someone could help me out here.
First you should specify the content type in the ajax POST:
$.ajax( {
type: "POST",
url: "./Summary.php",
contentType: "application/json; charset=UTF-8", // Add content type
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
then in PHP:
$request_body = file_get_contents('php://input'); //This reads the raw POST data
$json = json_decode($request_body); // Then parse it to JSON
$lengths = $json->lengths;
$widths = $json->widths;
please add a POST parameter name as dataType,type it value JSON,
the Ajax data param value use key=value&key=value format
then in php file enter debug code

Upload image using ajax and form submitting

I want to upload an image to the server using Ajax, but there is a problem. Would somebody please help me what is wrong here. I could submit the image using submit form but not ajax.
here is my code:
html:
<div id="uploadPic" onclick="getFile()">
Select a photo to upload
</div>
<form name="myForm" id="avatar_form" enctype="multipart/form-data" method="post" action="">
<div style='height: 0px;width:0px; overflow:hidden;'>
<input id="upfile" class="botpic" type="file" name="avatar" value="upload" required="" onchange="sub1()">
</div>
</form>
javascript:
function getFile(){
document.getElementById("upfile").click();
}
function sub1(){
var photo = document.getElementById("upfile");
var file = photo.files[0];
data = new FormData();
data.append('file', file);
$.ajax({
url: 'url',
data: data
enctype: 'multipart/form-data',
processData: false, // do not process the data as url encoded params
contentType: false, // by default jQuery sets this to urlencoded string
type: 'POST',
success: function ( output ) {
document.getElementById('picTmp').innerHTML = output;;
}
});
}
PHP code:
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
.......
}
The first thing I notice is that you're missing a comma after the data parameter declaration. That might be your only issue.
$.ajax({
url: 'url',
data: data,
enctype: 'multipart/form-data',
//etc...
What's the name of your PHP script? That's what you should specify as 'url':
url: 'script_name.php',
Maybe this plugin could help you
Jquery Form
I had a lot of problem making from myself and with this plugin everething works, just try, this
$('form').ajaxForm(function() {
alert("Thank you for your comment!");
});
I would guess that without using preventDefault() method in your script,
you submit the form to the same page using action="" and method="post", thus never entering your $.ajax();
I've done something like this
$('#query_projects').submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
var request = $.ajax({
type: 'POST',
url: 'query_tab_projets.php',
mimeType:'application/json',
dataType:'json',
data: formData,
contentType: false,
processData: false,
success: function(data){
alert(JSON.stringify(data,null,4));
},
error: function(msg){
alert(JSON.stringify(msg,null,4));
}
});
});
where #query_projects is my form id
Finally I found where the problem is. Maybe it is useful for others struggling with ajax uploading a file.Now it is working perfectly.
The solution is:
In the php code, all the ["avatar"] should be replaced with ["file"] as we are sending the file specified as file in ajax.

Categories