Hard time using AJAX to post pictures when button is clicked - php

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

Related

How do I save the value of this PHP dropdown using jQuery? [duplicate]

This question already has answers here:
How to save value of dropdown in PHP without submitting?
(5 answers)
Closed 2 years ago.
I have this dropdown menu in PHP and I would like to get the selected value in jQuery:
<p>
Choose device type :
<?php
echo "<select id='type_id_selected' name='device_type_id'>";
echo "<option value='Select'>Select</option>";
foreach ($dev_type_results as $row) {
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
echo "</select>"; ?>
</p>
and I tried with this jQuery code but didn't work:
<script>
$('#type_id_selected').change(function() {
var data = "";
$.ajax({
type: "POST",
data: "value=" + $(this).val(),
async: false,
success: function(response) {
data = response;
return response;
},
error: function() {
alert('Error occured');
}
});
var select = $('equipe1');
select.empty();
$.each(array, function(index, value) {
select.append(
$('<option></option>').val(value).html(value)
);
});
});
</script>
EDIT: I changed the jquery code and now I am able to get the data in jQuery, however, I dont know how to save the value somehow that I can access in PHP code
<script type="text/javascript">
$(document).ready(function() {
$("select.device_type_id").change(function() {
var selectedType = $(this).children("option:selected").val();
// access selectedType in PHP
});
});
</script>
You can get the values in JS and send an AJAX POST request to your PHP file.
HTML
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Testing</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('select.unit').change(function() {
let selectedUnit = $(this).children("option:selected").val();
console.log(selectedUnit)
$.ajax({
url: "./data.php",
method: "POST",
data: {
unit: selectedUnit
},
dataType: "text",
success: function(html) {
$('#confirmation').html(html);
}
});
});
});
</script>
</head>
<body>
<select id="choose-first-unit" class="span-four unit">
<option value="m3">cubic meters</option>
<option value="cm3">cubic centimeters/milliliters</option>
<option value="dm3">cubic decimeters/litres</option>
<option value="hl">hectolitres</option>
<option value="cl">centilitres</option>
</select>
<div id="confirmation"></div>
</body>
</html>
PHP Code: for first PHP File
<?php
session_start();
$unit = $_POST['unit'];
$_SESSION['unit'] = $unit;
?>
And in the other file where you want to access the value
session_start();
$data = $_SESSION['unit'];

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.

Undefined index: files when uploading using ajax and 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);
}
});
}

How to trigger a colorbox gallery with form submit

I have a document with two pages. The first one sends a folder name via form submit
<form method="post" >
<input type="hidden" name="portfolio" value="directory">
<input type="submit" value="author">
</form>
the second one receives this folder name and open the files with glob function
<?php
header('Content-Type: application/json');
$directoryName = $_POST['portfolio'];
echo json_encode (glob($directoryName."/".'*.{jpg,mp4}', GLOB_BRACE));
?>
...finally images appear on the first page again via Ajax
$(document).ready(function(){
$('form').submit(function(e) {
var data = $(this).serialize();
e.preventDefault();
$.ajax({
url: "PAGE2.php",
data: data,
type: "POST",
dataType: "json",
success: function(response) {
var html = "";
$.each(response, function(i, val) {
var fileExtension = val.substring(val.lastIndexOf('.'));
if (fileExtension == ".jpg") {
html += '<img src="'+val+'" height=250></img>';
}
else if (fileExtension == ".mp4") {
html += '<video width="320" height="240" src="'+val+'" type="video/mp4"controls autoplay loop></video>';
}
});
$("#display").html(html);
}
});
});
});
up to here no href tags...
I need to know how to display images like modal gallery with colorbox plugin.
I've tried this without success
$(document).ready(function(){
$('form').submit(function(e) {
var data = $(this).serialize();
e.preventDefault();
$.ajax({
url: "PAGE2.php",
data: data,
type: "POST",
dataType: "json",
success: function(response) {
var html = "";
$.each(response, function(i, val) {
var fileExtension = val.substring(val.lastIndexOf('.'));
if (fileExtension == ".jpg") {
html += '<img src="'+val+'" height=250></img>';
}
else if (fileExtension == ".mp4") {
html += '<video width="320" height="240" src="'+val+'" type="video/mp4"controls autoplay loop></video>';
}
});
$("#display").html(html);
$("#link").colorbox({ inline:true, href: "#display"});
}
});
});
});
<body>
...
<div id="display" style="display:none;"></div>
<a id="link" style="display:none"></a>
</body>
PAGE1.php
<!DOCTYPE HTML>
<html lang="">
<head>
    <meta charset="UTF-8">
    <title>page1</title>
<link rel="stylesheet" href="colorbox.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="../jquery.colorbox.js"></script>
<script>
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({
html:data,
rel:'group1'
});
},
'html');
return false;
});
});
</script>
</head>
<body>
<div class="container">
<form action="page2.php" method="post" id="formID">
<input type="hidden" name="var" value="directory">
<input type="submit" value="author">
</form>
</div>
</body>
</html>
PAGE2.php
<!DOCTYPE HTML>
<html lang="">
<head>
<meta charset="UTF-8">
<title>page2</title>
</head>
<body>
<?php
$variable = $_POST['var'];
$img_dir = $variable . "/";
foreach(glob($img_dir . '*.jpg') as $image) {
echo '<img src="'.$image.'">'.'<img class="group">';
}
?>
</body>
</html>

How to upload image using jQuery?

I attached JS and index.php file. This code not working for image, but for type text it is working properly. I have searched very much but not getting how can upload image by jQuery.
index.php file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title><?= TITLE . ' | ' . ucfirst($page); ?></title>
<!-- Tell the brow form_groupser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<?php include('inc/css-inc.php'); ?>
</head>
<body>
<div class="row form_group">
<div for="inputName" class="col-sm-2 control-div">Image A. </div>
<div class="col-sm-4">
<input type="file" class="form-control" id="qimage" name="imga" onchange="un(this.value)">
</div>
<button type="button" onClick="return savequestion()" id="savequestion" class="btn btn-info pull-right"><?= $act; ?></button><!--</form>-->
<!-- jQuery 2.1.4 -->
<script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
Js file
$('#savequestion').click(function () {
var qimage1 = $('#qimage').prop('files')[0];
var form_data = new FormData();
form_data.append('qimage', qimage1);
form_data.append('mod', mod);
form_data.append('req', req);
$.ajax({
url: 'common_process.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function (data) {
alert(data);
}
});
});
Try this:
HTML:
<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>
Jquery:
$('#upload').on('click', function() {
var file_data = $('#pic').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,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php:
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
This will uload your file to "uploads" folder. And also check for the folder write permission.

Categories