i am trying to pass a path to a php script and the script is supposed to then return all image files in that path in a array but all i keep getting is undefined error, can someone help please.
function LoadGallery(dir_path) {
$.ajax({
type: 'POST',
url: "getimages.php",
traditional: true,
data:{ path : dir_path},
type: "json",
success: function(data){
alert(data[0]);
// $("#image-container").val(data[0]);
}
});
}
PHP SCRIPT getimages:
<?php
if(isset($_POST['path'])){
$dir = $_POST['path'];
$img = array();
if (is_dir($dir)) {
if ($hnd = opendir($dir)) {
while (false !== ($file = readdir($hnd))) {
if ($file != "." && $file != "..") {
$img[] = $file;
}
}
closedir($hnd);
}
}
return $img;
}
?>
change your php code to return json with result.
<?php
if(isset($_POST['path'])){
$dir = $_POST['path'];
$img = array();
if (is_dir($dir)) {
if ($hnd = opendir($dir)) {
while (false !== ($file = readdir($hnd))) {
if ($file != "." && $file != "..") {
$img[] = $file;
}
}
closedir($hnd);
}
}
echo json_encode($img);
}
?>
Related
I want to list the files in "archives/" and write the decoded array to disk (file name = "archives/events.txt") But what I have doesn't create that file.
xhr.send(data); // gives: Uncaught ReferenceError: data is not defined
What am I doing wrong?
function LISTevents () {
var xhr = new XMLHttpRequest();
xhr.open("POST", "json-events.php");
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
}
json-events.php
<?php
// create list of events files in archives/* on server
$files1 = scandir('archives');
file_put_contents('archives/events.txt', print_r($files1, true));
?>
<?php
function list_contents($dir, $suffix) {
$contents = array();
$dir = realpath($dir);
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..' && $file != 'events.txt') {
if (substr($file, -strlen($suffix)) == $suffix) {
$contents[] = $file;
}
}
}
foreach ($contents as $key => $item) {
if (strlen($item) != 14) {
unset($contents[$key]);}
}
foreach ($contents as $key => $item) {
if (substr($item,0,1) != "2") {
unset($contents[$key]);}
}
}
$contents_json = json_encode($contents);
file_put_contents($dir . '/events.txt', $contents_json);
}
list_contents('archives','.txt');
?>
I have a script for uploading images, it works fine but I would like to limit the image size to a maximum of 2 mb, I have tried a few things but without success, I am not one of the best at this so I would be very grateful for some help, follow the code
$(document).ready(function(){
$("#but_upload_w").click(function(){
var fd = new FormData();
var files = $('#file_w')[0].files;
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'host/profile/upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#up-01").attr("value",response);
$("input").show(); // Link img
}else{
alert('failed');
}
},
});
}else{
alert("select");
}
});
});
<?php
if(isset($_FILES['file']['name'])){
$filename = $_FILES['file']['name'];
$location = "upload/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
if(in_array(strtolower($imageFileType), $valid_extensions)) {
if(move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$newfilename)){
$response = "host/profile/upload/".$newfilename;
}
}
echo $response;
exit;
}
echo 0; ?>
if(isset($_FILES['uploaded_file'])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES['uploaded_file']['type'], $acceptable)) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) === 0) {
move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die(); //Ensure no more processing is done
}
}
Look into the docs for move_uploaded_file() for more information.
So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else{
}
if (email == ""){
$("input#youremail").focus;
return false;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
//qis_process_application in register.php
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});
I have an AJAX file upload code in codeigniter. The Issue is that I changed the simple form submit to file submit. But After that, JQUERY has stopped working. The response is coming success, but at the same time, ajax error function is called. I don't know what's wrong with my code.
This is my controller.
public function ajax_add() {
$this->_validate();
$config = [
'upload_path' => './assets/game_images/',
'allowed_types' => 'gif|png|jpg|jpeg'
];
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
$file = $this->upload->data();
$file_name = $file['file_name'];
if ($file_name == '') {
$data['error_string'][] = 'Please upload an image.';
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
} else {
$data['inputerror'][] = 'image';
$data['error_string'][] = $this->upload->display_errors();
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id'),
//'image' => $file_name
);
$insert = $this->game->save($data);
echo json_encode(array("status" => TRUE));
}
private function _validate() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if ($this->input->post('title') == '') {
$data['inputerror'][] = 'title';
$data['error_string'][] = 'Game Title is required';
$data['status'] = FALSE;
}
if ($this->input->post('iframe') == '') {
$data['inputerror'][] = 'iframe';
$data['error_string'][] = 'Game Iframe is required';
$data['status'] = FALSE;
}
if ($this->input->post('status') == '') {
$data['inputerror'][] = 'status';
$data['error_string'][] = 'Status is required';
$data['status'] = FALSE;
}
if ($this->input->post('category_id') == '') {
$data['inputerror'][] = 'category_id';
$data['error_string'][] = 'Please select category';
$data['status'] = FALSE;
}
if ($data['status'] === FALSE) {
echo json_encode($data);
exit();
}
}
And this is my HTML
if (save_method == 'add') {
url = "<?php echo site_url('game/ajax_add') ?>";
} else {
url = "<?php echo site_url('game/ajax_update') ?>";
}
var formData = new FormData($('#form')[0]);
$.ajax({
url: url,
type: 'JSON',
data: formData,
async: false,
success: function (data)
{
if (data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
cache: false,
contentType: false,
processData: false
});
$.ajax({
type: 'POST',
url: url,
dataType: 'JSON',
contentType: 'application/json; charset=utf-8'
})
Okay basically I'm trying to have a action happen of alert('hi $message'); when a user enters the command /command lewis into the chatroom; In the alert I have stated the variable $message and this is the word followed by the command; for example /command $message. I have posted my script below; so basically what I'm trying to achieve is recognise when a user types /command followed by a $message into the textarea then perform an action.
Chatroom Javascript
name ='<? echo $chat_room_username; ?>';
$("#name-area").html("You are: <span>" + name + "</span>");
var chat = new Chat();
$(function() {
chat.getState();
// watch textarea for key presses
$("#sendie").keydown(function(event) {
var key = event.which;
//all keys including return.
if (key >= 33) {
var maxLength = $(this).attr("maxlength");
var length = this.value.length;
// don't allow new content if length is maxed out
if (length >= maxLength) {
event.preventDefault();
}
}
});
// watch textarea for release of key press
$('#sendie').keyup(function(e) {
if (e.keyCode == 13) {
var text = $(this).val();
var maxLength = $(this).attr("maxlength");
var length = text.length;
// send
if (length <= maxLength + 1) {
chat.send(text, name);
$(this).val("");
} else {
$(this).val(text.substring(0, maxLength));
}
}
});
});
var instanse = false;
var state;
var mes;
var file;
function Chat () {
this.update = updateChat;
this.send = sendChat;
this.getState = getStateOfChat;
}
//gets the state of the chat
function getStateOfChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'getState',
'file': file
},
dataType: "json",
success: function(data){
state = data.state;
instanse = false;
},
});
}
}
//Updates the chat
function updateChat(){
if(!instanse){
instanse = true;
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'update',
'state': state,
'file': file
},
dataType: "json",
success: function(data){
if(data.text){
for (var i = 0; i < data.text.length; i++) {
var newdata = data.text[i].replace(/:brand/g,"<img src=\"/_img/logo1.png\"></img>");
newdata = newdata.replace(/:tipsound/g,"<audio autoplay><source src=\"/tip.wav\" type=\"audio/mpeg\"></audio>");
<?
$select_gifs = mysql_query("SELECT * FROM `submited_chatroom_gifs` WHERE `staff` = '1'");
while($gif = mysql_fetch_array($select_gifs)){
?>
newdata = newdata.replace(/:<? echo $gif['name']; ?>/g,"<img data-toggle=\"tooltip\" height=\"<? echo $gif['height']; ?>\" width=\"<? echo $gif['width']; ?>\"title=\":<? echo $gif['name']; ?>\" src=\"/_img/gifs/<? echo $gif['img']; ?>\"></img>");
<? } ?>
$('#chat-area').append($("<p>"+ newdata +"</p>"));
}
}
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
instanse = false;
state = data.state;
},
});
}
else {
setTimeout(updateChat, 1500);
}
}
//send the message
function sendChat(message, nickname)
{
updateChat();
$.ajax({
type: "POST",
url: "/rooms/process.php?room=<? echo $room; ?>",
data: {
'function': 'send',
'message': message,
'nickname': nickname,
'file': file
},
dataType: "json",
success: function(data){
updateChat();
},
});
}
process.php
<?php
$function = $_POST['function'];
$room = $_GET['room'];
$log = array();
switch($function) {
case('getState'):
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$log['state'] = count($lines);
break;
case('update'):
$state = $_POST['state'];
if(file_exists($room . '.txt')){
$lines = file($room . '.txt');
}
$count = count($lines);
if($state == $count){
$log['state'] = $state;
$log['text'] = false;
}
else{
$text= array();
$log['state'] = $state + count($lines) - $state;
foreach ($lines as $line_num => $line)
{
if($line_num >= $state){
$text[] = $line = str_replace("\n", "", $line);
}
}
$log['text'] = $text;
}
break;
case('send'):
$nickname = $_POST['nickname'];
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$message = htmlentities(strip_tags($_POST['message']));
if(($message) != "\n"){
if(preg_match($reg_exUrl, $message, $url)) {
$message = preg_replace($reg_exUrl, ''.$url[0].'', $message);
}
fwrite(fopen($room . '.txt', 'a'), "<p><font size=\"2px\">". $nickname . ": " . $message = str_replace("\n", " ", $message) . "</font></p>\n");
}
break;
}
echo json_encode($log);
}
?>
the alert is only for the person who wrote the command in
Thankyou for any help, and I apologise for the lengthy question.
[edit] Sorry just re-read my question and I will just try and explain what I'm trying to achieve in abit more detail. So basically when a user inputs /command lewis the script would then perform an alert('Hi Lewis');. But then if a user was to enter /command john the alert would be alert('Hi John');.
The alert would be instead of posting the message to the chatroom.