AJAX file upload to put data into data - php

I have this script that will upload multiple files and it will be retrieve by the controller.
Question
How can I put another data in the data: section in the AJAX request for example like this:
data: data + '&reference='+$('#ref').val(),
controller
function insertAttachment() {
$i = 0;
$referenceNo = $this->input->post('reference');
if(!isset($_FILES[$i]) ) {
}
else {
$x = $_FILES[$i]['name'];
$xx = explode('.', $x);
$config['upload_path'] = 'MRS-files\Upload_files';
$config['allowed_types'] = 'xls|doc|jpg|png|gif|pdf';
$this->load->library('upload',$config);
for($i; $i <= 4; $i++) {
$counter = $_FILES;
while ( $i <= count($counter) ) {
$x = $_FILES[$i]['name'];
$xx=explode(".", $x);
$config['file_name']= 'IT2015' .'('. ($i+1) .').'. $xx[1];
$this->upload->initialize($config);
$_FILES['up']['name'] = $_FILES[$i]['name'];
$_FILES['up']['tmp_name'] = $_FILES[$i]['tmp_name'];
$_FILES['up']['type'] = $_FILES[$i]['type'];
$_FILES['up']['size'] = $_FILES[$i]['size'];
if ( ! $this->upload->do_upload('up')) {
//error on uploading
echo str_replace('','',$this->upload->display_errors()); //temporary commented no use cause of redirect to homepage
//$this->cancelREC();
exit();
}
else {
$data = array('upload_data' => $this->upload->data());
$this->edit_development_model->insertonAttachments($data['upload_data'] , $referenceNo);
$i++;
}
}
}
}
}
Here is the script:
function EditUploadImage() {
var data = new FormData($('input[name^="edit_files"]'));
jQuery.each($('input[name^="edit_files"]')[0].files, function(i, file) {
data.append(i, file);
});
$.ajax ({
type: 'POST',
data: data,
url: 'mis.php/edit_development_detailsControl/updateRequest',
cache: false,
contentType: false,
processData: false,
success: function(data) {
alert(data);
//messagealert("Success","You're Request have been save successfully");
}
});
}

Hope this one help you.
var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});

Related

Laravel session::has('key') doesn't exist after new request

First time working with Laravel and a bit confused.
Performing ajax request into controller action and after next request session key I've stored before doesn't exist.
The purpose of this code is to save some set of images and store their names to session for further work..
Session ID's equal in my parent page and ajax request. Application has no user authenticaton yet.
(Upd) Session driver is 'file' by default.
Why session key doesn't save normally?
public function upload(Request $request)
{
$rules = ['photo.*' => 'image|mimes:jpeg,png,jpg|max:2048'];
$validator = Validator::make($request->all(), $rules);
$files = [];
$fileNames = [];
$errors = [];
if ($validator->fails()) {
$errors = ArrayHelper::getFinalValuesRecursive($validator->errors()->messages());
} else {
foreach ($request->file('photo') as $key => $value) {
$imageName = $key . md5(time() . $key) . '.' . $value->getClientOriginalExtension();
$value->move(public_path('uploads'), $imageName);
$fileNames[] = $imageName;
$files[] = '/uploads/' . $imageName;
}
$sessionFiles = [];
if (Session::has('photo')) {
$sessionPhoto = Session::get('photo');
foreach ($sessionPhoto as $value) {
$sessionFiles[] = $value;
}
}
Session::put('photo', array_merge($sessionFiles, $fileNames));
}
Javascript
$(document).ready(function () {
$('#photo').on('change', function () {
var fileData = $('#photo').prop('files');
var formData = new FormData();
for (var i = 0; i < fileData.length; i++) {
formData.append('photo[]', fileData[i]);
}
formData.append("_token", $('input[name="_token"]').attr('value')); //csrf
$.ajax({
url: '{{route('adverts.upload')}}',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (response) {
response = $.parseJSON(response);
if (response.errors.length) {
for (var i = 0; i < response.errors.length; i++) {
$('#image_errors')
.append('<div class="invalid-feedback" style="display: block;">' + response.errors[i] + '</div>');
}
} else {
$('#image_errors').html('');
var totalFile = response.files.length;
for (var i = 0; i < totalFile; i++) {
$('#image_preview').append("<img src='" + response.files[i] + "'>");
}
}
}
});
});
});

My indices are defined but I still get the unidentified error

So I have this strip of code working for one page and not working for another page... Same code, same form name attributes, same php functionality on the server side. I'm calling with jquery ajax.. Calling from one page, it works completely fine... When I call from another page, it gives me "Unidentified index"
I've tried changing the names around (to remove duplicates and all)..
I seem to be sure that the names are correct though.
<script type="text/javascript">
$('#uploadcsv').submit(function(e){
e.preventDefault();
$.ajax({
url: "functions/grocerystore.php?item=fetchcontacts",
method: "post",
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
var accumulator = "";
var filetype = $('#uptype').val();
if(filetype == "csv"){
for(trav=0; trav<data.length; trav++){
accumulator += data[trav];
if(trav < data.length-1)
accumulator += "\r\n";
}
}else{
for(trav=0; trav<data.length; trav++){
accumulator += data[trav];
}
}
var mobilenumbers = $('#mobilenumbers');
mobilenumbers.html(accumulator);
},
error: function(data){
console.log(data);
}
});
});
</script>
php
case 'fetchcontacts':
if(!empty($_FILES['customFilex']['name'])){
$name = explode('.',$_FILES['customFilex']['name']);
$extension = end($name);
$file_data = fopen($_FILES['customFilex']['tmp_name'],"r");
if($extension == 'csv'){
fgetcsv($file_data);
$mobile = array();
$init = 0;
while($row = fgetcsv($file_data)){
$mobile[$init] = $row[0];
$init++;
}
fclose($file_data);
}else{
if ($file_data = fopen($_FILES['customFilex']['tmp_name'], 'r')) {
$mobile = array();
$init = 0;
while (!feof($file_data)) {
$row = fgets($file_data);
$mobile[$init] = $row;
$init++;
}
fclose($file_data);
}
}
echo json_encode($mobile);
}else{
$report["status"] = "failed";
echo json_encode($report);
}
break;
I just need it to accept my file...
You are using $_FILES['customFilex']['tmp_name']without checking if the keys exists in the $_FILES array.

Ajax post not passing data to php?

So I'm having trouble with passing data using ajax post to php
Here is my jquery :
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat = ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
and here is the php file:
$kodeobat = $_POST['kodeobat'];
$stmt = $db_con->prepare("SELECT kodeobat, hargaobat FROM Obat WHERE kodeobat='".$kodeobat."'");
$stmt->execute();
while($row=$stmt->fetchAll(PDO::FETCH_ASSOC))
{
if($kodeobat == $row['kodeobat']){
echo json_encode($row);
}
}
and it results : Notice: Undefined index: kodeobat in .../getdata.php on line 4 which is this line $kodeobat = $_POST['kodeobat'];
Is there something wrong with the code? Thank youuu :)
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat == ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
Notice if (kodeobat == "")
Try sending your JSON as JSON by using PHP's header() function:
header("Content-Type: application/json", true);
look at this
If you are unaware of what type of value you would get in response here is a try..
$kodeobat = $_POST['kodeobat'];
if(empty($kodeobat)) {
echo("Value is empty");
} else if(is_array($kodeobat)) {
$i = count($kodeobat); //If the value is array iterate it
for($j = 0; $j < $i; $j++) {
echo($kodeobat[$i] . " ");
}
} else if(is_object($kodeobat)){
$json = json_decode($_POST,true); //if it is a json value decode it
$kodeobat_new = $json['kodeobat'];
}

getting error while uploading image via Ajax

im having trouble in uploading a multiple file by ajax . here is my code.
HTML code:-
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="button" id="uploadBusinessImg" value="Upload" >
Ajax Code:-
$("#uploadBusinessImg").on("click",function(e)
{
var fd = new FormData();
var file_data = $("#txtBusinessImage")[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file"+[i], file_data[i]);
}
var other_data = $("#selectBusinessHiddenID").serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
data: fd,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
When im calling upload_business_photo_do() function via Ajax then it does't able to recive the name of image $_FILES['file']['name']
upload_business_photo_do()
{
$business_hidden_id=$this->input->post('selectBusinessHiddenID');
/*code for image*/
$config['upload_path']='./upload_101/';
$config['allowed_types']= 'jpg|png|jpeg';
$config['max_width'] = '6000';
$config['max_height'] = '4500';
$this->load->library('upload',$config);
for($i=0; $i<count($_FILES['file']['name']); $i++)
{
$_FILES['userfile']['name']= $_FILES['file']['name'][$i];
$_FILES['userfile']['type']= $_FILES['file']['type'][$i];
$_FILES['userfile']['tmp_name']= $_FILES['file']['tmp_name'][$i];
$_FILES['userfile']['error']= $_FILES['file']['error'][$i];
$_FILES['userfile']['size']= $_FILES['file']['size'][$i];
if(! $this->upload->do_upload())
{
/*----set flash message*/
echo "error";
}
else
{
echo "done";
}
}
}
try to use like this , its simple and easy
$("#uploadBusinessImg").on("click",function(e)
{
var formData = new FormData($("#form_name")[0]);
$.ajax({
url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>',
processData: false,
contentType: false,
data: formData,
type: 'POST', async : true,
success: function(data){
alert(data);
}
});
});
and in controller use like this
if($_FILES['txtBusinessImageName'])
{
$file_ary = $this->reArrayFiles($_FILES['txtBusinessImageName']);
foreach ($file_ary as $file)
{
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
and also use this function for convert files data into array for multiple images data
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
its working perfect , just try to use it . you don't need to add a extra codes of files with ajax.
use form tag and submit button for file upload.
<form method="post" enctype="multipart/form-data">
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple >
<input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>">
<input type="submit" id="uploadBusinessImg" value="Upload">
</form>
and remove enctype: 'multipart/form-data', from ajax call and try.
Change following for fetching files:
var file_data = $('#txtBusinessImage').prop('files')[0];
var fd = new FormData();
fd.append('file', file_data);

echo query on ajax response

I'm trying to send a php form data via AJAX (without the refresh) and display data in new form. I echo query but it didnt work. On AJAX response it shows me getReportAj form on call.The code goes like this:
Javascript
function getReport()
{
var dataString = "grNo=" +$(".grNo").val();
$.ajax({
type: "GET",
url: "getReportAj.php",
data: dataString,
success:function(data)
{
$('#result').html(data);
}
});
}
getReportAj.php
<?php
include "include/config.inc.php";
if(!isset($_SESSION['s_activName']) && !isset($_SESSION['s_userType']) || isset($_SESSION['s_userType']) && $_SESSION['s_userType'] == 'Student') {
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:checkLogin.php");
}
else {
if(isset($_REQUEST['submit'])) {
$selectReport = "SELECT * from gradeterm1
WHERE studentId = ".$_POST['studentId']."
AND termValue = 1
LEFT JOIN studentmaster ON studentmaster.studentId = gradeterm1.studentId";
$selectReportRes = mysql_query($selectReport);
if($reportRow = mysql_fetch_array($selectReportRes)); {
$eReadingPro = $reportRow['eReadingPro'];
$eReadingFlu = $reportRow['eReadingFlu'];
$eReadingCom = $reportRow['eReadingCom'];
$eWritingCre = $reportRow['eWritingCre'];
$eWritingHan = $reportRow['eWritingHan'];
$eWritingGra = $reportRow['eWritingGra'];
$eWritingSpe = $reportRow['eWritingSpe'];
$eWritingVoc = $reportRow['eWritingVoc'];
$ewSpeakinCon = $reportRow['ewSpeakinCon'];
$ewSpeakinRec = $reportRow['ewSpeakinRec'];
$ewSpeakinCla = $reportRow['ewSpeakinCla'];
$eListingComp = $reportRow['eListingComp'];
$eListingCon = $reportRow['eListingCon'];
$extraReading = $reportRow['extraReading'];
$activityPro = $reportRow['activityPro'];
$hiReadingPro = $reportRow['hiReadingPro'];
$hiReadingFlu = $reportRow['hiReadingFlu'];
$hiReadingCom = $reportRow['hiReadingCom'];
$hiWritingCre = $reportRow['hiWritingCre'];
$hiWritingHan = $reportRow['hiWritingHan'];
$hiWritingGra = $reportRow['hiWritingGra'];
$hiWritingSpe = $reportRow['hiWritingSpe'];
$hiWritingVoc = $reportRow['hiWritingVoc'];
$hiwSpeakinCon = $reportRow['hiwSpeakinCon'];
}
}
}
include("./bottom.php");
$smarty->display('getReportAj.tpl');
?>
<script>
function getReport()
{
var dataString = "grNo=" +$(".grNo").val();
$.ajax({
type: "GET",
url: "getReportAj.php",
data: dataString,
success:function(data)
{
$('#result').html(data);
console.log(data);
}
});
}
</script>
in success event.. put the console.log(data) then run the script and check in console.

Categories