I'm using croppie.js to crop user uploaded imaged, once the crop is done ajax is used to upload the result. Here is the codes for that...
Page A..
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "uploadown/uploader.php",
type: "POST",
data: {"image":resp},
success: function (data) {
html = '<img id="cropresult" style="margin: 0px;" src="' + resp + '" />;
$("#uploaded-input").html(html);
}
});
});
});
Then uploader.php is..
<?php
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
file_put_contents($imageName, $data);
?>
As you can see uploader.php is using time() for the $imageName variable.
I either need to pass $imageName back to Page A during upload
or
set $imageName in page A first and pass it to uploader.php at the same time as the image info.
After a few hours and many attempts having read many similar questions on here and cannot work out how to do this. Any help greatly appreciated.
Echo out the $imageName in php file, once done use it in javascript.
PHP
<?php
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
if(file_put_contents($imageName, $data)){
echo $imageName;
} else {
echo " ";//In this case src will be empty
}
?>
Java script
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "uploadown/uploader.php",
type: "POST",
data: {"image":resp},
success: function (data) {
html = '<img id="cropresult" style="margin: 0px;" src="' + data + '" />';
$("#uploaded-input").html(html);
}
});
});
});
For any queries comment down.
just echo the name in php or var_dump() the array and then you will be able to access it in your javascript
all the data from the php page is addign to the variable name you give to the anonymous function you give to the success callback. for your case it will be accessed as data
Found your full exmaple here: https://websolutionstuff.com/post/crop-image-before-upload-using-croppie-plugin
Consider the following PHP.
<?php
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
if(file_put_contents($imageName, $data)){
echo "Success, " . $imageName;
} else {
echo "Error, unable to Put file.";
}
?>
This will provide a response to the AJAX Script.
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "uploadown/uploader.php",
type: "POST",
data: { "image":resp },
success: function (data) {
var response = data.split(",");
var html;
if(response[0] != "Error"){
html = '<img id="cropresult" style="margin: 0px;" src="' + response[1].trim() + '" />';
$("#uploaded-input").html(html);
} else {
console.log(data);
}
}
});
});
});
Related
I wrote the following code snippet for Ajax connections, but unfortunately the return value is not displayed in the output, but it does not give a special warning to understand the meaning. Please help.
js
$("#search").on('keyup', function(){var value = $(this).val();
$.ajax('feed.php',{
type: 'POST',
dataType: 'json',
data: {
keyword: value
},
success: function(data){
$("#pre").html(data);
}
});
});
feed.php
<?php
require_once('main.php');
$db = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $db->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$out['html']= '';
foreach($records as $record){
$out['html'] .= $record['word'] . '<br>';
}
echo json_encode($out);
?>
js:
jQuery('#search').on('keyup', () => {
jQuery.ajax({
url: 'feed.php',
type: 'POST',
data: { keyword: jQuery(this).val() },
success: response => {
jQuery('#pre').html(response);
}
});
});
feed.php
<?php
require_once('main.php');
$database = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $database->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$output = '';
foreach($records as $record){
$output .= $record['word'] . '<br />';
}
echo($output);
?>
PS: You don't need to use json output absolutly. But if there is coercion to using json output, the problem is 2 following items:
You don't set the output "Content-Type" to json: header('Content-Type: application/json');
You shouldn't pass the json object to html method in jQuery and should parsing it at first with JSON.parse(response) class, then with foreach, for or anything else process it
I can't seem to pass the "filename" variable from main.php to save_sign.php, can someone help me with this?
main.php
<? $filename="222222"; ?>
<script>
$(document).ready(function() {
$('#signArea').signaturePad({drawOnly:true, drawBezierCurves:true, lineTop:90});
});
$("#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 filename = '<? echo $filename; ?>';
//ajax call to save image inside folder
$.ajax({
url: 'save_sign.php',
data: { img_data:img_data },
type: 'post',
dataType: 'json',
success: function (response) {
window.location.reload();
}
});
}
});
});
</script>
save_sign.php
<?php
$result = array();
$imagedata = base64_decode($_POST['img_data']);
$filename = $_POST['filename'];
//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);
?>
You need to add filename var to ajax data like below
url: 'save_sign.php',
data: { img_data:img_data,filename:filename}
I am in need to send an ajax call to a function in following directory structure
Yii::$app->request->absoluteUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile";
my view function
function uploadImage(){
var url = '<?php echo Yii::app()->request->baseUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile"; ?>';
console.log(url);
return false;
$.ajax({
url:'<?php echo Yii::$app->createUrl("Post/UploadMusicFile"); ?>',
method:'post',
data:{file:$('input[type="file"]')},
dataType:'',
contentType:false,
processData:false,
success:function(data){
var parsed_data = $.parseJSON(data);
},
error:function(data){
console.log("Error "+data);
}
});
}
function which i am posting to
public function UploadMusicFile(){
$file = Yii::$app->request->post('file');
echo "<pre>";
print_r($file);
echo "</pre>";
exit();
$target_dir = "/home/jmwglobaladmin/public_html/melmory/uploads/music_memory/";
$target_file = $target_dir . basename($_FILES["files"]["name"][0]);
foreach ($_FILES["files"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["files"]["tmp_name"][$key];
move_uploaded_file($tmp_name, $target_file);
$connection = Yii::$app->getDb();
$command = $connection->createCommand('select id from post order by id desc limit 1');
$result = $command->queryAll();
$new_id = $result[0]['id']+1;
$file_name = "abc.mp3";
$connection = Yii::$app->getDb();
$command_insert = $connection->createCommand('insert into memory_music (post_id,memory_music) values ("'.$new_id.'","'.$file_name.'")');
$result = $command_insert->execute();
}
}
}
I get the error of 404. How to pass proper url in yii to a function which is present in directory structure like mentioned above?
Basics. Your function is not an action.
Change this:
public function UploadMusicFile()
To this:
public function actionUploadMusicFile()
I am really new to ajax do forgive me if the question is stupid. I have a multi step form and it has the 4 parts , and I am using $.post() ajax request to send this. while all my other details are going fine I am not able to upload my file. this is what I am trying to do
Here I am trying to catch the form values.
var data_img = new FormData();
var hello = $.each(jQuery('#pan_file')[0].files, function (i, file) {
data_img.append('file-' + i, file);
});
Then I am passing these values to the object variable.
obj_params.pan_file = hello;
And then sending it to store with ajax.post()
$.post('<?php echo base_url(); ?>get-ekyc-form', obj_params, function (msg) {
if (msg == "1") {
swal("Success!", "EKYC Form has been Submitted Successfully", "success");
window.location = '<?php echo base_url(); ?>list-active-requirement';
}
}, "json", "processData:false", "contentType:false");
return true;
And this is where I do file transfer.
if ($_FILES['file-0']['name'] != "") {
$image_data = array();
//config initialise for uploading image
$config['upload_path'] = './media/front/img/quote-docs/';
$config['allowed_types'] = 'xlsx|pdf|doc|docx';
$config['max_size'] = '5000';
$config['max_width'] = '12024';
$config['max_height'] = '7268';
$config['file_name'] = time();
//loading upload library
$this->upload->initialize($config);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file-0')) {
$error = array('error' => $this->upload->display_errors());
} else {
$data = array('upload_data' => $this->upload->data());
$image_data = $this->upload->data();
$file_name = $image_data['file-0'];
}
$file_name = $image_data['file_name'];
} else {
$file_name = '';
}
Also I am working on someone elses code so I do understand I must have made loads of mistakes. I'll be grateful if someone could help me around this.
HTML code
<input id="picture" type="file" name="pic" />
<button id="upload">Upload</button>
$('#upload').on('click', function() {
var file_data = $('#picture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
in upload.php
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
In my project am using ajax for sending message the problem is i can't get the response in the ajax function the function works perfectly before,Can't find exact cause of the issue help me to solve it
ajax
var str = {
message:message, department_id:department, email:email, username:name
};
$.ajax( {
type: "POST",
url:'<?php echo base_url(); ?>home/savemessage',
dataType:"json",
data: str,
success: function(msg) {
$('#sentchat') . hide();
$('#chatmessage') . show();
$('#userchat') . html(msg . dataid);
$('.chat-box-content') . hide();
$('#adminname span').html('waiting for admins reply');
var elem = document . getElementById('userchat');
elem.scrollTop = elem . scrollHeight;
}
});
php controller
function savemessage() {
extract($this->input->post());
$data['message_id'] = $this->session->userdata('msgid');
$data['username'] = $username;
$data['email'] = $email;
$data['department_id'] = $department_id;
$data['message'] = $message;
$data['datetime'] = date('Y-m-d H:i:s');
$data['status'] = 'new';
$data['message_by'] = '1';
$this->db->insert('message', $data);
echo json_encode($username);
exit;
}
I cant get the response in it help me to solve it
You use ajax to communicate with a PHP script, inside the PHP script you could have the content of the function you want to execute. For example in your code:
$.ajax( {
type: "POST",
url:'<?php echo base_url(); ?>home/savemessage.php',
dataType:"json",
data: {myData:str},
success: function(msg) {
$('#sentchat') . hide();
$('#chatmessage') . show();
$('#userchat') . html(msg . dataid);
$('.chat-box-content') . hide();
$('#adminname span').html('waiting for admins reply');
var elem = document . getElementById('userchat');
elem.scrollTop = elem . scrollHeight;
}
});
Then, on the server side the php script "savemessage.php" would receive the POST action, so you could have:
if(isset($_POST['myData']) && !empty($_POST['myData'])) {
$obj = $_POST['myData'];
//rest of your code
echo json_encode($username);
exit;
}
However from your code I cannot see $username defined, so that probably would return an error.