i have created a native javascript code (w/o jquery) to upload using php for server side, it seems that everything is ok and going fine, but when i selected 10 or more images, not all of them are uploaded some images are having problem, here is my javascript so far:
var uploadevent = function(event) {
event.preventDefault();
event.stopPropagation();
var xhr = new XMLHttpRequest();
var data = new FormData();
for(var i = 0; i < images.files.length; ++i) {
data.append('images[]', images.files[i]);
}
data.append('EmailAd', EmailAd);
data.append('UserID', UserID);
data.append('Studentnumber', Studentnumber);
data.append('album_name', document.getElementById('hidden_album_name').value);
var ul_album_thumbnails = document.getElementById('ul_album_thumbnails');
var rand = Math.random().toString().split('.');
var str = rand[1]; // need this to generate unique id
var newli = document.createElement('li');
newli.setAttribute('id', str);
var display = document.createElement('div'); // div element that handles preview
display.style.position = "relative";
display.style.height = "191px";
display.style.width = "180px";
display.style.cssFloat = "right";
display.style.border = "1px solid #a4a4a4";
display.style.background = "#fff";
display.style.zIndex = '998'; // this thumbnail container should be on the top
$(display).append("<progress id='progressBar' style='border:1px solid #a4a4a4;position:absolute;bottom:0px;width:178px;z-index:1' value='0' max='100'></progress>");
$(display).append("<div id='progressStatus' style='position:absolute;bottom:0px;width:178px;z-index:1;text-align:right;background:transparent'></div>");
newli.appendChild(display);
ul_album_thumbnails.insertBefore(newli, ul_album_thumbnails.childNodes[1]);
xhr.upload.addEventListener('progress', function(event) {
var percent = (event.loaded / event.total) * 100;
document.getElementById('progressBar').value = Math.round(percent);
document.getElementById('progressStatus').innerHTML = Math.round(percent) + ' %';
});
xhr.onload = function() {
if((typeof this.response == 'object' || typeof this.response) && this.status == 200 && this.response != '') {
try {
var $resp = JSON.parse(this.response);
document.body.style.overflowY = 'auto';
divback.removeAttribute('style');
$('#ul_album_thumbnails > li#' + str + ' > div').css('z-index','1');
$('li#' + str + ' > div').html('');
var newimg = document.createElement('img'), thumb = $resp.ImageUrl.replace('../', '');
newimg.src = 'temp_pages/image.php?nocache=nocache&width=180&height=180&cropratio=5:4&image=/prototype/' + thumb;
$('li#' + str + ' > div').append(newimg);
var strs = $resp.AlbumName; // album name
var divfooter = document.createElement('div');
divfooter.style.position = 'absolute';
divfooter.style.width = '180px';
divfooter.style.height = '50px';
divfooter.style.bottom = '0px';
$(divfooter).append("<a href='JavaScript:void(0)' style='font-family:Tahoma, Geneva, sans-serif;font-size:11px;font-weight:bold;position:relative;top:8px;left:3px;'>" + strs + "</a>");
$('li#' + str + ' > div').append(divfooter);
images.value = '';
document.getElementById('hidden_album_name').value = '';
} catch(SyntaxError) {
}
} else {
}
} // end of xmlhttprequest onload event
xhr.open('POST', 'ajax/ajax_upload_photo_album.php', true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.send(data);
xhr.close();
}
and this is my PHP
<?php
function find($filename, $key) {
//$x = is_file($base . $filename) ? 'true' : 'false';
// count the number of period occurence as this return an array object
$countp = explode('.', $filename);
$s = (count($countp) > 2) ? end($countp) : $countp[1];
$countp[0] = md5($countp[0]) . md5(rand());
if($key == 0) {
$filename = $countp[0] . '_' . 'thumbnail' . '.' . $s;
} else {
$filename = $countp[0] . '.' . $s;
}
return strtolower($filename);
}
$base_url = '../user/images/albums/';
$EmailAd = $_REQUEST['EmailAd'];
$username = explode('#', $EmailAd);
$UserID = $_REQUEST['UserID'];
$Studentnumber = $_REQUEST['Studentnumber'];
$album_name = $_REQUEST['album_name'];
$base_url .= $UserID.'_'.$Studentnumber.'_'.$username[0].'/'.$UserID.'_'.$Studentnumber.'_'.$username[0].'_'.$album_name.'/';
$tmp = array();
foreach($_FILES['images']['name'] as $key => $name) {
//$sizexy = getimagesize($w);
$image_info = getimagesize($_FILES['images']['tmp_name'][$key]);
$imageWidth = $image_info[0];
$imageHeight = $image_info[1];
$f = $base_url . $imageWidth . '_' . $imageHeight . '_' . find($name, $key);
if($_FILES['images']['error'][$key] == 0 && move_uploaded_file($_FILES['images']['tmp_name'][$key], $f)) {
if($key == 0) {
$g = array('ImageUrl' => $f, 'BaseUrl' => $base_url, 'AlbumName' => $album_name, 'ImageCount' => count($_FILES['images']['name']), 'Created' => date('h:ia', filectime($base_url)));
}
}
}
echo json_encode($g);
clearstatcache();
?>
is there alternative code for this?
Related
I have a input for searching in my website and I assign onkeyup event for that.
For example my string is : 'hello world' and when the user types 'llo'(or anything else)show the matched characters as highlighted with the other characters in search list below input.(like google search)
I try this but my code works for the first character not the all characters of string
My code :
//html
<input type="text" onKeyUp="search_customer(this)">
<div class="data_list"></div>
//javascript
function search_customer(input){
var text = input.value;
if(text == ''){
input.nextElementSibling.style.display = 'none';
return;
}
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
var result = JSON.parse(xhr.responseText);
show_results(result , input);
}else{
alert('request was unsuccessful : ' + xhr.status);
}
}
xhr.open('post' , "<?php echo base_url('deal/search/')?>" , true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('text_search=' + text);
}
function show_results(res , input){
var datalist = input.nextElementSibling;
datalist.style.display = 'block';
if(res.length == 0){
datalist.innerHTML = '<div>nothing matched!<div>';
}else{
var div = document.createElement('div');
for(var i = 0 ; i < res.length ; i++){
if(res[i].full_name.substr(0 , input.value.length) == input.value){
var str = '<strong>'+res[i].full_name.substr(0 , input.value.length)+'</strong>' + res[i].full_name.substr(input.value.length);
var p = div.appendChild(document.createElement('p'));
p.innerHTML = str;
}
}
datalist.replaceChild(div , datalist.firstChild);
}
xhr.open;
}
You can use indexOf to get first index in the matched string and then calculate the last index. Also it's better to use the method slice to be able to use a negative index.
function search_customer(input){
var text = input.value;
if(text == ''){
input.nextElementSibling.style.display = 'none';
return;
}
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
var result = JSON.parse(xhr.responseText);
show_results(result , input);
}else{
alert('request was unsuccessful : ' + xhr.status);
}
}
xhr.open('post' , "<?php echo base_url('deal/search/')?>" , true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('text_search=' + text);
}
function show_results(res , input){
var datalist = input.nextElementSibling;
datalist.style.display = 'block';
if(res.length == 0){
datalist.innerHTML = '<div>nothing matched!<div>';
}else{
var div = document.createElement('div');
for(let i = 0 ; i < res.length ; i++){
let search = input.value;
let match;
let lastIndx = (res[i].full_name.length-1) - res[i].full_name.indexOf(search) - (search.length-1);
if(lastIndx == 0){
match = res[i].full_name.slice(res[i].full_name.indexOf(search), res[i].full_name.length);
}else{
match = res[i].full_name.slice(res[i].full_name.indexOf(search), -lastIndx);
}
let str = res[i].full_name.slice(0, res[i].full_name.indexOf(search) ) + '<strong>' + match + '</strong>'+ res[i].full_name.slice(res[i].full_name.length-lastIndx, res[i].full_name.length);
let p = div.appendChild(document.createElement('p'));
p.innerHTML = str;
}
datalist.replaceChild(div , datalist.firstChild);
}
xhr.open;
}
I am running into issues when uploading an image sent to PHP via JS. I can upload the image fine, but I would to resize the image before moving it to it's new destination. I can also rename the image without any issues. It's really just the resizing that is the issue here.
After a lot of searching I have seen a lot of questions regarding this on SO, which is how I got to where I am now, but not one that answers this 100%. If you know of a question/answer already on SO please link me to the correct article.
Any help is much appreciated, thanks.
Here is the JS
var test = document.querySelector('#afile');
test.addEventListener('change', function() {
var file = this.files[0];
var fd = new FormData();
fd.append('afile', file);
// These extra params aren't necessary but show that you can include other data.
fd.append('id', burgerId);
var xhr = new XMLHttpRequest();
// why wont this work in the actions directory?
xhr.open('POST', 'actions/upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
var uploadProcess = document.getElementById('uploadProcess');
uploadProcess.setAttribute('style', 'width: ' + percentComplete + '%;');
// uploadProcess.innerHTML = parseInt(percentComplete) + '% uploaded';
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
image = 'img/' + resp.newFileName;
sessionStorage.setItem('burgerLoc', image);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
// upImage(id)
}, false);
Here is the markup
<input type="file" name="afile" id="afile" accept="image/*"/>
Here is the PHP
$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];
function getName($str) {
$parts = explode('.',$str);
$imgName = str_replace(' ', '_',$parts[0]);
return $imgName;
}
function getExtension($str) {
$parts = explode('.',$str);
$ext = $parts[1];
return $ext;
}
$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);
if($ext == 'jpg' || $ext == 'jpeg' ) {
$ext = 'jpg';
$src = imagecreatefromjpeg($image_tmp);
} else if($ext == 'png') {
$src = imagecreatefrompng($image_tmp);
} else {
$src = imagecreatefromgif($image_tmp);
}
$file_content = file_get_contents($image_tmp);
$data_url = 'data:' . $image_type . ';base64,' . base64_encode($file_content);
list($width,$height) = getimagesize($image_tmp);
// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
// rename the file
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = '../img/' . $new_file_name;
imagejpeg($img_dest,$new_file_name,100);
move_uploaded_file($image_tmp, $new_file_location);
imagedestroy($src);
imagedestroy($img_dest);
$json = json_encode(array(
'dataUrl' => $data_url,
'extension' => $ext,
'id' => $_REQUEST['id'],
'name' => $image,
'newFileName' => $new_file_name,
'type' => $image_type
));
echo $json;
I would maybe try installing ImageMagick in your linux distribution and try to use this function to resize the image
http://php.net/manual/en/imagick.resizeimage.php
I have reproduced your script on my webserver... I have made modifications and came up with this.
The most significant modification is that I am using exact paths in the file locations, and that I am moving the tmp file to a real file, load that real file, resize that real file instead of trying it to do with the tmp uploaded file.
PHP:
<?php
$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];
function getName($str) {
$parts = explode('.',$str);
$imgName = str_replace(' ', '_',$parts[0]);
return $imgName;
}
function getExtension($str) {
$parts = explode('.',$str);
$ext = $parts[1];
return $ext;
}
$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);
$outputfolder = "/var/www/html/wp-content/";
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = $outputfolder.$new_file_name;
move_uploaded_file($image_tmp, $new_file_location);
if($ext == 'jpg' || $ext == 'jpeg' ) {
$ext = 'jpg';
$src = imagecreatefromjpeg($new_file_location);
} else if($ext == 'png') {
$src = imagecreatefrompng($new_file_location);
} else {
$src = imagecreatefromgif($new_file_location);
}
list($width,$height) = getimagesize($new_file_location);
// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
$resizedLocation = $outputfolder."resized_".$new_file_name;
imagejpeg($img_dest,$resizedLocation,100);
imagedestroy($src);
imagedestroy($img_dest);
$file_content = file_get_contents($resizedLocation);
$data_url = 'data:image/jpeg;base64,' . base64_encode($file_content);
$json = json_encode(array(
'dataUrl' => $data_url,
'extension' => $ext,
'id' => $_REQUEST['id'],
'name' => $image,
'newFileName' => $new_file_name,
'type' => $image_type
));
echo $json;
?>
Your HTML/JS stays untouched.
Now this works for me flawlessly, the only thing you have to make sure
the $outputfolder is writeable by the linux user under which the webeserver executing the php script is runnging (typically web-data...)
My web server:
CentOS Linux release 7.0.1406 (Core)
php.x86_64 5.4.16-23.el7_0.3
apache x86_64 2.4.6
I have the following code:
<script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript'>
var last_song = '$song[1]';
var jqy = jQuery.noConflict()
var change_radio = setInterval(function ()
{
jqy.ajax({
url : 'modules/ajax/refresh.php',
type : 'GET',
data : {lastsong: 'last_song'},
success: function(data)
{
last_song = data;
jqy('#radio').html(last_song);
}
});
}, ($refresh*1000));
change_radio;
</script>
refresh.php
<?php
$lastsong = $_GET['lastsong'];
$timeout = "2"; // Number of seconds before connecton times out.
$ip[1] = "198.101.13.110"; // IP address of shoutcast server
$port[1] = "8000"; // Port of shoutcast server
//$song = [];
//$msg = [];
//END CONFIGURATION
$servers = count($ip);
$i = "1";
while ($i <= $servers)
{
$fp = #fsockopen($ip[$i], $port[$i], $errno, $errstr, $timeout);
if (!$fp)
{
$listeners[$i] = "0";
$msg[$i] = "<span class=\"red\">ERROR [Connection refused / Server down]</span>";
$error[$i] = "1";
}
else
{
fputs($fp, "GET /7.html HTTP/1.0\r\nUser-Agent: Mozilla\r\n\r\n");
while (!feof($fp)) $info = fgets($fp);
$info = str_replace('<HTML><meta http-equiv="Pragma" content="no-cache"></head><body>', "", $info);
$info = str_replace('</body></html>', "", $info);
$stats = explode(',', $info);
if (empty($stats[1]))
{
$listeners[$i] = "0";
$msg[$i] = "<span class=\"red\">ERROR [There is no source connected]</span>";
$error[$i] = "1";
}
else
{
if ($stats[1] == "1")
{
$song[$i] = $stats[6];
$listeners[$i] = $stats[4];
$max[$i] = $stats[3];
// Both IFs the same? Please check that and make one only if its the case
if ($stats[0] == $max[$i]) $msg[$i] = "<span class=\"red\">";
if ($stats[0] == $max[$i]) $msg[$i] .= "</span>";
}
else
{
$listeners[$i] = "0";
$msg[$i] = " <span class=\"red\">ERROR [Cannot get info from server]</span>";
$error[$i] = "1";
}
}
}
$i++;
}
if($song[1] != "")
{
echo $song[1];
exit();
}
echo uriencode($lastsong);
?>
And I want to change it to use prototype instead. I use prototype and jQuery already, and this is conflicting as written. I've no idea where to begin, but any assistance would be appreciated... especially since there are a lot of folks in my situation. Thanks so much.
im trying to make a enrollment system in the school and i need help
not to duplicate the emails and fullname with middlename, but if the name and lastname is the same its ok to add but with the middlename will not continue to add the student. still the same process when i update the student
function student($param1 = '', $param2 = '', $param3 = '')
{
if ($this->session->userdata('admin_login') != 1)
redirect('login', 'refresh');
if ($param1 == 'create') {
$data['name'] = $this->input->post('name');
$data['mname'] = $this->input->post('mname');
$data['lastname'] = $this->input->post('lastname');
$data['birthday'] = $this->input->post('birthday');
$data['sex'] = $this->input->post('sex');
$data['address'] = $this->input->post('address');
$data['phone'] = $this->input->post('phone');
$data['email'] = $this->input->post('email');
$data['password'] = md5($this->input->post('password'));
$data['father_name'] = $this->input->post('father_name');
$data['mother_name'] = $this->input->post('mother_name');
$data['class_id'] = $this->input->post('class_id');
$data['roll'] = $this->input->post('roll');
$this->db->insert('student', $data);
$student_id = mysql_insert_id();
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/student_image/' . $student_id . '.jpg');
$this->email_model->account_opening_email('student', $data['email']); //SEND EMAIL ACCOUNT OPENING EMAIL
$this->session->set_flashdata('flash_message', get_phrase('add_student_success'));
redirect(base_url() . 'index.php?admin/student/' . $data['class_id'], 'refresh');
}
if ($param2 == 'do_update') {
$data['name'] = $this->input->post('name');
$data['mname'] = $this->input->post('mname');
$data['lastname'] = $this->input->post('lastname');
$data['birthday'] = $this->input->post('birthday');
$data['sex'] = $this->input->post('sex');
$data['address'] = $this->input->post('address');
$data['phone'] = $this->input->post('phone');
$data['email'] = $this->input->post('email');
$data['password'] = md5($this->input->post('password'));
$data['father_name'] = $this->input->post('father_name');
$data['mother_name'] = $this->input->post('mother_name');
$data['class_id'] = $this->input->post('class_id');
$data['roll'] = $this->input->post('roll');
$this->db->where('student_id', $param3);
$this->db->update('student', $data);
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/student_image/' . $param3 . '.jpg');
$this->crud_model->clear_cache();
$this->session->set_flashdata('flash_message', get_phrase('edit_student_success'));
redirect(base_url() . 'index.php?admin/student/' . $param1, 'refresh');
} else if ($param2 == 'edit') {
$page_data['edit_data'] = $this->db->get_where('student', array(
'student_id' => $param3
))->result_array();
} else if ($param2 == 'personal_profile') {
$page_data['personal_profile'] = true;
$page_data['current_student_id'] = $param3;
} else if ($param2 == 'academic_result') {
$page_data['academic_result'] = true;
$page_data['current_student_id'] = $param3;
}
I m trying to save popup windows data in to database.but its throw error when i m trying pass data in queryString.Its just write "error".I dont know why its not call the update_clientstatus.php
Javscript :
function SaveNotes()
{
var notecontent = $("#txtPopNotes").val();
lookup(notecontent, globalNoteId);
overlay.appendTo(document.body).remove();
return false;
}
function lookup(inputstr, eleid) {
var inputString = inputstr;
// var row = parseFloat(eleId.substring(eleId.indexOf('_') + 1))+1;
var noteId = '#noteContent_' + eleid;
var editLinkId = '#editlink_' + eleid;
var saveLinkId = '#savelink_' + eleid;
var cancelLinkId = '#cancellink_' + eleid;
var txtBoxId = '#txt_' + eleid;
// var eleId = ele.id;
$.post("update_clientstatus.php", {queryString: ""+inputString+"", id: ""+eleid+"" }, function(data){
if(data=="success") {
alert("Status updated successfully");
$('.popup').hide();
var noteId = '#noteContent_' + globalNoteId;
$(noteId).html(inputstr);
$('.message').html('Status Updated successfully');
}
else
{
**document.write('error');**
}
});
} // lookup
PHP code(update_clientstatus.php)
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
}
try this
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
if ($query ) {
echo "success";
} else {
echo "error";
}
} else {
echo "error";
}