Can't upload multiple image using Ajax with codeigniter - javascript

Wana to upload multiple image with the help of Ajax in codeigniter but got some error while calling the function upload_business_photo_do() please help
thanks in advance....
<input type="button" id="uploadBusinessImg" value="Upload">
Ajax Code:- here i call ajax via id="uploadBusinessImg"
<script>
$("#uploadBusinessImg").on("click",function(e)
{
var total_img=$("#txtBusinessImage").get(0).files.length;
if(total_img<=5)
{
var f_size=0;
var f_size_1=0;
var f_type_1="" ,validFileName="",InValidFileName="";
var chkFileValid=true;
for(var i=0; i<=total_img-1; i++)
{
var f_name=$("#txtBusinessImage").get(0).files.item(i).name;
var f_size=$("#txtBusinessImage").get(0).files.item(i).size;
var f_type=f_name.split('.').pop();
//alert(f_type);
var valid_extensions = /(\.jpg|\.jpeg|\.png)$/i;
if(valid_extensions.test(f_name))
{
if(validFileName=="")
validFileName =f_name;
else
validFileName+=","+f_name;
}
else
{ InValidFileName=f_name;
chkFileValid=false;
break;
}
var newFileSize=parseInt(f_size);
f_size_1=parseInt(f_size_1)+parseInt(newFileSize);
}
var totalFileSize=f_size_1;
//alert(totalFileSize);
if(totalFileSize<=1572864 && chkFileValid==true)
{
//alert("allow");
alert(validFileName);
var businessIMAGE=validFileName;
$.ajax({
type:"POST",
url:"<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>",
mimeType:"multipart/form-data",
uploadMultiple: true,
data:{reciveBusinessImg:businessIMAGE},
success: function(reviceUploadImgMsg)
{
alert(reviceUploadImgMsg);
}
});
}
else
{
if(chkFileValid==false)
alert("InValidFileName"+InValidFileName);
else
alert("Image size should be less then 1.5 MB");
}
}
else
{
alert("Not Allow");
}
});
</script>
This is Controller Code:-
function upload_business_photo_do()
{
$reciveBusinessImgName=$this->input->post('reciveBusinessImg');
$newArray=explode(",",$reciveBusinessImgName);
/*code for image*/
$config['upload_path']='./company_image/';
$config['allowed_types']= 'jpg|png|jpeg';
$config['max_width'] = '6000';
$config['max_height'] = '4500';
$this->load->library('upload',$config);
for($i=0; $i<count($newArray); $i++)
{
$_FILES['userfile']['name']= $_FILES['txtBusinessImage']['name'][$i];
$_FILES['userfile']['type']= $_FILES['txtBusinessImage']['type'][$i];
$_FILES['userfile']['tmp_name']= $_FILES['txtBusinessImage']['tmp_name'][$i];
$_FILES['userfile']['error']= $_FILES['txtBusinessImage']['error'][$i];
$_FILES['userfile']['size']= $_FILES['txtBusinessImage']['size'][$i];
if(! $this->upload->do_upload())
{
/*----set flash message*/
echo "error";
}
else
{
$upload_data = $this->upload->data();
echo "done";
}
}
}

Related

How do I stop others from post requesting my php

I have a page called index.php. This contains a form which the user submits. Upon submission, it verifies the input from verify-input.php and returns some key information back to index.php. From there, index.php post requests scanner.php ~100 times. This is all done without refreshing index.php.
My question is, how do I stop other websites or other people from post requesting verify-input.php and scanner.php? I only want people to be able to call these files on my website (essentially, I don't want others using my verify-input.php and scanner.php API's for their own gain.
I've added the code below for these files, but I don't think it matters too much. I'm fairly good in PHP but I am terrible at javascript.
index.php
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<div class="display-error" style="display: none"></div>
<form>
<label for="fname">Fruit (only correct input is: banana)</label><br>
<input type="text" id="fruit-name" name="fruit" value="banana"><br>
<button type="submit" id="submit" value="Submit">Submit</button>
</form>
<div id="results">
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$("#submit").attr("disabled", true);
$("#submit").html("Verifying Username");
var fruitName = $("#fruit-name").val();
$.ajax({
type: "POST",
url: "verify-input.php",
dataType: "json",
data: {
fruitName: fruitName
},
success: function(data) {
if (data.code == 200) {
$("#submit").html("Running Scan");
(async function() {
var fruitID = data.fruitId;
var min = 1;
while (min < 60) {
await scan(fruitID, min, min + 30);
min = min + 30;
}
$("#submit").html("Submit");
$("#submit").attr("disabled", false);
})();
} else {
$("#submit").html("Submit");
$("#submit").attr("disabled", false);
$(".display-error").html("<ul>" + data.msg + "</ul>");
$(".display-error").css("display", "block");
}
}
});
});
});
function scan(vFruitId, min, max) {
return $.ajax({
type: "POST",
url: "scanner.php",
dataType: "json",
data: {
vFruitId: vFruitId,
min: min,
max: max
},
success: function(data) {
data.forEach((item, idx) => {
$("#results").append(`
<div class="fruit-item" data-item="${idx}">
<div class="f-calories">calories: ${item.sweetness}</div>
<div class="f-sweetness">sweeteness: ${item.calories}</div>
<div class="f-bitterness">bitterness: ${item.bitterness}</div>
</div><br>
`);
})
}
});
}
</script>
verify-input.php
<?php
if (isset($_POST['fruitName'])) {
echo(is_valid($_POST['fruitName']));
}
function is_valid($fruit) {
// Verify post data is valid and correct
$names = ['Banana cake', 'Banana pancake', 'Banana bread'];
$colors = ['Yellow', 'Blue', 'Green', 'Purple', 'Black'];
sleep(2);
if ($fruit == "banana") {
$result['code'] = 200;
$result['fruitId'] = rand(1, 9999999);
$result['msg'] = "YAY SUCCESS";
$json = json_encode($result);
return $json;
}
$result['code'] = 400;
$result['msg'] = "ERROR! The correct fruit is banana";
$json = json_encode($result);
return $json;
}
scanner.php
<?php
ini_set('max_execution_time', '300');
define('MAX_SCAN', 30);
if (isset($_POST['vFruitId']) &&
isset($_POST['min']) &&
isset($_POST['max'])) {
$result = roomscanner($_POST['vFruitId'], $_POST['min'], $_POST['max']);
$json = json_encode($result);
file_put_contents("result.txt", $json);
echo($json);
}
function roomscanner($fruitId, $min, $max) {
$result = [];
$i = $min;
while ($i < $max) {
if ($i % 3 == 0) {
$curr['sweetness'] = rand(20, 29);
$curr['calories'] = rand(30, 39);
$curr['bitterness'] = rand(30, 39);
$result[] = $curr;
}
sleep(rand(0, 1));
$i++;
}
return $result;
}

AJAX keep showing wrong data from array

I have a loop that calls multiples AJAX to find out if there's any booking in the database or not. JS will pass the data from an array to AJAX and find it out in database through SQL query.
However, the data returned from the AJAX is correct, and if it's there in database, i want to to show the data returned from AJAX and the current value of array in current loop, but still the data that i show from the array is the last index of array.
javascript :
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
for (var j = 0; j < lap.length; j++){
for (var i = 0;i < jam.length; i++){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
}
return false;
}
PHP File:
<?php
ob_start();
$error=""; // Variable To Store Error Message
$connection = mysqli_connect(/*credential*/);
$tgl = $_POST['date'];
$time = $_POST['time'];
$lap = $_POST['lapangan'];
//Query
$query = mysqli_query($connection, "SELECT * FROM lapangan_book WHERE tanggal='$tgl' and jam='$time' and lapangan='$lap'");
$rows = mysqli_num_rows($query);
$data = mysqli_fetch_array($query);
if($rows > 0){
echo $data['lapangan'];
}else{
echo "0";
}
?>
The output should be
Lapangan A
22lapA
22Lapangan A
But keep showing
Lapangan A
22lapBat
22Lapangan Batminton
Yes, this is happening because of the Asyncroniouse behavior of ajax. There is two tricks you have to send asynchronous request by async: false or you have to call the recursive function after success response from ajax request.
Trick 1- Pass option aysnc: false in ajax request, but some browser will throws warning in synchronous request of ajax
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
Trick 2: Recursive function, this is most accurate way of calling
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
var i=0;
var j=0;
var ajaxCall= function(){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
var recursiveCall=true;
i=i+1;
if(i>=jam.length){
j=j+1;
if(j>=lap.length) recursiveCall= false;
else i=0;
}
if(recursiveCall===true)
{
ajaxCall();
}
},
error: function () {
$('#output').html('ERROR!');
},
});
}
ajaxCall();
return false;
}
I have written code for your understanding might be your have to made come modification in this code

Unable to see the source of the problem with the code for sending data to PHP file

I am very sorry to appear much ignorant but I have experienced this problem for long and I am now completely unable to understand why my JQuery function is not working.
I need this code to send data to PHP file which I am sure its working. I have tried to code everything with php but I have found there are place that I will have to include ajax.
$(document).ready(function(){
$('#sending').on('submit', function(event){
event.preventDefault();
if(($('#receiver_id1').val() == '0') && ($('#receiver_id2').val() == '0') && ($('#receiver_id3').val() == '0'))
{
alert("Please fill in the recipient!");
return false;
}
else if($.trim($("#message").val()) == '')
{
alert("You cannot send an empty message.");
return false;
}
else if($('#subject').val() == '')
{
var retVal = confirm("Are you sure to send a message without a subject?");
if( retVal == true ) {
var receiver_id1 = $('#receiver_id1').val();
var receiver_id2 = $('#receiver_id2').val();
var receiver_id3 = $('#receiver_id3').val();
var receiver_name1 = $('#receiver_id1').text();
var receiver_name2 = $('#receiver_id2').text();
var receiver_name3 = $('#receiver_id3').text();
var from_user_name = '<?php echo $from_user_name;?>';
var from_user_id = '<?php echo $from_user_id;?>';
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url:"messaging.php",
type:"POST",
data:{receiver_id1:receiver_id1, receiver_id2:receiver_id2, receiver_id3:receiver_id3, receiver_name1:receiver_name1, receiver_name2:receiver_name2, receiver_name3:receiver_name3, subject:subject, message:message},
success:function(data)
{
$('#receiver_id1').val("0");
$('#receiver_id2').val("0");
$('#receiver_id3').val("0");
$('#subject').val("");
$('#message').val("");
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
type:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#popup').modal("show");
}
});
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
} else {
return false;
}
} else
{
var receiver_id1 = $('#receiver_id1').val();
var receiver_id2 = $('#receiver_id2').val();
var receiver_id3 = $('#receiver_id3').val();
var receiver_name1 = $('#receiver_id1').text();
var receiver_name2 = $('#receiver_id2').text();
var receiver_name3 = $('#receiver_id3').text();
var from_user_name = '<?php echo $from_user_name;?>';
var from_user_id = '<?php echo $from_user_id;?>';
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url:"messaging.php",
type:"POST",
data:{receiver_id1:receiver_id1, receiver_id2:receiver_id2, receiver_id3:receiver_id3, receiver_name1:receiver_name1, receiver_name2:receiver_name2, receiver_name3:receiver_name3, from_user_name:from_user_name, from_user_id:from_user_id, subject:subject, message:message},
success:function(data)
{
$('#receiver_id1').val("0");
$('#receiver_id2').val("0");
$('#receiver_id3').val("0");
$('#subject').val("");
$('#message').val("");
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
method:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#popup').modal("show");
}
});
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
}
});
});
I really need help. I absolutely need this script to work. Thanks in advance.

Js on click triggers a php update, it also triggers on load

this works for me on delete button, but this works when I go to this page also, on load of page it triggers status update i dont want that to change unless i click delete
Is it because it is php inside js or what?
var deleted_question = 0;
$(document).on("click", "button[id=removequestion]", function(data) {
var total_question_nr = <?php echo count($questions);?>;
var test_status = <?php echo $test->status; ?>;
if (test_status == 1) {
if ((total_question_nr - deleted_question) == 1) {
var result = confirm("#lang('general.if_questions_zero_test')");
console.log(total_question_nr - deleted_question);
if ((total_question_nr - deleted_question) == 0) {
var status = <?php echo $test->update(['status' => 0]); ?>;
}
} else {
var result = confirm("#lang('general.are_you_sure_want_to_delete_question')?");
}
} else {
var result = confirm("#lang('general.are_you_sure_want_to_delete_question')?");
}
if (result) {
var questionid = $(this).val();
$.ajax({
method: "POST",
url: "{{ url('/questions/delete-question') }}",
data: {
_token: "{{ csrf_token() }}",
question_id: questionid,
},
success: function(response) {
$("button[id=removequestion][value=" + questionid + "]").parent().parent().fadeOut('slow');
deleted_question++;
if ((total_question_nr - deleted_question) == 0) {
$('#publish-col').find('a').each(function() {
$(this).addClass("disabled");
});
}
},
error: function() {
console.log("error");
}
});
}
});

commands in chatroom & defining words after command

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.

Categories

Resources