Please help me find the problem here. I am trying to upload a file via AJAX but For some reason which I am unaware of this code has refused to work i.e uploaded file is not copied to the location.
function save()
{
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append('files',files[i],files[i].name);
}
var datastring = $("#businessform").serializeArray();
$.each(datastring,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
type: "POST",
url: "../include/update_ajax.php",
contentType: false,
processData: false,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
//do something
},
error: function(){
alert('error handling here');
}
});
}
Here's the PHP
$success = 0;
$logo = "";
$logo_error = 0;
$sql = "update business set businessname=:bname, phone=:phone, email=:email where vendorid = :id";
$fields = array(
':bname'=>$_POST['businessname'],
':phone'=>$_POST['businessphone'],
':email'=>$_POST['businessemail'],
':id'=>$_POST['vendorid']
);
$q=$con->update_query($sql,$fields);
if($q)
{
//save logo
$businessid = $con->lastID;
if(!empty($_FILES['files']['tmp_name']))
{
$ext=pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
if(strcasecmp($ext, "jpeg") == 0 || strcasecmp($ext, "jpg") == 0 || strcasecmp($ext, "png") == 0)
{
$logo = "logo".$businessid;
move_uploaded_file($_FILES['files']['tmp_name'], UPLOADS_FOLDER.$logo);
}
else
{
$logo_error = 1;
}
}
$success = 1;
}
echo json_encode(array('success'=>$success, 'logo_error'=>$logo_error));
The serialized form appended is sent and inserted without issues but the uploaded file is not sent this way. Please what are my doing wrong and what's the better way.
Thank you so much.
You don't need to append files in FormData() just put Form tag selector in side FormData($("#businessform")[0]);
function save()
{
var datastring = FormData($("#businessform")[0]);
$.ajax({
type: "POST",
url: "../include/update_ajax.php",
contentType: false,
processData: false,
data: data,
dataType: 'json',
cache: false,
success: function(data) {
//do something
},
error: function(){
alert('error handling here');
}
});
}
Related
I need your help to upload an image on my server.
Indeed, with this code, I have an array(0) {} response while the values are well populated.
No image is uploaded... thank you for your help, here are my two files:
index.php
<input type="file" id="txt_image_user" name="txt_image_user" accept="image/*" required >
<script>
function upload_image() {
var handle = document.getElementById("txt_handle").value;
var reference = document.getElementById("txt_reference").value;
var fd = new FormData();
var files = $('#txt_image_user')[0].files[0];
fd.append('txt_image_user', files);
$.ajax({
type: 'POST',
url: '_upload-image.php',
cache: false,
data: {fd:fd, handle:handle, reference:reference},
contentType: false,
processData: false,
error: function (e) {console.log('Ajax Error', e);alert('Erreur Ajax');},
success: function(response){
console.log(response);
},
});
}
</script>
_upload-image.php
<?php require($_SERVER['DOCUMENT_ROOT']."/ew-includes/config.php");
var_dump($_POST);
$PathImage = $_SERVER['DOCUMENT_ROOT']."/ew-content/images/images-clients/";
if (!is_dir($PathImage)) {mkdir($PathImage);}
if(isset($_POST["handle"])) {
if(is_array($_POST["handle"])) {$handle = implode(", ", $_POST['handle']);} else {$handle = $_POST['handle'];}
if(is_array($_POST["reference"])) {$reference = implode(", ", $_POST['reference']);} else {$reference = $_POST['reference'];}
$img_name = $_FILES["txt_image_user"]["name"];
$img_tmp = $_FILES["txt_image_user"]["tmp_name"];
$filename = "ew".$reference."_".$handle."_".date("YmdHi");
$ext = pathinfo($img_name, PATHINFO_EXTENSION);
$photo = $filename.".".$ext;
$resultat = move_uploaded_file($img_tmp, $PathImage.$photo);
echo "img_name: ".$img_name."\n";
echo "img_tmp: ".$img_tmp."\n";
echo "ext: ".$ext."\n";
echo "photo: ".$photo."\n";
echo "resultat: ".$resultat."\n";
}
Thanks for your help.
I specify that I am new in Jquery
That's not the way to use FormData it should be the data. You can append other values to it.
function upload_image() {
var handle = document.getElementById("txt_handle").value;
var reference = document.getElementById("txt_reference").value;
var fd = new FormData();
var files = $('#txt_image_user')[0].files[0];
fd.append('txt_image_user', files);
fd.append('handle', handle);
fd.append('reference', reference);
$.ajax({
type: 'POST',
url: '_upload-image.php',
cache: false,
data: fd,
contentType: false,
processData: false,
error: function(e) {
console.log('Ajax Error', e);
alert('Erreur Ajax');
},
success: function(response) {
console.log(response);
},
});
}
I new to this site as well as to ajax, before posting here, although I searched for, nut not get proper answer to my question.
I have form through which I can upload and than save file, all this happening through ajax.
$('#'+loader).fadeIn('fast');
var input = document.getElementById(fileid);
file = input.files[0];
var filename= $('#'+fileid).val();
var exts = ["pdf", "doc", "docx", "PDF", "DOC", "DOCX"];
if(file != undefined){
formData= new FormData();
if ( filename )
{
// split file name at dot
var get_ext = filename.split('.');
// reverse name to check extension
get_ext = get_ext.reverse();
// check file type is valid as given in 'exts' array
if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){ var found = true; } else { var found = false; }
}
if(found) {
formData.append("image", file);
$.ajax({
url: uri,
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
if(data.length!=0)
{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+successid).fadeIn('fast');
$('#'+inputhidden).val(data);
$('#'+imgname).fadeIn('fast');
$('#'+filesavebtn).fadeIn('fast');
$('#'+imgname).html(data);
}else if(data.length==0)
{
$('#'+loader).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+errorid).fadeIn('fast');
}
}
});
}
else{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+exerror).fadeIn('fast');
}
}else{
}
and getting saved through
var fileval= $('#'+fileid).val();
var fileuniqval= $('#'+fileuniqid).val();
$.ajax({
url: pageurl,
type: 'POST',
data: 'fileupload='+fileval+'&identi='+fileuniqval+'&uniqids=fileuploading',
success: function(data)
{
if(data=='FALSE'){
alert("Server Error, please try again.");
}if(data=='TRUE'){
$('#'+hide1).fadeOut('fast');$('#'+hide2).fadeOut('fast');$('#'+hide3).fadeOut('fast');
$('#'+inputid).val('');
$('#'+successmsg).fadeIn('fast');
$('#'+filearea).css({ 'border-color': '#008000', 'border-width':'2px', 'border-style':'solid' });
$('#'+filearea).animate({ 'backgroundColor': '#008000', 'color': '#fff'}, 1000);
$('#'+filearea).animate({ 'backgroundColor': '#fff', 'color': '#000'}, 3000);
}
}
});
Now my question is that I want to get this upload and save procedure in one go! Although I tried my to merge both function by nesting one in other but not working as per expectations.
$('#'+loader).fadeIn('fast');
var input = document.getElementById(fileid);
file = input.files[0];
var filename= $('#'+fileid).val();
var exts = ["pdf", "doc", "docx", "PDF", "DOC", "DOCX"];
var fileval= $('#'+inputhidden).val();
var fileuniqval= $('#'+fileuniqid).val();
if(file != undefined){
formData= new FormData();
if ( filename )
{
// split file name at dot
var get_ext = filename.split('.');
// reverse name to check extension
get_ext = get_ext.reverse();
// check file type is valid as given in 'exts' array
if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){ var found = true; } else { var found = false; }
}
if(found) {
formData.append("image", file);
$.ajax({
url: uri,
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
if(data.length!=0)
{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+successid).fadeIn('fast');
$('#'+inputhidden).val(data);
$('#'+imgname).fadeIn('fast');
//$('#'+filesavebtn).fadeIn('fast');
$('#'+imgname).html(data);
$.ajax({
url: pageurl,
type: 'POST',
data: 'fileupload='+fileval+'&identi='+fileuniqval+'&uniqids=fileuploading',
success: function(data)
{
if(data=='FALSE'){
alert("Server Error, please try again.");
}if(data=='TRUE'){
$('#'+successid).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+errorid).fadeOut('fast');
$('#'+fileid).val('');
$('#'+hide1).fadeIn('fast');
$('#'+filearea).css({ 'border-color': '#008000', 'border-width':'2px', 'border-style':'solid' });
$('#'+filearea).animate({ 'backgroundColor': '#008000', 'color': '#fff'}, 1000);
$('#'+filearea).animate({ 'backgroundColor': '#fff', 'color': '#000'}, 3000);
}
}
});
}else if(data.length==0)
{
$('#'+loader).fadeOut('fast');$('#'+exerror).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+errorid).fadeIn('fast');
}
}
});
}
else{
$('#'+loader).fadeOut('fast');$('#'+errorid).fadeOut('fast');$('#'+successid).fadeOut('fast');$('#'+hide1).fadeOut('fast');
$('#'+exerror).fadeIn('fast');
}
}else{
}
I am upload a file in php codeigniter project using a ajax. The file is uploading succesfully. But I also want to post some extra values to database with this. I am not sure how to do it. Can anybody please tell me how to pass another data fields while saving a file in php
Here is my js code
$("#btnupdatecover").click(function(event){
alert(coverPostion);
if($("#fileuploadcover").val() != ''){
if (typeof FormData !== 'undefined') {
var form = $('#formname').get(0);
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "Userpage/updatedp",
data: formData,
mimeType:"multipart/form-data",
dataType: 'json',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
cache:false,
contentType: false,
processData: false,
success: function(result){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
// imgURI: ["https://unsplash.it/120/120?image=20"]
});
clearAll();
}
});
//
event.preventDefault();
}
}
else
{
toastr8.info({
message:'Error Occured',
title:"Please try again",
iconClass: "fa fa-info",
// imgURI: ["https://unsplash.it/120/120?image=20"]
});
}
});
My PHP Code
public function updatedp()
{
$var = $_FILES ['fileUp'];
$img=$_FILES ['fileUp'];
$config['upload_path'] = 'webim/dp_images';
$config['overwrite'] = 'TRUE';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config["max_size"] = '1400';
$config["max_width"] = '1400';
$config["max_height"] = '1400';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('fileUp'))
{
$this->data['error'] = $this->upload->display_errors();
echo json_encode(array("result"=>$this->data['error']));
exit;
}
else
{
$data=array('active'=>0);
$this->db->where('userid','1');
$this->db->update('music_user_dp',$data);
$uname['uname'] =$this->session->all_userdata('uname');
$uname['id'] =$this->session->all_userdata('id');
$post_data = array(
'id' => '',
'userid' => $uname['id']['id'],
'profilepic'=>$var['name'],
'updatedate' => date("Y-m-d H:i:s"),
'active' => '1'
);
$this->Userpage_model->insert_dp_to_db($post_data);
echo json_encode(array("result"=>"Success"));
exit;
}
}
I just pass extra fields with this to post in database.
Thanks
You can achieve this:
Approach 1
Use hidden fields into the form.
Approach 2
$.ajax({
type: "POST",
url: "Userpage/updatedp",
data: {formData: formData, var1: 'value', var2: 'value'},
dataType: 'json',
success: function(result){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
// imgURI: ["https://unsplash.it/120/120?image=20"]
});
clearAll();
}
});
Now these value you will get your controller.
I want to send/get a variable to/from controller action. My codes:
view file
....
<button id="radiyo">radio</button>
<script>
$("#radiyo").on("click", function(){
var $radio = $('input[type=radio][name=siniflerin-siyahisi]:checked').attr('id');
$.ajax({
type: 'POST',
url: '<?=Yii::app()->baseUrl;?>/ideyalar/sech/radio',
async: false,
cache: false,
data: {radio: $radio},
// datatype: "html",
success:function(){
alert($radio);
}
});
$.ajax({
type: 'GET',
url: '<?=Yii::app()->baseUrl;?>/ideyalar/sech/radio',
async: false,
cache: false,
datatype: "json",
data: {change: $sql},
success: function(data) {
alert(data.change);
}
});
});
</script>
....
controller action
public function actionSech ($radio)
{
$sql = Yii::app()->db->createCommand()
->select ('m.maraq')
->from ('maraq m')
->where ('m.idsinif=:ids', [':ids'=>$radio])
->queryAll();
$gonderilen = CJSON::encode(['change'=>$sql]);
}
I read articles from Yii offical site and other forums. But I couldn't understand how can I do it.
Please tell me, how can I send $sql variable to my view file?
Thanks.
I'm not pretty sure what you want. But, I want to pointing out some snippet.
In view file
<?php
Yii::app()->clientScript->registerScript("header-info","
var baseUrl = '".Yii::app()->baseUrl;."';
",CClientScript::POS_HEAD);
?>
<button id="radiyo">radio</button>
<script>
$("#radiyo").on("click", function(){
var radioValue = $('input[type=radio][name=siniflerin-siyahisi]:checked').attr('id');
$.ajax({
url: baseUrl +'/ideyalar/sech',
dataType:'json',
type:'POST',
data:{radioValue:radioValue},
async:false
}).done(function(data){
if(data['status'] == 'OK'){
alert(data['returnValue']);
}else if(data['status'] == 'ERROR'){
alert("HERE WE GO ERROR");
}
});
});
</script>
Your controller action;
public function actionSech()
{
//In my point, I never call db layer in controller. Controller should be routing purpose
If(Yii::app()->request->isAjaxRequest){
$radioValue = isset($_REQUEST['radioValue']) ? $_REQUEST['radioValue'] : "";
$returnObj = array();
if($radioValue !=""){
$query = "SELECT `maraq` FROM maraq WHERE idsinif='$radionValue'";
$result = Yii::app()->db->createCommand($query)->queryScalar();
if($result != "" || $result != null){ //ensure result is correct or not
$returnObj['returnValue'] = $result;
$returnObj['status'] = 'OK';
}else{
$returnObj['status'] = 'ERROR';
}
}else{ //if radiovalue is blank string
$returnObj['status'] = 'ERROR';
}
echo json_encode($returnObj);
}
}
Hope this help! Btw, JavaScript variable can't not initialize with $. Just only var yourVar="";
I have a big issue with $.ajax. I try to send a file name to the PHP part (in the same file), to help me stocking that name in a $_SESSION.
It worked perfectly yesterday, but not anymore. Is there a browser issue instead of code issue ?
Here is my code :
JS function
<script type="text/javascript" charset="utf-8">
function no_select(){
var images = $("#selected_images").text();
if(images != ''){
var tmpFile = $("#selected_images").text();
var arrayFile = tmpFile.split(",");
if (arrayFile.length > 2){
alert("Il ne faut selectionner qu'un seul badge !");
return false;
}
var value = $.ajax({
type: "GET",
dataType: "json",
url: "overview_list.php",
data: "selectedImage="+arrayFile[0],
async: false,
success: function()
{
return true;
}
});
return true;
} else if(images == ''){
alert("Il faut selectionner un badge");
return false;
}
}
</script>
PHP
<?php
if(!empty($_GET['selectedImage'])){
$let = $_GET['selectedImage'];
} else {
$let = "";
}
$_SESSION['selectedImage'] = $let;
?>
I have already check a lot of solutions around the web, but there was no solution for me.
It should be like
$.ajax({
type: "GET",
dataType: "json",
url: "overview_list.php",
data: {selectedImage:arrayFile[0]},
async: false,
success: function()
{
return true;
}
and makesure arrayFile[0] is getting value