No data qrcode image pass to URL after Ajax function - javascript

I want to pass data via url using ajax, the result is that no data is captured by the post method.
(function() {
var qr = new QRious({
element: document.getElementById('qr'),
size: 200,
value: 'https://github.com/ddsfdf'
});
var img = qr.toDataURL('image/jpeg');
var img_data = img.replace(/^data:image\/(png|jpg);base64,/, "");
$.ajax({
'type': 'post',
'url': '<?php echo base_url('dasboard/qrcode'); ?>',
data: {
'img': img_data
},
success: function(response) {
}
});
})();
and this is the code in the controller:
$imagedata = base64_decode($_POST['img']);
$filename = $id;
$file_name = './saveimageQR/' . $filename . '.png';
file_put_contents($file_name, $imagedata);
i get result Undefined index:img which means no data sent,please help me Thank You.

Related

Javascript dataURL POST to PHP not working

I'm trying to post dataURL over to php but with no succsess.
My .js file is as follow.
var dataURL = signaturePad.toDataURL();
alert(dataURL);
$.ajax({
type: "POST",
url: "test.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
alert(o);
});
alert(dataURL) output is as follow;
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAADZCAYAAACNbSIWAAAeW.....
test.php
<?php
if($_POST['imgBase64']) {
$img = $_POST['imgBase64'];
}
else{
$img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAADZCAYAAACNbSIWAAAeW.....";
}
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$timestamp = date('YmdHis');
$fileName = ''.$timestamp.'.png';
echo"$fileData";
file_put_contents($fileName, $fileData);
?>
In my php file I have entered the value of my alert for testing purposes. Now my php page is working 100% due to the test and passing no value from my .js function. but with the correct value it's not even posting to my php page, only when I remove all not standard characters from the dataURL then it post but obvious with corrupt data.
To avoid further confusion the following code works 100%, the .js and the php. where var dataURL = signaturePad.toDataURL(); is passed to the function
function postData(data) {
alert(data);
var desired = data.replace(/[^\w\s]/gi, '');
$.ajax({
type: "POST",
url: "test.php",
data: {
imgBase64: desired
}
}).done(function(o) {
console.log('saved');
alert(o);
});
}
So the problem is the .js will not post with the given dataUrl due to special characters, but I cant remove them.. I even tried var desired = encodeURIComponent(data); witch I can at least decode on the php page but this also does not want to post.
data: {
imgBase64: data
//send key is imgBase64 and data value is undefined in given scope
//replace data with dataURL
}
And in php file change this $_POST['image'] to $_POST['imgBase64']
Thanks for the replies..
I ended up creating a blob first and posting the blob.
function dataURLToBlob(dataURL) {
var parts = dataURL.split(';base64,');
var contentType = parts[0].split(":")[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
$.post("test2.php",
{
name: uInt8Array
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
}

how to upload image from codeigniter to mysql

I am new in CodeIgniter. I am not getting how to update form data in the database. Insertion and showing data from database is done but can't understand how to update data in the database.
I've tried researching this link but data not successfully uploaded.
This is my Controller
//npwp
$temp1 = explode(".", $_FILES['file_npwp']['name']);
$new_name1 = time().'.'.end($temp1);
$config1['upload_path'] = APPPATH.'/file_npwp/';
$config1['file_name'] = $new_name1;
$config1['overwrite'] = TRUE;
$config1['allowed_types'] = 'jpg|jpeg|png|pdf';
$this->load->library('upload',$config1);
$this->upload->initialize($config1);
if(!$this->upload->do_upload('file_npwp')){
$this->data['error'] = $this->upload->display_errors();
}
$media1 = $this->upload->data('file_npwp');
This is my Model
$data_service['file_npwp']= $file_lampiran1;
$data_service['file_ktp']= $file_lampiran2;
$data_service['file_po']= $file_lampiran3;
$data_service['file_registrasi']= $file_lampiran4;
$this->db->where('id_service',$this->input->post('id_service'));
$this->db->update('service_sis', $data_service);
This is my View
<div class="form-group">
<label for="">File NPWP</label>
<input type="file" name="file_npwp" id="file_npwp" class="form-control">
</div>
<br>
<div id="hasilloadfoto"></div>
<br>
<p>*Pastikan semua form sudah terisi dengan benar</p>
<button id="SaveAccount" class="btn btn-success">Simpan</button>
This is my Javascript in my view
$( function() {
var $signupForm = $( '#myForm' );
$signupForm.validate({errorElement: 'em'});
$signupForm.formToWizard({
submitButton: 'SaveAccount',
nextBtnName: 'Selanjutnya',
prevBtnName: 'Sebelumnya',
nextBtnClass: 'btn btn-primary btn-flat next',
prevBtnClass: 'btn btn-default btn-flat prev',
buttonTag: 'button',
validateBeforeNext: function(form, step) {
var stepIsValid = true;
var validator = form.validate();
$(':input', step).each( function(index) {
var xy = validator.element(this);
stepIsValid = stepIsValid && (typeof xy == 'undefined' || xy);
});
return stepIsValid;
},
progress: function (i, count) {
$('#progress-complete).width(''+(i/count*100)+'%');
}
});
});
function filePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#hasilloadfoto + img').remove();
$('#hasilloadfoto').after('<img src="'+e.target.result+'" width="450" height="300"/>');
}
reader.readAsDataURL(input.files[0]);
}
}
$(document).ready(function(){
$("#file_npwp").change(functio () {
filePreview(this);
});
Need help in update operation. I appreciate any help.
you can do in two ways,
You can upload the image to any cloud storage(Aws, Azure, etc) then update the link on your Db
Convert the image into base64 and update it as the string on your DB.
I will prefer to go with step one, I have the sample where I have uploaded it to Azure and update my DB
// This is on Js , Using ajax , I will send to controller
function uploadImage() {
var base_url = '<?php echo BASEURL ?>';
// call ajax to upload image
//event.preventDefault();
var file_data = $('#post-image').prop('files')[0];
var form_data = new FormData();
form_data.append('uploaded_file', file_data);
$.ajax({
url: base_url + "dashboard/uploadImage",
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (aData) {
},
error: function (data) {
alert(data);
}
});
}
On Controller ,
public function uploadImage() {
// get the 'api-key' key from Request Headers
$data = array();
if (isset($_FILES ['uploaded_file']['name']) && !empty($_FILES ['uploaded_file']['name'])) {
$userId = $this->input->post("userId");
$file_name = $userId . "_" . uniqid() . ".jpg";
$S3ImgUrl = uploadImageToS3($_FILES ['uploaded_file']['tmp_name'], "app_feed_images", $file_name);
$data = array(
'code' => 555,
'message' => 'Image has been uploaded successfully',
'url' => $S3ImgUrl
);
} else {
$data['code'] = -111;
$msg = "failed to upload image to s3";
$data ['status'] = $this->failed_string;
}
// var_dump($data);
echo json_encode($data);
}
Helper Class
function uploadImageToS3($tmp, $bucket, $file_name) {
$connectionString = "DefaultEndpointsProtocol=https;AccountName=" . azure_bucket_name . ";AccountKey=" . azure_bucket_key;
$blobClient = MicrosoftAzure\Storage\Blob\BlobRestProxy::createBlobService($connectionString);
$containerName = "app-image/" . $bucket;
$containerUrl = "https://hbimg.blob.core.windows.net/";
$content = fopen($tmp, "r");
$options = new MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions();
$content_type = $_FILES['uploaded_file']['type'];
$options->setContentType($content_type);
$blobClient->createBlockBlob($containerName, $file_name, $content, $options);
return $containerUrl . $containerName . "/" . $file_name; }
On the controller side, I have just uploaded the image, you can call you model class with the uploaded image link and update on your DB.
Happy coding :)
All you need is to send the name of the photo in database right then in model you have to add
$this->input->post('databse_column_name')=$variable_name_which_content_file_name

Ajax code in php and javascript regarding an image file

I am trying to save image file through signature pad. I want the name of the file to be an element from my div. Which changes accordingly. Here is my code. It is saving the image but the filename is blank(.png).
Javascript:
$("#btnSaveSign").click(function(e){
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
var p = document.getElementById('my_class').innerHtml;
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:p}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
save_sign.php:
<?php
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = $_POST['p'];
//Location to where you want to created sign image
$file_name = './doc_signs/'.$filename.'.png';
file_put_contents($file_name,$imagedata);
$result['status'] = 1;
$result['file_name'] = $file_name;
echo json_encode($result);
?>
Replace with your assignment with var p = document.getElementById('my_class').value;
Due to onrendered function is a callback, it may not get the document.getElementById('my_class').innerHtml properly. Please get echo out the $_POST['p'] to make sure proper filename is sent to PHP side.
get document.getElementById('my_class').innerHtml before call html2canvas function.
$("#btnSaveSign").click(function(e){
var p = document.getElementById('my_class').innerText;
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
// ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:p}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
$("#btnSaveSign").click(function(e){
var p = document.getElementById('my_class').innerText;
html2canvas([document.getElementById('sign-pad')], {
onrendered: function (canvas) {
var canvas_img_data = canvas.toDataURL('image/png');
var img_data = canvas_img_data.replace(/^data:image\/(png|jpg);base64,/, "");
// ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: [{ img_data:img_data, p:document.getElementById('my_class').innerText}],
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});

How to reload a img attr "src" after ajax call without knowing the file name from the image tag?

I have this html:
<div class="d-inline-flex">
<img id="reloadIMG" class="p-3 mt-5 imgP" onDragStart="return false" <?php echo htmlentities($avatar, \ENT_QUOTES, 'UTF-8', false); ?>>
<input type="file" id="uploadAvatar" name="uploadedAvatar">
</div>
the value of $avatar:
$pathFolderAvatar = 'user/'.$folder.'/avatar/*';
$imgUserPastaAvatar = glob($pathFolderAvatar)[0] ?? NULL;
if(file_exists($imgUserPastaAvatar)){
$avatar = 'src='.$siteURL.'/'.$imgUserPastaAvatar;
}else{
$avatar = 'src='.$siteURL.'/img/avatar/'.$imgPF.'.jpg';
}
and the script to send a ajax call to my file that process the file upload request:
$(function () {
var form;
$('#uploadAvatar').change(function (event) {
form = new FormData();
form.append('uploadedAvatar', event.target.files[0]);
});
$("#uploadAvatar").change(function() {
$("#loadingIMG").show();
var imgEditATTR = $("div.imgP").next().attr("src");
var imgEdit = $("div.imgP").next();
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime());
}
});
});
});
i tried to force the browser to reload the img on success ajax call $(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime()); but the selector from the var imgEdit and imgEditATTR is not working:
console.log(imgEdit); result: w.fn.init [prevObject: w.fn.init(0)]
console.log(imgEdit); result: undefined;
Why is it happening, and how to fix?
I know that there's a bunch of questions about reload img, but on these questions there's not a method to reload a image without knowing the file name. I checked so many questions and this is what the answears say:
d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
On my case i don't know the file name, because it's generated randomly on profileForm.php with mt_rand():
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
You can return file name in response to your AJAX request and use it in success block to update src attribute of img tag
So your profileForm.php will look something like
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000).'_'.time();
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo $newname // you can also send a JSON object here
// this can be either echo or return depending on how you call the function
and your AJAX code will look like
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data);
}
});
Let profileForm.php return the generated filename:
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo json_encode(['filename' => $folderPFFetchFILE]);
Then in the callback of your POST request:
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data.filename);
}

Codeigniter: Uploading image through Ajax and storing in db

I am using CI 3.0.1 was uploading and inserting image to db successfully before i used ajax, i guess trying to do it with ajax i'm missing something which isn't even sending data to upload maybe because we have to use multipart() in form while in ajax we are just sending data direct to controller, another thing i don't know how to receive the variable in response
my Ajax request function is:
<script type="text/javascript">
$(document).ready(function() {
alert("thirddddddddd");
$('#btnsubmit').click(function()
{
alert("i got submitted");
event.preventDefault();
var userfile = $("input#pfile").val();
alert("uploading");
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload', //how to receive var here ?
type: 'POST',
cache: false,
data: {userfile: userfile},
success: function(data) {
alert(data);
$('.img_pre').attr('src', "<?php echo base_url().'uploads/' ?>");
$('.dltbtn').hide();
},
error: function(data)
{
console.log("error");
console.log(data);
alert("Error :"+data);
}
});
});
});
And my controller Upload's function do_upload is:
public function do_upload()
{
$config['upload_path'] = './uploads/'; #$this->config->item('base_url').
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('layouts/header');
$this->load->view('home_page', $error);
$this->load->view('layouts/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$imagedata = $this->input->post('uerfile');
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$result = $this->model_edit->update_dp($id, $imagedata);
$image_name = $result->images;
$this->session->set_userdata('image', $image_name);
echo json_encode($name = array('image' => $image_name));
// $image_name = $this->upload->data('file_name');
// $data = array('upload_data' => $this->upload->data());
// redirect("account");
}
}
Now image is not even going to uploads folder, if any other file is needed tell me i'll post it here. Thanks
You cannot send file data using $("input#pfile").val();
var len = $("#pfile").files.length;
var file = new Array();
var formdata = new FormData();
for(i=0;i<len;i++)
{
file[i] = $("input#pfile").files[i];
formdata.append("file"+i, file[i]);
}
and send formdata as data from ajax
Hope it helps !
Try with the below ajax code
var formData = new FormData($('#formid'));
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload',
data: formData ,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
The file contents may not send through ajax as per your code. Try with the attributes mentioned in above code.

Categories

Resources