In my PHP app I have some content generated by AJAX with form having file input.
This form is located in Bootstrap Modal. I write some data into inputs and upload file using jQuery File Upload Plugin 5.26 and it works fine.
I close modal and load the same content asynchronously by clicking on another list element.
I do the same as before and I have error: 4;
No file was uploaded.
I used the same action, the same modal and form, only difference is that I render it twice using AJAX. Could anyone explain me how to fix this error and how to upload second file?
I would like to add that data from text inputs has changed, but $_FILES is empty array.
Another info is that when I render view first I can upload file, close modal and upload second file.
Problem is when I render this view second time and try to upload file.
AJAX sending POST and getting view:
$.ajax({
type: "POST",
url: "/ksiazka/pobierz-partial",
dataType : 'json',
data: {
id: idObiektu,
template: template,
typ: typObiektu,
fmodel: fmodel
},
success: function(data)
{
$('#ksiazka-tresc').html(data.html);
}
});
Rendering view:
public function pobierzPartialAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
$id = $request->getPost('id');
$templatka = $request->getPost('template');
$typ = $request->getPost('typ');
$fmodel = $request->getPost('fmodel');
/* #var $wartosciDoTemplatki \Obiekty\Model\Ommost */
$wartosciDoTemplatki = $this->pobierzWartosciDoTemplatki($templatka, $id, $typ, $fmodel);
$htmlViewPart = new ViewModel();
$htmlViewPart->setTerminal(true)
->setTemplate('template/' . $templatka)
->setVariables(array(
'wartosci' => $wartosciDoTemplatki
));
$htmlOutput = $this->getServiceLocator()
->get('viewrenderer')
->render($htmlViewPart);
$jsonObject = \Zend\Json\Json::encode(array(
'html' => $htmlOutput
), true);
echo $jsonObject;
return $this->response;
}
}
View:
<div class="row" style="padding-bottom: 5px">
<div class="col-sm-6" id="ksiazka-save-table-alert">
<div class="alert alert-success text-center" role="alert" style="padding: 4px; margin-bottom: 0; display: none">Pomyślnie zapisano</div>
</div>
<div class="col-sm-6 text-right">
<img src="/img/30-load.gif" alt="spinner" class="ksiazka-table-spinner" style="display: none">
<div class="btn-group btn-group-sm" role="group">
<a class="btn btn-primary ksiazka-add-photo" data-toggle="tooltip" data-placement="top" title="Dodaj rekord"><i class="fa fa-plus"></i></a>
<a class="btn btn-danger karta-delete-row" data-toggle="tooltip" data-placement="top" title="Usuń rekord"><i class="fa fa-minus"></i></a>
<a class="btn btn-success karta-save-row" data-toggle="tooltip" data-placement="top" title="Zapisz zmiany"><i class="fa fa-check"></i></a>
</div>
</div>
Modal:
<div class="modal fade bs-example-modal-lg" tabindex="-1" aria-hidden="true" id="ksiazkaFileUpload"><div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Dodawanie zdjęcia</h4>
</div>
<div class="modal-body" style="min-height: 450px" id="hide-spinner">
<div class="row">
<div class="col-sm-12">
<form id="upload" method="post" action="/ksiazka/upload-file" enctype="multipart/form-data">
<input type="hidden" name="model" value="<?php echo $wartosci['model-pliki'] ?>" />
<input type="hidden" name="tabela" value="<?php echo $wartosci['tabela-pliki'] ?>" />
<input type="hidden" name="MASTER_ID" />
<?php if(isset($wartosci['OM_ID'])): ?>
<input type="hidden" name="OM_ID" value="<?php echo $wartosci['OM_ID'] ?>" />
<?php endif ?>
<label for="NR">NR</label>
<input type="text" class="form-control" name="NR" />
<label for="OPIS">Opis</label>
<input type="text" class="form-control" name="OPIS" />
<div id="drop" style="margin-top: 10px">
<input type="file" name="upl" />
<i class="fa fa-plus"></i> Dodaj
</div>
<ul style="margin-top: 20px">
The file uploads will be shown here
</ul>
</form>
</div>
</div>
</div>
</div>
Upload file action:
public function uploadFileAction()
{
$allowed = array('png', 'jpg', 'gif','zip', 'txt', 'rtf');
var_dump($_FILES, $_POST);
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0)
{
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
$file = file_get_contents($_FILES['upl']['tmp_name']);
$idTypu = 2;
$values = $_POST;
$model = $values['model'];
$tabela = $values['tabela'];
$values['ID_TYPU_PLIKU'] = $idTypu;
$values['PLIK'] = 'empty_blob()';
$values['OPIS'] = "'". $values['OPIS'] . "'";
$values['NR'] = "'". $values['NR'] . "'";
$values['NAZWA_PLIKU'] = "'". $_FILES['upl']['name'] . "'";
unset( $values['model']);
unset( $values['tabela']);
$session = new \Zend\Session\Container('namespace');
$zasobId = $session->item;
$zasob = $this->getZasobyTable()->zwrocSchematPoId($zasobId);
$fun = 'get' . $model . 'Table';
$this->$fun()->saveUploadedFile($file, $values, $tabela, $zasob);
echo 'ok';
exit;
}
echo '{"status":"error"}';
exit;
}
JS script:
var ul = $('#upload ul');
$('.file').click(function(e){
e.preventDefault();
// Simulate a click on the file input button
// to show the file browser dialog
$(this).parent().find('input').click();
});
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
// This element will accept file drag/drop uploading
dropZone: $('#drop'),
pasteZone: $(document),
// This function is called when a file is added to the queue;
// either via the browse button, or via drag/drop:
add: function (e, data) {
var tpl = $('<li class="working"><input type="text" value="0" data-width="20" data-height="20"'+
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');
// Append the file name and file size
tpl.find('p').text(data.files[0].name)
.append('<b>' + formatFileSize(data.files[0].size) + '</b>');
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function(){
if(tpl.hasClass('working')){
jqXHR.abort();
}
tpl.fadeOut(function(){
tpl.remove();
});
});
// Automatically upload the file once it is added to the queue
var jqXHR = data.submit();
},
progress: function(e, data){
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if(progress == 100){
data.context.removeClass('working');
}
},
fail:function(e, data){
// Something has gone wrong!
data.context.addClass('error');
},
done: function (e, data) {
}
});
We don't have any code yet but the most common mistake in ajax transfers are how they define the data in the call. I upload files like this: (try it)
$.ajax({
type: 'post',
url: 'upload.php',
data: new FormData($('form')[0]),
processData: false,
contentType: false,
success: function (result) {
//show a success message or something else
}
});
Related
I got a problem with no error message. I don't know why this happen. My code working 100% on localhost. But when I upload the code to live shared hosting, there is nothing happen after uploading process. I am using codeigniter 3. This is my html code:
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form method="post" enctype="multipart/form-data">
<div class="modal-header bg-dark">
<h5 class="modal-title">Edit Gambar Profil</h5>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body text-center">
<div class="row">
<div class="col-md-12">
<div class="alert alert-warning">
Sebelum melanjutkan, pastikan Foto Profil yang Anda upload sudah tepat. Hanya berkas <b>JPG</b> dan <b>PNG</b> yang diperbolehkan. Maksimal ukuran berkas <b>2 MB</b>.
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="file" class="form-control-uniform-custom" name="gambar" accept="image/*" id="upload" required>
</div>
</div>
<div class="col-md-8">
<center>
<div id="upload-demo" style="width:350px"></div>
<div id="upload-demo-i"></div>
</center>
</div>
</div>
</div>
<div class="modal-footer" id="upload_footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button class="btn bg-dark upload-result"><i class="icon-check pr-2"></i> Set Gambar Profil</button>
</div>
</form>
</div>
</div>
</div>
And this is my javascript code:
<script>
$("#upload-demo").hide();
$("#upload_footer").hide();
//Mulai crop Image
$uploadCrop = $('#upload-demo').croppie({
enableExif: true,
viewport: {
width: 320,
height: 320,
//type: 'circle'
},
boundary: {
width: 350,
height: 350
}
});
$('#upload').on('change', function () {
$("#upload-demo").show();
$("#upload_footer").show();
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "<?php echo base_url('profil/postfotoprofil');?>",
type: "POST",
data: {"image":resp, "no_register" : "<?php echo sesuser('no_register');?>"},
success: function (data) {
console.log(data);
html = '<img src="' + resp + '" />';
$("#upload-demo-i").html(html);
}
});
});
});
//Akhir Crop image
</script>
And this is my post ajax url controller:
public function postfotoprofil()
{
header("Access-Control-Allow-Headers: Authorization, Content-Type");
header("Access-Control-Allow-Origin: *");
$post = $this->input->post();
$data = $post['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = $post['no_register'].'.png';
unlink('sekolah_berkas/user/'.$imageName);
if(file_put_contents('sekolah_berkas/user/'.$imageName, $data)){
$post_data = array(
"gambar" => $imageName
);
$hajar = $this->db->update("pengguna", $post_data, array("no_register" => $post['no_register']));
if($hajar){
$this->session->set_flashdata('pesen', '<script>sukses("proses");</script>');
}else{
$this->session->set_flashdata('pesen', '<script>gagal("proses");</script>');
}
}else{
$this->session->set_flashdata('pesen', '<script>gagal("proses");</script>');
}
redirect(base_url("profil"));
}
Anyone knows about this, please help.
Problem Solved
Alright guys... thank you very much for reply to my thread. The problem is only on the submit button. I change my code from :
<button class="btn bg-dark upload-result"><i class="icon-check pr-2"></i> Set Gambar Profil</button>
become like this :
<a class="btn bg-dark upload-result"><i class="icon-check pr-2"></i> Set Gambar Profil</a>
and the problem solved. With (button) syntax you will submit immediately to server. Therefore you don't have much time while submitting. Then I change it to syntax (a) and really solved my problem. Look like small problem, with no error message you will get headache.
I need some help. I have a page where I display database records as a bootstrap button pill in a display div. I also have an Ajax Submit input that saves new records to the database and dynamically creates a button pill for the new record using the db record id for the button id. The jQuery below allows me to click on the new dynamically created button but it always displays ID = 1 and not the ID shown in view source.
Can someone please explain what I am doing wrong here?
Code of Button Pills created from PHP:
<div class="row">
<div class="col-md-8 col-sm-10 mx-auto mb-3">
<div class="decision-box">
<div class="decision-icon bg-orange-grad"><img src="../assets/img/logos/Sparck-Logo-Icon-Lg-White.png" alt="Sparck-Logo-Icon-Lg" width="40" height="40" /></div>
<div class="decision-text">
<form id="accolorform">
<input type="hidden" name="action" value="colorsave">
<input type="hidden" name="interesttype" value="Favorite Color">
<input type="hidden" name="userid" value="<?php echo $_SESSION['userid']; ?>">
Favorite Color:
<input type="text" class="form-control-inline col-auto no-border no-shadow" id="ac_color" name="interest" placeholder="Type something" autocomplete="off" style="min-width: 200px;">
<span class="float-right" style="margin-right: 15px;">
<button type="submit" class="btn btn-light" id="colorbtn">Add</button>
</span>
</form>
</div>
</div>
<div id="color_pills">
<?php if(!empty($resultlist) && isset($resultlist)){
foreach($resultlist as $r){
if($r['interesttype'] = "Favorite Color"){ ?>
<button id="btn<?php echo $r['id']; ?>" class="btnpill" title="Are you sure you want to delete <?php echo $r['interest']; ?>?"><?php echo $r['interest']; ?> <i id="<?php echo $r['id']; ?>" class="fal fa-minus-circle delete"></i></button>
<?php }
}
}?>
</div>
</div>
</div>
Code of jQuery aJax that creates dynamic button
$("#accolorform").validate({
rules: {
ac_color: {
required: true
}
},
messages: {
ac_color: {
required: 'Please select a Color'
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $(form).serialize(),
success: function(id){
//alert("Color Added");
var name = $("#ac_color").val();
var newpill = '<button id="btn'+id+'" class="btnpill" title="Are you sure you want to delete '+name+'?">'+name+' <i id="'+id+'" class="fal fa-minus-circle delete"></i></button>';
$("#color_pills").append(newpill);
$("#accolorform")[0].reset();
},
error: function(){
alert("Error");
}
});
}
});
Code of Ajax Delete where I am trying to grab dynamic button id:
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
var title = $('#btn'+id).attr('title');
var string = 'source=interests&id='+ id ;
if (confirm(title)) {
$.ajax({
type: "POST",
url: "ajaxdelete.php",
data: string,
cache: false,
success: function(){
$('#btn'+id).remove();
}
});
}
return false;
});
The above code looks like it should work and view source shows a button tag that is formatted like the ones created by PHP that work perfectly.
I appreciate any help!
I have a modal window that pops up whenever a screen is ideal for 3 minutes. It asks for a PIN to be entered and there is a Continue button on that to be clicked after the PIN is entered in it. On using this Continue button, an insert is made in a database table. Now my problem here is on entering the PIN and clicking on Continue button, the modal does not hides or closes itself. Although the database insertion is done but the modal does not hides. What can be possibly going wrong in this. Any suggestion will be highly helpful. My code,
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation <b>PIN</b><font color="red">*</font><br>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
<p style="font-size:11px"><b><font color="red">*</font><font color="grey"><b>PIN</b><i> is mentioned in your welcome email.</font></i></b></p><br>
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Continue</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(result){
if(result['status'] == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And processActivation.php,
<?php
$uid = $_SESSION['session_user_id'];
$dobCheck = $db->idToField("tbl_user", "dob", $uid);
$dob = explode("-", $dobCheck);
$pin = $_REQUEST['pin'];
$moduleId = $_REQUEST['module_id'];
$chapterId = $_REQUEST['chapter_id'];
$time_taken = $_REQUEST['seconds'];
$created = date("Y-m-d h:i:s");
if($pin != $dob[0])
{
echo "Please enter valid PIN."; die;
}
else
{
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
}
?>
I want to know if
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
is the right way?? Because all of the above operations are being performed correctly and upon that console.log(result) does not shows up anything. Something wrong with the above couple of lines. Very helpful if somebody points out the error in this.
Use the hide function from jQuery.
jQuery('#myModal').hide();
As I know modal('hide') is used for bootstrap modals.
A quick fix maybe, instead of doing
echo json_encode(array('status' => 'active')); and if(result['status'] == 'active')
do
echo "active"; and if(result == 'active')
Use
jQuery('#myModal').toggle().click();
instead of
jQuery('#myModal').modal('hide');
I am loading record details into a modal allowing the user to edit. What I am trying to achieve is to have the user update the record in the modal and then submit to the MySQL table via AJAX / jQuery, however, afte pressing the "Save Changes" button nothing happens. I checked the JS Query and can confirm that the button is linked correctly and also managed to update the database when directly addressing the PHP update script. Not sure why the script refuses to start
Modal:
<div id="output"></div>
<!-- Modal MYMODAL -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Record</h4>
</div>
<div class="modal-body">
<!-- ID No. -->
<div class="form-group">
<label>ID No.:</label>
<input type="number" class="form-control" id="dataPID" name="dataPID" size="5" disabled />
</div>
<!-- /.id number -->
<!-- Category -->
<div class="form-group">
<label>Category:</label>
<input type="text" class="form-control" id="dataCat" name="dataCat" />
</div>
<!-- /.category -->
<!-- Issue -->
<div class="form-group">
<label>Issue:</label>
<input type="text" class="form-control" id="dataIssue" name="dataIssue" />
</div>
<!-- /.issue -->
<!-- Department Responsible -->
<div class="form-group">
<label>Department Responsible:</label>
<input type="text" class="form-control" id="dataDeptResp" name="dataDeptResp" />
</div>
<!-- /.department responsible -->
<!-- Experience -->
<div class="form-group">
<label>Experience:</label>
<input type="text" class="form-control" id="dataExp" name="dataExp" />
</div>
<!-- /.experience -->
<!-- textarea -->
<div class="form-group">
<label>Description:</label>
<textarea class="form-control" id="dataDesc" name="dataDesc" rows="3" ></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" id="SaveChanges" name="SaveChanges" class="btn btn-primary">Save Changes</button>
<button type="button" id="DeleteRecord" name="DeleteRecord" class="btn btn-danger">Delete Record</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- /.Modal MYMODAL -->
Javascript:
$("#SaveChanges").click(function() {
$.ajax({
type: "POST",
url: "plugins/MySQL/ajax_action.php",
data: { action:"update_mysqli",PID:$("#dataPID").val(), Category:$("#dataCat").val(), Issue:$("#dataIssue").val(), Department_Responsible:$("#dataDeptResp").val(), Experience:$("#dataExp").val(), Description:$("#dataDesc").val()}, //your form data to post goes here as a json object
dataType: "json",
contentType:"text",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
});
ajax_action.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['action']) && ($_POST['action']=='update_mysqli')) {
// include connection details
include 'connect_db.php';
//Open a new connection to the MySQL server
$db = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
//Output any connection error
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
// get variables and sanitize
$pid = mysqli_real_escape_string($db,$_POST['PID']);
$cat = mysqli_real_escape_string($db,$_POST['Category']);
$issue = mysqli_real_escape_string($db,$_POST['Issue']);
$dept_resp = mysqli_real_escape_string($db,$_POST['Department_Responsible']);
$exp = mysqli_real_escape_string($db,$_POST['Experience']);
$desc = mysqli_real_escape_string($db,$_POST['Description']);
// check if record exists based on ID number
$result = $db->query("SELECT * FROM qci_problems_index_new WHERE PID='".$pid."'");
// if record is found, update accordingly
if ($result->num_rows > 0){
$sql = "UPDATE qci_problems_index_new SET Category = '$cat', Issue = '$issue', Department_Responsible = '$dept_resp', Experience = '$exp', Description = '$desc' WHERE PID = '$pid'";
if (!$db->query($sql)) {
echo "Error - Update of record PID " . $pid . " failed: (" . $db->errno . ") " . $db->error;
}
} else {
// if no record with relevant PID is found, create new record
$sql = "INSERT INTO `qci_problems_index_new`(`PID`, `Category`, `Issue`, `Department_Responsible`, `Experience`, `Description`) VALUES ('".$pid."', '".$cat."', '".$issue."', '".$dept_resp."', '".$exp."', '".$desc."')";
if (!$db->query($sql)) {
echo "Error - could not insert new record: (" . $db->errno . ") " . $db->error;
}
}
echo "Success, record updated successfully";
//close connection
$db->close();
}
EDIT 1:
Chrome Console says the following:
EDIT 2:
updated code
Change you data type to json and content type to text,add your get variable to the post request
$("#SaveChanges").click(function() {
$.ajax({
type: "POST",
url: "plugins/MySQL/ajax_action.php",
data: { action:"update_mysqli",PID:$("#dataPID").val(), Category:$("#dataCat").val(), Issue:$("#dataIssue").val(), Department_Responsible:$("#dataDeptResp").val(), Experience:$("#dataExp").val(), Description:$("#dataDesc").val()}, //your form data to post goes here as a json object
dataType: "json",
contentType:"text",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
});
php
if(isset($_POST['action']) && ($_POST['action']=='update_mysqli')) {
You are passing the value "update_mysql" in "action" parameter in the ajax URL(plugins/MySQL/ajax_action.php?action=update_mysql). On the other hand your condition in ajax_action.php will only be executed the code if the value of "action" parameter is "update_mysqli"
Change the following line
if(isset($_GET['action']) && ($_GET['action']=='update_mysqli'))
to
if(isset($_GET['action']) && ($_GET['action']=='update_mysql'))
in your ajax_action.php file.
OR
Alternatively, you can pass value update_mysqli instead of update_mysql for your action parameter in ajax call.
Since you are using mysqli, you will prefer this for the sake of best practice as you are using mysqli functions inside code.
My code was working fine before. But Now it is not working. I am working on codeigniter and I am uploading a file using jquery ajax. I donot know why my code stop working. If you can find the issue please let me know.
Here is the controller 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;
}
}
My jquery code which calling above function:
$("#btnupdate").click(function(event){
if($("#fileupload2").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() {
return $.ajaxSettings.xhr();
},
cache:false,
contentType: false,
processData: false,
success: function(result){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
});
}
});
event.preventDefault();
}
} else {
toastr8.info({
message:'Error Occured',
title:"Please try again",
iconClass: "fa fa-info",
});
}
});
HTML:
<div class="modal fade" id="myModal" role="dialog">
<form enctype="multipart/form-data" name="formname" id="formname" method="post" action="">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header ">
<script type="text/javascript">
$(document).ready(function(){
$('#mgupload-dp').click(function(e){
$('#fileupload2').click();
e.preventDefault();
});
});
</script>
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Create profile picture</h4>
</div>
<div class="modal-body">
<div class="text-center" style="width:100%"> <img src="<?php echo base_url(); ?>img/profile.png" alt="add dp" id="pop-dp" >
<button type="button" class="btn btn-default text-center" id="mgupload-dp">Choose picture to upload</button>
<input type="file" id="fileupload2" name="fileUp" class="hidden-dp" accept="image/*">
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="btnupdate">Update Picture</button>
</div>
</div>
</div>
</div>
</form>
</div>
Files are not uploading and I am getting this error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: fileUp
Filename: controllers/Userpage.php
Open the Firebug in FF.
Click on the ajax call URL under Console.
See what are passed under "Post" tab.
If fileUp is present there, use $this->input->post('fileUp'); to fetch the contents.