Undefined index: files when uploading using ajax and php - php

I'm trying to create a page that uploads an image. When I hit the upload.php I get this error
Undefined index: files in E:\My-Laptop\Wamp\www\image-upload\upload.php on line 3
and if I do print_r($_FILES)I get an empty array.
I'm not sure where I went wrong.
Here is my code.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container" >
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="files[]" id="file" multiple>
<!-- Drag and Drop container-->
<div class="upload-area" id="drop-zone">
<h1>Drag and Drop file here<br/>Or<br/>Click to select file</h1>
</div>
</form>
</div>
<script src="http://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="js/main.js"></script>
</body>
</html>
my main.js
$(document).ready(function(){
var dropZone = document.getElementById('drop-zone');
dropZone.ondrop = function(e){
e.preventDefault();
var transfer = e.dataTransfer.files;
uploadImage(transfer);
}
dropZone.ondragover = function(e){
return false;
}
dropZone.ondragleave = function(e){
return false;
}
});
function uploadImage(files){
var dataString = 'files='+files;
$.ajax({
type: 'POST',
url: 'upload.php',
data: dataString,
success: function(response){
console.log(response);
}
});
}
my upload.php
<?php
print_r($_FILES['files']);

Hope it's help:
function uploadImage(files){
var data = new FormData();
$.each( files, function( key, value ){
data.append( key, value );
});
$.ajax({
type: 'POST',
url: 'upload.php',
data: data,
success: function(response){
console.log(response);
}
});
}

Related

AJAX send value from js to php

been tring to send var form js to php and do some manipulation but I keep receving this error. Is it even possible to send the value through to php?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<?php
echo $_POST['name'];
?>
<button id='button'>hi</button>
</body>
<script src="index.js"></script>
</html>
$("#button").click(function(){
$.post("index.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
});
});
I created one index.php file here this should work for you.
<?php
if ($_POST) {
echo json_encode(['data' => $_POST['name'], 'success' => true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<script
src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
crossorigin="anonymous">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.15.1/d3.min.js"></script>
</head>
<body>
<input type="text" name='name'>
<p id="hey"></p>
<div id='test'></div>
<button id='button'>hi</button>
</body>
<script>
let data = {
name: "Donald Duck",
city: "Duckburg"
};
$("#button").click(function(){
$.ajax({
type: "POST",
url: 'index.php',
data: data,
dataType: 'json'
}).done(function(response) {
if (response.success) {
$('#hey').html('success');
$('#test').html(response.data);
}
});
});
</script>
</html>
This does not work because when you first load the page $_POST['name'] is undefined. Your javascript code does not trigger a submit (= reload to send the data). $_POST['name'] is never set because it will not be updated on the fly. To make this work make a separate php file which only handles the POST data from your javascript and returning a value.
/* call post.php and add console.log to track data */
$("#button").click(function(){
$.post("post.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
$("#hey").append(status);
console.log(data);
});
});
<?php
// post.php
if($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['name'];
}
This is of course very basic. In order to communicate effectively you should look into formating the data e.g. into JSON.

Hard time using AJAX to post pictures when button is clicked

I am having issues understanding ajax. I am trying to upload the array of pictures when the button on the HTML is clicked so the images update onto the HTML site without it refreshing.
My html:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Homework 12</title>
</head>
<body>
<h1>Pictures of Pets</h1>
<form id="my_form_id" action="index.php" method="POST">
<input type="submit" value="Dog">
</form>
<div id="answer"></div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('#my_form_id').on('submit', function(e){
//Stop the form from submitting itself to the server.
e.preventDefault();
var dog = $('#dog');
$.ajax({
type: "POST",
url: 'index.php',
data: {postdog:dog},
success: function(data){
// alert(data);
$( "#answer" ).append(data);
}
});
});
});
</script>
</body>
</html>
My php
<?php
$dogs = array("Corgi", "Husky", "Samoyed");
if(isset($_POST['postdog'])){
foreach ($dogs as $dog) {
echo "<img src='images/dogs/$dog.jpg'> <br>";
}
};
$cats = array("Scottish_Fold", "Persian", "Himalayan");
foreach ($cats as $cat) {
echo "<img src='images/dogs/$cat.jpg'> <br>";
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Homework 12</title>
</head>
<body>
<h1>Pictures of Pets</h1>
SUBMIT
<div id="answer"></div>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function get_result()
$.ajax({
type: "POST",
url: 'upload.php',
data: {action: 'upload'},
success: function(data){
// alert(data);
$( "#answer" ).append(data);
}
});
}
</script>
</body>
</html>
upload.php
<?php
if(isset($_POST['action']) && $_POST['action'] == 'upload' ){
$dogs = array("Corgi", "Husky", "Samoyed");
foreach ($dogs as $dog) {
echo "<img src='images/dogs/$dog.jpg'> <br>";
};
$cats = array("Scottish_Fold", "Persian", "Himalayan");
foreach ($cats as $cat) {
echo "<img src='images/dogs/$cat.jpg'> <br>";
}
}
?>
HTML :
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Homework 12</title>
</head>
<body>
<h1>Pictures of Pets</h1>
<form enctype="multipart/form-data" action="index.php" method="post" id="my_form_id">
<input name="file[]" type="file" />
<button class="pets">Add More</button>
<input type="button" value="Image upload" id="upload"/>
</form>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</body>
</html>
Script :
$(document).ready(function(){
$('.pets').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'index.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
index.php :
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "pets/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "Your pets images has been uploaded successfully <br>";
} else{
echo "Error, please try again! <br />";
}
}

How can I consume and autocomplete a field from url that contents json information

I'm trying to autocomplete a field from url that contents json information, I find a lot of examples that I dont know where is my error.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://camino-rest-service.cloudhub.io/caminoAPI/GetCamino",
data: { query: request.term },
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el.ubicaciones
};
});
response(transformed);
},
error: function () {
response([]);
}
});
});
});
} );
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
JSON example
[
{
"ubicaciones": "San Gabriel, Provincia de Carchi"
},
{
"ubicaciones": "El Ángel, Provincia de Carchi"
},
{
"ubicaciones": "Ambuquí, Provincia de Imbabura"
}
]
some could says who is my error? I try everthing that I know
$( function() {
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: "http://camino-rest-service.cloudhub.io/caminoAPI/GetCamino",
dataType: "json",
success: function (data) {
var transformed = $.map(data, function (el) {
return {
label: el
};
});
response(transformed);
},
error: function () {
response([]);
}
});
}
});
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
you have syntax error in code and link you provide is nor respond to POST or GET method (i fix only syntax issue)

empty array when post data ajax phonegap

I am trying use ajax in phonegap. When I post data - php always take null array. And it is not wrong code.
I wonder if something with url is wrong. Is it possible? Or maybe I should add some more access? I have really no idea what i do incorrectly.
incorrectly..
Here is my code:
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
</head>
<body>
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<div id="result"></div>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var values = $(this).serialize();
$.ajax({
url: "http://localhost/inne/phonegap_test/agregar.php",
type: "post",
data: values ,
success: function (response) {
console.log("okey");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
</script>
</body>
</html>
php:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
var_dump($_POST);
It is because script sends request immediately page is loaded.
You should use this code:
$("#foo").submit(function(e){
var values = $(this).serialize();
$.ajax({
url: "http://localhost/inne/phonegap_test/agregar.php",
type: "post",
data: values ,
success: function (response) {
console.log("okey");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
e.preventDefault();
return false;
});

Image isnt getting in editor [PHP image upload]

Hello I tried every think i can and searched online but noting came up.
My index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<!-- include libraries BS3 -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" />
<script type="text/javascript" src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/codemirror.min.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/theme/blackboard.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/theme/monokai.min.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/codemirror.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/codemirror/3.20.0/mode/xml/xml.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/codemirror/2.36.0/formatting.min.js"></script>
<!-- include summernote css/js-->
<link href="include/summernote.css" / rel="stylesheet">
<script src="include/summernote.min.js"></script>
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: 200,
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
});
function sendFile(file, editor, welEditable) {
data = new FormData();
data.append("file", file);//You can append as many data as you want. Check mozilla docs for this
$.ajax({
data: data,
type: "POST",
url: 'savetheuploadedfile.php',
cache: false,
contentType: false,
processData: false,
success: function(url) {
editor.insertImage(welEditable, url);
}
});
}
});
</script>
<head>
<title>Bootstrap WysWig Editor Summernote</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>
<body>
<div class="container">
<div class="row">
<form class="span12" id="postForm" action="index.php" method="POST" enctype="multipart/form-data" >
<fieldset>
<legend>MyCodde.Blogspot.com Editor</legend>
<p class="container">
<textarea class="input-block-level" id="summernote" name="content" rows="18">
</textarea>
</p>
</fieldset>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
</div>
</div>
</body>
</html>
My savetheuploadedfile.php
<?php
$dir_name = "uploads/";
move_uploaded_file($_FILES['file']['tmp_name'],$dir_name.$_FILES['file']['name']);
echo "http://localhost:90/summernote/".$dir_name.$_FILES['file']['name'];
?>
Problem is when i use this like that image is uploading but image doesn't adding to editor, From chrome tools i see this error Uncaught TypeError: Cannot read property 'insertImage' of undefined I found this code to fix it.
$('.summernote').summernote('editor.insertImage', url);
But still image is uploading but not adding to editor. Thank you for helping.
The onImageUpload callback signature was changed, try this modified JavaScript:
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: 200,
onImageUpload: function(files) {
sendFile(files[0]);
}
});
function sendFile(file, editor, welEditable) {
data = new FormData();
data.append("file", file);//You can append as many data as you want. Check mozilla docs for this
$.ajax({
data: data,
type: "POST",
url: 'savetheuploadedfile.php',
cache: false,
contentType: false,
processData: false,
success: function(url) {
$('#summernote').summernote('editor.insertImage', url);
}
});
}
});
</script>
Basically you don't get the editor object anymore but have to fetch it yourself in the success callback.

Categories