jQuery Ajax Upload File php receives array even with out content - javascript

It's working but on every submit I receive an array even tho a file is not even added to the file input (multifile input)
postData = new FormData(this);
$.ajax({
url: "/url",
type: "POST",
data: postData,
cache: false,
contentType: false,
processData: false,
success: function (data, textStatus, jqXHR) {
if (data === "true") {
window.location.replace("/url");
} else {
$(".errors").html(data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
swal("Der opstod en fejl");
}
});
What i get from $_FILES is the following
Array
(
[files] => Array
(
[name] => Array
(
[0] =>
)
[type] => Array
(
[0] =>
)
[tmp_name] => Array
(
[0] =>
)
[error] => Array
(
[0] => 4
)
[size] => Array
(
[0] => 0
)
)
)
Is there a way where I can avoid this from happening?

Try adding required attribute to input type="file" element to prevent submission of form if no files selected by user
$("form").on("submit", function(e) {
e.preventDefault();
// do `$.ajax()` stuff
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form>
<input type="file" name="files[]" multiple required />
<input type="submit" />
</form>

Related

send uploaded file via phpmailer

I have a form, with a input files element.
I would like to select a file with this element and send it via ajax to antother php file:
** HTML **
<form enctype="multipart/form-data">
<input type="file" id="angebote" name="angebote[]" accept=".pdf" multiple />
</form>
** Script **
var form_data = new FormData();
for (var index = 0; index < $('#angebote').prop('files').length; index++) {
form_data.append("angebote[]", $('#angebote').prop('files')[index]);
}
$.ajax({
url: 'ajax/sendAnforderung.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
//...
}
});
** PHP **
print_r($_FILES);
** Result **
Array
(
[angebote] => Array
(
[name] => Array
(
[0] => scan.pdf
)
[type] => Array
(
[0] => application/pdf
)
[tmp_name] => Array
(
[0] => /volume1/#tmp/phpiZrjNh
)
[error] => Array
(
[0] => 0
)
[size] => Array
(
[0] => 509145
)
)
)
Now I would like to send this file as an attachment via php mailer.
for this I nee the path of the file.
I tried this:
echo $_FILES['angebote']['tmp_name'][0].'/'.$_FILES['angebote']['name'][0];
Result:
/volume1/#tmp/phpiZrjNh/scan.pdf
But the file is not be accessable.
Where is my mistake?

How to get value from response Array to Ajax

How to get value from response array to ajax?
let's se my response array
Array ( [files] => Array ( [0] => files/media_post/Hydrangeas.jpg ) [metas] => Array ( [0] => Array ( [date] => Mon, 31 Oct 2016 06:16:13 +0100 [extension] => jpg [file] => files/media_post/Hydrangeas.jpg [name] => Hydrangeas.jpg [old_name] => Hydrangeas [replaced] => [size] => 595284 [size2] => 581.33 KB [type] => Array ( [0] => image [1] => jpeg ) ) ) )
and my javascript
data: null,
type: 'POST',
enctype: 'multipart/form-data',
nama : $("#filer_input2").val(),
url: "<?php echo base_url(); ?>blog-media/ajax_add",
beforeSend: function(){},
success: function(data, el){
alert(data.metas);
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
$("<div class=\"jFiler-item-others text-success\"><i class=\"icon-jfi-check-circle\"></i> Success</div>").hide().appendTo(parent).fadeIn("slow");
});
},
error: function(el){
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
$("<div class=\"jFiler-item-others text-error\"><i class=\"icon-jfi-minus-circle\"></i> Error</div>").hide().appendTo(parent).fadeIn("slow");
});
}
so i hope i can get value from array because i neet that values for save to database.

Getting error while using each loop under ajax

When i am trying each loop under Ajax call, i am getting error as:
TypeError: invalid 'in' operand e
Below is my Ajax call code
$.ajax({
type: "POST",
url: "/admin/counselormanagement/centername",
data: 'groupId='+valueSelected,
async: true,
success: function(arrCenter) {
$.each(arrCenter, function( intValue, arrValue ) {
console.log('<option value="' + arrValue['ID'] + '">'+ arrValue['CenterName'] +'</option>');
});
}
});
Response which i am getting back from server is :
Array (
[0] => Array
(
[ID] => 4
[CenterName] => test2
[ParentName] => 2
[Parent] => 3
[GroupName] => test
[Type] => 1
)
[1] => Array
(
[ID] => 8
[CenterName] => test21
[ParentName] => 2
[Parent] => 3
[GroupName] => test
[Type] => 1
)
)
I am using PHP as backend, whose code is :
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
print_r($arrCenter[0]);
die();
Use json_encode() in PHP to return response. And your JS code should be like:
PHP:
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();
JQuery:
$.ajax({
type: "POST",
url: "/admin/counselormanagement/centername",
data: 'groupId='+valueSelected,
dataType: 'json',
async: true,
success: function(arrCenter) {
$.each(arrCenter, function( intValue, arrValue ) {
console.log('<option value="' + arrValue.ID + '">'+ arrValue.CenterName +'</option>');
});
}
});
Try to echo out your object using json_encode instead:
<?php
$arrCenterName = array();
$objCenterMapper = new Application_Model_CentersMapper();
$arrCenter = $objCenterMapper->seekCenters($_POST['groupId']);
echo json_encode($arrCenter[0]);
die();

How to use autocomplete inside a dialog box using jQuery?

I have a form inside of a dialog box that is displayed when a user click on a button. When a user starts tying inside a field I want to display available options found inside a database.
The available options will need to be read using an AJAX request.
Here is my jQuery code where I try to initialize the autocomplete()
$("#icwsTransferTo")
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
}).autocomplete({
source: function(request, response) {
$.ajax({
type: 'GET',
url: 'index.php',
data: {method: 'userSearch', term: request.term},
dataType: 'json',
cache: false,
timeout: 30000,
success: function(data) {
console.log(data);
if(!data){
return;
}
var array = $.map(data, function(m) {
return {
label: '<div syle="display: block;"><span>' + m.configurationId.displayName + '</span><span style="float: right"> (' + m.extension + ')</span></div>'
};
});
response(array);
}
});
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
alert('Worked!');
}
});
The field icwsTransferTo is located inside of a form which is displayed in the dialog box.
The problem is that when typing 2+ characters, I see the spinning icon in the field but no results is ever presented.
When I do a manual call to the index.php?method=userSearch&term=mike I get results like this
stdClass Object
(
[items] => Array
(
[0] => stdClass Object
(
[configurationId] => stdClass Object
(
[id] => msmith
[displayName] => Mike Smith
[uri] => /configuration/users/msmith
)
[extension] => 2062
)
[1] => stdClass Object
(
[configurationId] => stdClass Object
(
[id] => mjohns
[displayName] => Mike Jones
[uri] => /configuration/users/mjohns
)
[extension] => 2083
)
)
)
what am I doing wrong here? Why the results are not showing?
I am assuming you are using the Jquery UI autocomplete? According to their documentation here: Documentation you should pass it a JSON array not html.

Ajax response array

I want to insert ajax response array into form select input. for the purpose i want to look into array. here is my function;
function _get_student_failed_classes()
{
$failed_classes=$this->db->select('class_student.class_id,course.course_code,course.course_name,course.course_credit')
->join('class','class.class_id=class_student.class_id','LEFT')
->join('course','course.course_id=class.class_course','LEFT')
->where('class.class_status',$active)
->where('class_student.class_marks <=',50)
->where('class_student.student_id',$std_code)
->order_by('class.class_id')
->get('class_student')->result();
echo $failed_classes;
}
and here is my ajax call in form
$.ajax({
url: '<?php echo base_url()."index.php/student/get_student_failed_classes/s-14-1"; ?>',
type: 'POST', data: std_code,
success: function(response)
{
alert(response);
},
error: function()
{
alert(error);
}
I get the response is []
the actual array looks like this
Array
(
[0] => stdClass Object
(
[class_id] => 3
[course_code] => cs3
[course_name] => cs3
[course_credit] => 3
)
[1] => stdClass Object
(
[class_id] => 4
[course_code] => cs4
[course_name] => cs4
[course_credit] => 4
)
[2] => stdClass Object
(
[class_id] => 5
[course_code] => cs5
[course_name] => cs5
[course_credit] => 3
)
)
can some one help me out on this
var objectRet= jQuery.parseJSON(response);
for(var i=0;i<objectRet.length;++i) {
alert(objectRet[i].class_id)
}
success: function(response) {
var $select = $('<select id="mySelect"/>');
var $options = response.map(function(a, i) {
return $('<option />', {
value: a.class_id,
text: a.course_code + ' - ' +
a.course_name + ' (' + a.course_credit +')'
});
});
$options.appendTo($select.appendTo($('#someForm')));
}

Categories

Resources