PHP 7.x can't get post data using Ajax - javascript

After submitting the form I can't get post data, no clue where is the problem but I think it's the js file. I'm not advanced in using Ajax so I guess this is the problem.
I'm getting error that can't get $name, $projectFile etc.
So should I rewrite the js or PHP? There are no syntax errors, I want this form to be dynamically submitted with Ajax.
html
<form enctype="multipart/form-data" id="upload-form" class="upload-container">
<label for="projectname">Project Name</label>
<input type="text" id="projectname" name="projectname">
<label for="projecturl">Project Link (Gitlab/Github)</label>
<input type="text" id="projecturl" name="projecturl">
<div class="fileuploader">
<label for="projectpreview">Project Upload</label>
<input type="file" id="projectpreview" name="projectpreview">
</div>
<label for="projectwebsite">Project Website</label>
<input type="text" id="projectwebsite" name="projectwebsite">
<button type="submit" id="upload">Add Project</button>
</form>
js
$('#upload-form').on('submit', (e) => {
e.preventDefault();
let $this = $(this);
let $name = $('#projectname');
let $url = $('#projecturl');
let $file = $('#projectpreview');
let $web = $('#projectwebsite');
$.ajax({
url: '../assets/upload.php',
type: 'POST',
data: new FormData($(this)),
contentType: false,
cache: false,
processData: false,
success: (response) => {
console.log(response);
}
});
// VALIDATION
$('#file').change(() => {
let file = this.files[0];
let imageFile = file.type;
let match = ['image/jpeg', 'image/png', 'image/jpg'];
if (!((imageFile == match[0]) || (imageFile == match[1]) || (imageFile == match[2]))) {
alert('Pleas select valid file: JPEG, PNG, JPG');
$('#file').val('');
return false;
}
});
});
php
<?php
include('db.php');
$name = $_POST['projectname'];
$projectUrl = $_POST['projecturl'];
$projectFile = $_FILES['projectpreview'];
$projectWebsite = $_POST['projectwebsite'];
$date = date('Y-m-d H:i:s');
if (!empty($name) || !empty($projectUrl) || !empty($projectFile['name']) || !empty($projectWebsite)) {
$upFile = '';
if (!empty($projectFile['type'])) {
$fileName = time().'_'.$projectFile['name'];
$valid_extensions = array('jpeg', 'jpg', 'png');
$temporary = explode('.', $projectFile['name']);
$file_extension = end($temporary);
if ((($_FILES['hard_file']['type'] == 'image/png') || ($projectFile['type'] == 'image/jpeg') || ($projectFile['type'] == 'image/jpg')) && in_array($file_extension, $valid_extensions)) {
$sourcePath = $projectFile['tmp_name'];
$targetPath = 'img/photos/'.$fileName;
if (move_uploaded_file($sourcePath, $targetPath)) {
$uploadedFile = $fileName;
}
}
}
if ($connection->query("INSERT INTO projects VALUES('', '$name', '$projectUrl', '$uploadedFile', '$projectWebsite', '$date')")) {
exit('success');
} else {
exit('fail');
}
}

i think you have to remove the contentType argument (and use serializeArrayfrom your Form jQuery Object):
$.ajax({
url: '../assets/upload.php',
type: 'POST',
data: $(this).serializeArray(),
processData: false,
success: (response) => {
console.log(response);
}
});

Convert form fields to key value page and then pass that as the data in AJAX.
$('#upload-form').on('submit', (e) => {
e.preventDefault();
let $this = $(this);
var formData = "";
$.each($('#upload-form').serializeArray(), function(i, field) {
formData += field.name + ": \""+ field.value + "\","
});
formData = formData.replace(/^,|,$/g,'');
console.log(formData);
$.ajax({
url: '../assets/upload.php',
type: 'POST',
data: formData,
contentType: false,
cache: false,
processData: false,
success: (response) => {
console.log(response);
}
});
// VALIDATION
$('#file').change(() => {
let file = this.files[0];
let imageFile = file.type;
let match = ['image/jpeg', 'image/png', 'image/jpg'];
if (!((imageFile == match[0]) || (imageFile == match[1]) || (imageFile == match[2]))) {
alert('Pleas select valid file: JPEG, PNG, JPG');
$('#file').val('');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form enctype="multipart/form-data" id="upload-form" class="upload-container">
<label for="projectname">Project Name</label>
<input type="text" id="projectname" name="projectname">
<label for="projecturl">Project Link (Gitlab/Github)</label>
<input type="text" id="projecturl" name="projecturl">
<div class="fileuploader">
<label for="projectpreview">Project Upload</label>
<input type="file" id="projectpreview" name="projectpreview">
</div>
<label for="projectwebsite">Project Website</label>
<input type="text" id="projectwebsite" name="projectwebsite">
<button type="submit" id="upload">Add Project</button>
</form>

Related

Send file with jquery and recive in PHP (No plugIn)

I'm trying to send a file using AJAX with the form but the PHP file seems to receive nothing, not only the files but also the form elements. In PHP if i try to get a value from the $_POST i get an Undefined Index.
I've tried:
$("#animal-insert").click((e) => {
e.preventDefault();
var fd = $("#animal-form-input");
var files = $("#file")[0].files[0];
fd.append("file", files);
$.ajax({
url: "php_utility/ajax/admin-animal.php",
type: "post",
data: fd,
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
if (response === "allok") {
showModalError("Registrato Correttamente", "modalsuccess");
} else {
showModalError("Non Registrato Correttamente", "modalerror");
}
},
});
and the method you see in the code below. I'm restricted to do this without plugins.
I was also trying with the $.post() but if i understood correctly i have to use $.ajax() to add the processData: false to send files.
HTML
<form method="POST" action="" id="animal-form-insert" enctype="multipart/form-data">
<div class="span-1-of-2">
<label for="specie" class="label">Specie Animale:</label>
<input type="text" class="animal-input" id="specie" name="specie" required placeholder="Pavo cristatus">
<label for="an-name" class="label">Nome Comune:</label>
<input type="text" class="animal-input" id="an-name" name="an-name" required placeholder="pavone comune">
</div>
<div class="span-1-of-2">
<label for="biom" class="label">Bioma/Habitat:</label>
<select class="animal-input" name="biom" id="biom" required>
<option value="Savana">Savana</option>
<option value="Tundra">Tundra</option>
<option value="Pianura">Pianura</option>
</select>
<label for="zoo-zone" class="label">Zona Zoo:</label>
<select class="animal-input" name="zoo-zone" id="zoo-zone">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="F">F</option>
<option value="PN">PN</option>
</select>
</div>
<label for="animal-photo" class="label">Foto Animale:</label>
<input type="file" id="animal-photo" name="animal-photo" accept=".jpg,.jpeg.png" required>
<label for="aniaml-desc" class="label">Descrizione:</label>
<textarea class="animal-input-desc" name="animal-desc" id="animal-desc" required></textarea>
<button type="submit" name="animal-insert" id="animal-insert" class="btn btn-block">Aggiungi</button>
</form>
JS
$("#animal-insert").click((e) => {
e.preventDefault();
var formData = {
specie: $("#specie").val(),
anname: $("#an-name").val(),
biom: $("#biom").val(),
zoozone: $("#zoo-zone").val(),
animaldesc: $("#animal-desc").val(),
animalphoto: $("#animal-photo")[0].files[0],
submit: "submit",
};
console.log(formData);
$.ajax({
url: "php_utility/ajax/admin-animal.php",
type: "post",
data: JSON.stringify(formData),
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
if (response === "allok") {
showModalError("Registrato Correttamente", "modalsuccess");
} else {
showModalError("Non Registrato Correttamente", "modalerror");
}
},
});
});
PHP
<?php
error_log($_POST['specie']);
if (isset($_POST['specie'])) {
$animalspecie = $_POST['specie'];
$animalName = $_POST['anname'];
$animalBiom = $_POST['biom'];
$animalZone = $_POST['zoozone'];
$animalDesc = $_POST['animaldesc'];
$animalPhoto = $_FILES['animalphoto'];
$animalPhotoName = $animalPhoto['name'];
$photoTmp = $animalPhoto['tmp_name'];
$photoErr = $animalPhoto['error'];
$photoType = $animalPhoto['type'];
error_log("not here");
$formats = ["image/jpg", "image/jpeg", "image/png"];
require_once '../sql/utility.php'; //file with functions for db
require_once '../checks.php'; //file with some type checks
if (empty($animalspecie) || empty($animalName) || empty($animalBiom) || empty($animalZone) || empty($animalDesc) || empty($animalPhoto)) {
echo "emptyinput";
exit();
}
if (!preg_match('/[A-Z]+[a-z]+\s[a-z]+/', $animalspecie)) {
echo "invalidspecie";
exit();
}
if (!in_array($photoType, $formats)) {
echo "invalidformat";
exit();
}
if ($photoErr !== 0) {
echo "fileerror";
exit();
}
$tmpExtension = explode("/", $photoType);
$photoExtension = end($tmpExtension);
$photoNewName = preg_replace('/\s+/', '', $animalName) . preg_replace('/\s+/', '', $animalName) . "." . $photoExtension;
$photoDestination = "//resurces/images/animals/" . $photoNewName;
move_uploaded_file($photoTmp, $_SERVER['DOCUMENT_ROOT'] . $photoDestination);
$result = insertAnimal($conn, $animalspecie, $animalName, $animalBiom, $animalZone, $animalDesc);
echo $result;
}
You should create a new FormData() and append your form values and files to it, and then send it as 'multipart/form-data' in the data (not body) param.
$("#animal-insert").click((e) => {
e.preventDefault();
var formData = new FormData();
formData.append("specie", $("#specie").val())
formData.append("anname", $("#an-name").val())
formData.append("biom", $("#biom").val())
formData.append("zoozone", $("#zoo-zone").val())
formData.append("animaldesc", $("#animal-desc").val())
formData.append("animalphoto", $("#animal-photo")[0].files[0])
formData.append("submit", "submit")
$.ajax({
url: "php_utility/ajax/admin-animal.php",
method: "post",
data: formData,
cache: false,
mimeType: "multipart/form-data",
contentType: false,
processData: false,
success: function (response) {
console.log(response);
if (response === "allok") {
showModalError("Registrato Correttamente", "modalsuccess");
} else {
showModalError("Non Registrato Correttamente", "modalerror");
}
},
});
});
In PHP Your files will be avaiable in $_FILES array, and the other data will be in $_POST array.
More on FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData

I want to key and values using push array using jquery and laravel [duplicate]

This question already has answers here:
Can I append an array to 'formdata' in javascript?
(13 answers)
Closed 2 years ago.
Array push in jquery with key and value.When i use below code getting [object Object]. How to fix it?
Laravel:
public function store(Request $request){
$add_new_services_arr = json_decode($request['all_checked_services_arr']);
if(!empty($add_new_services_arr)){
foreach ($add_new_services_arr as $key => $value) {
$lab_services_obj = new Services;
$lab_services_obj->user_id = $userId;
$lab_services_obj->service_name = $value->service_name;
$lab_services_obj->price = $value->service_price;
$lab_services_obj->save();
}
}
jQuery
var all_checked_inputs = $('#list_add_services_div .service input[type=checkbox]:checked');
var all_checked_services_arr = [];
$(all_checked_inputs).each(function() {
var service_name = $(this).attr('service_name');
var service_price = $(this).attr('service_price');
all_checked_services_arr.push({
service_name: service_name,
service_price: service_price,
});
});
console.log('hello', all_checked_services_arr);
Ajax:
var form = $('#add_lab_form_id')[0];
var formData = new FormData(form);
// formData.append('add_new_services_arr', JSON.stringify(add_new_services_arr));
formData.append('all_checked_services_arr', all_checked_services_arr);
//console.log(formData);
$.ajax({
url: site_url + '/Laboratory/StoreAjax',
type: 'POST',
// contentType: "application/json;", // for passing array to the ajax
// data: JSON.stringify(all_checked_services_arr),
data: formData,
success: function(response) {
console.log('response', response);
if (response.status == "success") {
toastr.success('Record added successfully.');
window.location.href = site_url + '/Laboratory/List';
} else if (response.status == "false") {
toastr.warning('Record not added.');
} else if (response.status == 'error' && response.code == 402) {
console.log('response', response.errors);
toastr.error(response.message);
}
},
cache: false,
contentType: false,
processData: false
});
Whenever I console this getting :"all_checked_services_arr" => "[object Object]"
formData.append('add_new_services_arr', JSON.stringify(add_new_services_arr));
But you can simplify the creation
const all_checked_services_arr = $('#list_add_services_div .service input[type=checkbox]:checked').map(function() {
return {
service_name: $(this).attr('service_name'),
service_price: $(this).attr('service_price')
}
}).get();
console.log(all_checked_services_arr)
console.log(JSON.stringify(all_checked_services_arr))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list_add_services_div">
<div class="service">
<input type="checkbox" service_name="name1" service_price="$1" checked />
<input type="checkbox" service_name="name2" service_price="$2" />
<input type="checkbox" service_name="name3" service_price="$3" checked />
</div>
</div>
I would however use data-attributes and not custom attributes
const all_checked_services_arr = $('#list_add_services_div .service input[type=checkbox]:checked').map(function() {
return {
service_name: $(this).data('name'),
service_price: $(this).data('price')
}
}).get();
console.log(all_checked_services_arr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="list_add_services_div">
<div class="service">
<input type="checkbox" data-name="name1" data-price="$1" checked />
<input type="checkbox" data-name="name2" data-price="$2" />
<input type="checkbox" data-name="name3" data-price="$3" checked />
</div>
</div>

CodeIgniter file upload error “You did not select a file to upload” using Ajax

I've seen and tried a few answers that are similar to this question, but it still displays the same error.
The console is also giving the error: Uncaught TypeError: Cannot read property 'length' of undefined at Function.each (jquery-1.10.2.js:631)
My view:
<form action="https://dev.vmc.w3.uvm.edu/xana/sensors/deployments" class="basicForm aboutForm form-horizontal" id="deploymentForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="fldFileName" class="col-sm-4 control-label">Image</label>
<div class="col-sm-8">
<input type="file" name="fldFileName" value="" class="form-control" id="fldFileName" />
</div>
</div>
<button type="button" class="btn btn-primary" id="newSensorSubmit">Save</button>
</form>
javascript to submit form:
$(document).on("click", "#newSensorSubmit", function(event){
var posturl="<?php echo site_url("sensors/add_deployment");?>";
var formData = new FormData();
var fldFileName = $('#fldFileName').val();
formData.append('fldFileName', fldFileName);
jQuery.ajax({
url: posturl,
data: formData,
cache: false,
mimeType: "multipart/form-data",
dataType: 'json',
contentType: false,
processData: false,
type: 'POST',
success: function(data){
if(data.status === 'success') {
//handle success
}
else {
//handle fail
}
},
error: (error) => {
$('#articleErrorText').html(JSON.stringify(error));
}
});
});
controller:
public function add_deployment(){
$this->load->helper(array('form', 'url'));
$this->load->library('upload');
$config = array(
'upload_path' => site_url("attachments/project/999/metstations"),
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "16000000"
);
$this->load->library('upload', $config);
if($this->upload->do_upload('fldFileName'))
{
$data['image_metadata'] = array('image_metadata' => $this->upload->data());
}
else
{
$error = $this->upload->display_errors();
$data['errors']='<p class="error-message">'.$error.'</p>';
$data['status']='failure';
}
}
Try This.
To get all your form inputs, including the type="file" you need to use FormData object.
To append param just use append() method:
formData.append("param", "value");
And in the php-side I catch it:
echo $file_name = ($_FILES['file']['name']);
View Code:-
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" />
<button id="upload">Upload</button>
</body>
jQuery / Ajax Code:-
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'ControllerName/upload_file', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
Controller Code:-
class ControllerName extends CI_Controller {
function __construct() {
parent::__construct();
}
function upload_file() {
//upload file
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE; // remove it for actual file name.
$config['max_size'] = '1024'; //1 MB
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
echo 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/' . $_FILES['file']['name'])) {
echo 'File already exists : uploads/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
}
}
}
} else {
echo 'Please choose a file';
}
}
}
Note:- For more reference regarding this check this
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

Ajax does not return any result

My Ajax function does not return any result
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form >
</div>
</div>
$(document).ready(function(){
$("#ok").click(function() {
var login = $("#login").val();
var password = $("#password").val();
var dataString = 'login='+ login + '&password=' + password;
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userId= $row["id"];
$today=time();
$week=strftime('%W',$today) ;
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
}
The issue is because the button click is submitting the form in the standard manner, meaning your AJAX request is prevented from completing. It's better practice to hook to the submit event of the form.
Also note that your PHP code will never return 0, it would be better to have a error handler should the AJAX not complete as expected. Finally, your current code is wide open to attack; you should look in to using SSL and using prepared statements to avoid SQL injection.
That said, here's a fix for your AJAX issues:
<div id="container">
<div id="connexion">
<form id="myform" method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form>
</div>
</div>
$("#myform").submit(function(e) {
e.preventDefault(); // stop standard form submission
$.ajax({
type: "POST",
url: 'login.php',
data: {
login: $("#login").val(),
password: $("#password").val()
},
dataType: "json",
success: function(data) {
$('#errormess').html(data);
}
error: function() {
$('#errormess').html("problem");
}
});
});
I think you are giving the data parameter wrongly. It should be like
var dataString = {"login": login,
"password": password}
HTML
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password">
<br />
<input name="Submit" type="button" id="ok" value="OK" class="btn ">;
<br /> <br />
<span id="errormess"></span>
</form >
</div>
</div>
JS
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var login = $("#login").val();
var password = $("#password").val();
var dataString = {"login": login,
"password": password}
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
Also change the input type from submit to button and have and e.preventDefault() in your JS.
javascript code :
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var data = (this.form).serialize(); // added code
$.ajax({
url: 'login.php',
data: data,
dataType:'json',
type:'POST',
async:false,
success: function(data) {
if (data.success == 0) { // added code
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
},
error: function(data) { // if error occured
}
});
});//ok
});//document
php code :
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND
password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$userId = $row["id"];
$today = time();
$week = strftime('%W', $today);
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
} else { // added code
$arr = array("success" => '0');
echo json_encode($arr);
}
Please do check. I have modified the response from PHP as well as jquery code.

All files are not getting from file upload control using jquery

I am facing a problem during images upload.
I have an input type file control in my form and more input controls can be added using jquery. The problem is this: when I get all those control values, it only return the first value from file control.
How can I get all added files in all control? Here is my code:
Javascript
$(document).ready(function() {
$('#add_more').click(function() {
$(this).before($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append(
$("<input/>", {
name: 'file[]',
type: 'file',
id: 'file',
accept: '.jpg, .jpeg, .gif'
}),
$("<br/><br/>")
));
});
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name) {
alert("File Must Be Selected");
e.preventDefault();
} else {
//upload all images
var fileData = $('#file').prop("files")[0];
var form_data = new FormData();
form_data.append('file', fileData);
$.ajax({
url: "myurl.php",
dataType: 'text',
data: form_data,
cache: false,
contentType: false,
processData: false,
type: "post",
error: function() {
alert('error');
},
success: function(ret) {
alert('sucess');
}
});
}
}
});
HTML
<form enctype="multipart/form-data" action="" method="post">
<hr/>
<div id="filediv">
<input name="file[]" type="file" id="file" accept=".jpg, .gif, .jpeg" />
</div>
<br/>
<input type="hidden" value="" id="class" name="class">
<input type="button" id="add_more" class="upload" value="Add More Files" />
<input type="button" value="Upload File" name="submit" id="upload" class="upload" />
</form>
When I get the post from php using $_FILES['file']['name'] and counting it using
count($_FILES['file']['name']) it returns 1.
When I process further, only the first file is uploaded in the corresponding folder.
Something is probably wrong on line var fileData = $('#file').prop("files")[0];.
Your JS Code should be as below :
$(document).ready(function () {
$('#add_more').click(function () {
$(this).before($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append(
$("<input/>", {
name: 'file[]',
type: 'file',
// Id must be unique
// id: 'file',
class: "file_input",
accept: '.jpg, .jpeg, .gif'
}),
$("<br/><br/>")
));
});
$('#upload').click(function (e) {
var boolAreAllFilesSelected = true;
var objFormData = new FormData();
$.each($(":file"), function ( ) {
if (!$(this).val())
{
alert("File Must Be Selected");
$(this).focus();
return boolAreAllFilesSelected = false;
}
else
{
objFormData.append('file[]', $(this).prop("files")[0]);
}
});
if (boolAreAllFilesSelected)
{
$.ajax({
url: "myurl.php",
dataType: 'text',
data: objFormData,
cache: false,
contentType: false,
processData: false,
type: "post",
error: function () {
alert('error');
},
success: function (ret) {
alert('sucess');
}
});
}
});
});
Your PHP Code should be as below :
<?php
function uploadSingleImage($arrSingleFile = array())
{
if (!empty($arrSingleFile))
{
// Here your image uploading code
}
}
if (!empty($_FILES['file']))
{
$arrFile = $_FILES['file'];
foreach ($arrFile['name'] as $intIndex => $strName)
{
$arrSingleFile["name"] = $strName;
$arrSingleFile["type"] = $arrFile['type'][$intIndex];
$arrSingleFile["tmp_name"] = $arrFile['tmp_name'][$intIndex];
$arrSingleFile["error"] = $arrFile['error'][$intIndex];
$arrSingleFile["size"] = $arrFile['size'][$intIndex];
uploadSingleImage($arrSingleFile);
}
}
else
{
die("You have not uploaded any file.");
}

Categories

Resources