Codeigniter jquery not working inside AJAX file upload - javascript

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'
})

Related

Limit image upload size

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.

I can't redirect user after login

I have login page which take username and password from user after user will be login. I am getting response for successfully login. but I can not redirect to index.php.
I am getting console message that User successfully login, But then page is not redirect on other page.
My JS file is like this.
$(document).ready(function() {
//alert('ss');
$("#login-form").submit(function(e){
e.preventDefault();
var username = $("#email").val();
var password = $("#password").val();
var isValid = true;
var re = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!re.test($("#email").val())){
isValid = false;
$("#message").html("Please enter valid email.");
}
if($('#remember').is(':checked')){
$.cookie('adminCookie', $("#loginUser").val(), { expires: 7 });
}
else{
if($.cookie('adminCookie') == null) {
$.removeCookie("adminCookie");
}
}
if(password == ""){
isValid = false;
$("#message").html("Please enter password.");
}
if(isValid){
$.ajax({
type : "POST",
url : "process/login.php?rand="+Math.random(),
data : {
username : $("#email").val(),
password : $("#password").val(),
}
}).
done(function(response){
//alert(response);
var JSONArray = $.parseJSON(rawJSON);
console.log(response);
if(jsonObj.success=="1"){
window.location("index.php");
}else{
$("#userDiv").addClass("form-group has-error");
$("#passDiv").addClass("form-group has-error");
$("#passWarning").css("display","");
$("#passWarning").html("Invalid User Name or Password");
$.when($('#passWarning').fadeOut(5000)).done(function() {
$("#userDiv").attr('class', 'form-group');
$("#passDiv").attr('class', 'form-group');
});
}
}).fail(function(){
}).always(function() {
});
}
});
});
my PHP file is looks like this.
<?php
include "../connection.php";
extract($_POST);
$data = array();
$resArr = array();
if (isset($_POST['username']) && isset($_POST['password'])) {
$check_user = mysqli_query($conn, "select * from cut_users where email like '$username' and password like '$password' and user_role like 'A'");
if ($check_user) {
if (mysqli_num_rows($check_user) > 0) {
$message = "Login successfully.";
$success = 1;
while ($row = mysqli_fetch_array($check_user)) {
if ($row['is_active'] == "0") {
$message = "Your account is blocked. Please contact admin.";
$success = 0;
}
$data["id"] = $row['cut_users_id'];
$data["name"] = $row['name'];
$data["emailID"] = $row['email'];
$data["device"] = $row['device_type'];
$data["is_reset"] = $row['is_reset'];
$_SESSION['userID'] = $row['cut_users_id'];
$_SESSION['name'] = $row['name'];
$_SESSION['emailID'] = $row['email'];
}
$resArr = array("success" => $success, "data" => $data, "message" => $message);
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Email or password invalid.");
}
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Something went wrong!!!" . mysqli_error($conn));
}
} else {
$resArr = array("success" => 0, "data" => array(), "message" => "Parameter Missing");
}
header('Content-Type: application/json');
echo str_replace("\/", "/", json_encode($resArr, JSON_UNESCAPED_UNICODE));
?>
1) Why you are using variable jsonObj instead of response ?
2) Modify your if statement like this
if(response.success==1){
window.location.href="index.php";
}
window.location is not a function it is an object. Please change href property in window.location object to redirect to new url.
window.location.href = "./index.php";
Simple redirect to specific file
if(jsonObj.success==1)
{
window.location.href = "http://www.example.com/index.php";
}

How to show bootstrap success message in ajax success method ()?

I am using following jQuery/Ajax method to validate a form. I am passing json data to the php file called add.php. Now If add.php page find any error its showing error message otherwise it's showing success message.
Now, In ajax success method I want to show bootstrap success message class if there is no error otherwise a error message class.
To this line :
$('#form_result').append('<p class="alert alert-danger">'+value+'</p>');
Now I can't determine how to check if the result is success.
Jquery/Ajax Code :
<script type="text/javascript">
$(document).ready(function() {
$("#add_zone").submit(function(e) {
e.preventDefault();
$.ajax({
url : 'add',
data : $(this).serialize(),
dataType : 'json',
type : 'POST',
beforeSend : function () {
$("#submit_button").val("Wait...");
},
success : function ( result ) {
$("#submit_button").val("Add New Zone");
$('#form_result').html('');
$.each( result, function( key, value ) {
if(key !== 'error') {
$('#form_result').append('<p class="alert alert-danger">'+value+'</p>');
}
});
},
});
});
});
</script>
add.php page
if(isset($_POST['form_name']) && $_POST['form_name'] == "zone") {
if(verifyForm('zone', 'add')) {
$msg = array();
$msg['error'] = false;
$zone_name = validate_data($_POST['zone_name']);
$remark = validate_data($_POST['remark']);
$errors = array();
$check = mysqli_query($conn, "SELECT zone_name FROM zone WHERE uid ='$uid' AND zone_name = '$zone_name' ");
$num_check = mysqli_num_rows($check);
if(isset($zone_name, $remark)) {
if(empty($zone_name)) {
$msg[] = 'Zone name required';
$msg['error'] = true;
} elseif($num_check > 0 ) {
$msg[] = 'Zone name already exists, choose another name';
$msg['error'] = true;
}
if(!empty($errors)) {
$msg[] = '<div class="alert alert-danger">';
$msg[] = '<strong>OPPS! Correct the following error(s):</strong><br/>';
foreach($errors as $er) {
$msg[] = $er.'.<br/>';
$msg['error'] = true;
}
$msg[] = '</div>';
}
if(empty($errors) && $msg['error'] === false) {
$insert = mysqli_query($conn, "INSERT INTO zone (zone_name, uid, remark) VALUES('$zone_name', '$uid', '$remark') ");
if($insert) {
$msg[] = 'New zone added.';
} else {
$msg[] = "Can't add new zone.";
$msg['error'] = true;
}
}
}
echo json_encode($msg);
}
}
Don't mix output with error state:
<?php
/**
*/
if(isset($_POST['form_name']) && $_POST['form_name'] == "zone") {
if(verifyForm('zone', 'add')) {
$msg = array();
$msg['error'] = false;
$msg['body'] = [];
$zone_name = validate_data($_POST['zone_name']);
$remark = validate_data($_POST['remark']);
$errors = array();
$check = mysqli_query($conn, "SELECT zone_name FROM zone WHERE uid ='$uid' AND zone_name = '$zone_name' ");
$num_check = mysqli_num_rows($check);
if(isset($zone_name, $remark)) {
if(empty($zone_name)) {
$msg['body'][] = 'Zone name required';
$msg['error'] = true;
} elseif($num_check > 0 ) {
$msg['body'][] = 'Zone name already exists, choose another name';
$msg['error'] = true;
}
if(!empty($errors)) {
$msg['body'][] = '<div class="alert alert-danger">';
$msg['body'][] = '<strong>OPPS! Correct the following error(s):</strong><br/>';
foreach($errors as $er) {
$msg['body'][] = $er.'.<br/>';
$msg['error'] = true;
}
$msg['body'][] = '</div>';
}
if(empty($errors) && $msg['error'] === false) {
$insert = mysqli_query($conn, "INSERT INTO zone (zone_name, uid, remark) VALUES('$zone_name', '$uid', '$remark') ");
if($insert) {
$msg['body'][] = 'New zone added.';
} else {
$msg['body'][] = "Can't add new zone.";
$msg['error'] = true;
}
}
}
$msg['body'] = implode('',$msg['body']);
echo json_encode($msg);
}
}
?>
<script type="text/javascript">
$(document).ready(function() {
$("#add_zone").submit(function(e) {
e.preventDefault();
$.ajax({
url : 'add',
data : $(this).serialize(),
dataType : 'json',
type : 'POST',
beforeSend : function () {
$("#submit_button").val("Wait...");
},
success : function ( result ) {
$("#submit_button").val("Add New Zone");
if (result.error) {
$('#form_result').append('<p class="alert alert-danger">'+result.body+'</p>');
}
else {
$('#form_result') . html(result.body);
}
},
});
});
});
</script>

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.

SyntaxError: Unexpected token l in ajax call

I am trying to fetch a data from the server data base and pass it to the ajax to create a database table and its data in the local android database. But when an ajax call is make it give following error.
LogCat:
01-30 10:58:45.888: D/CordovaLog(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l
01-30 10:58:45.888: I/Web Console(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l at file:///android_asset/www/home.html:513
here is the ajax code:
$.ajax({
url : urlServer + 'getTableData.php',
// type: 'POST',
contentType : 'application/json',
beforeSend : function() {
$.mobile.loading('show')
},
complete : function() {
console.log("ajax complete");
createTable();
},
dataType : 'json',
data : {userId: user_id},
success : function(data) {
if (data != null)
{
dynamic_tabledetails = data.Table_details;
dynamic_selectQuery = data.SelectTableQuery;
table_data = data;
getTabledetails(dynamic_tabledetails);
}
else
{
alert("Error Message");
}
},
error : function(xhr, ajaxOptions, thrownError) {
console.log("Server is not responding... Please try again: "+thrownError);
}
});
Here is the php code:
<?php
require_once ('connect.php');
$userID= $_REQUEST['userId'];
$data = array ();
$listtables = array();
$Tabledetails = array();
$select_table = '';
$tab_name = array();
$getlistTables = 'SHOW TABLES FROM sacpl_crm_dev ';
$resultsListTables = mysql_query($getlistTables);
echo 'length of the tables name: '.$resultsListTables.' ';
while ($row = mysql_fetch_array($resultsListTables))
{
if(strpos($row[0],'_trail') == false)
{
$temporarydata = array();
$TableName = new ArrayObject();
$getTabledetails = 'show columns from '.$row[0].'';
$resultdetails = mysql_query($getTabledetails);
$TableName['tablename'] = $row[0];
$tab_name[] =$row[0];
$column = array();
$delete_field = '';
$comp_codeField = '';
while($rows = mysql_fetch_array($resultdetails))
{
$column_list =new ArrayObject();
$column_list['FieldName'] = $rows['Field'];
$column_list['Default'] = $rows['Default'];
if(strpos($rows['Type'],'(') == false)
{
$column_list['dataType'] = $rows['Type'];
$column_list['dataType_limit'] ='';
}
else
{
$type = explode('(',$rows['Type']);
$column_list['dataType'] = $type[0];
$column_list['dataType_limit'] = '('.$type[1];
}
if($rows['Field'] == 'deleted')
{
$delete_field = 'deleted = 0';
}
if($rows['Field'] == 'userId')
{
$userIdField = $rows['Field'].'="'.$userId.'"';
}
$column_list['Extra'] = $rows['Extra'];
$column_list['Null_value'] = $rows['Null'];
$column_list['Key_value'] = $rows['Key'];
$column[] = $column_list;
}
$TableName['column_details'] = $column;
$Tabledetails[]=$TableName;
if($userIdField == '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$delete_field.'';
}
else if($userIdField != '' && $delete_field =='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.'';
}
else if($userIdField != '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.' and '.$delete_field.'';
}
else{
$select_table = 'select * from '.$row[0].'';
}
$select_query[] = $select_table;
$resultTableData = mysql_query($select_table);
while ($row1 = mysql_fetch_array($resultTableData))
{
$temporarydata[] = $row1;
}
$data[$row[0]] = $temporarydata;
}
}
$data['Table_details'] = $Tabledetails;
$data['SelectTableQuery'] = $select_query;
mysql_close($con);
require_once('JSON.php');
$json = new Services_JSON();
echo ($json->encode($data));
?>
Comment out the line:
echo 'length of the tables name: '.$resultsListTables.' ';
Also, when outputting JSON for an AJAX call, it's important to set the Content-type header using:
header('Content-type: application/json; charset=utf-8',true);
This php code doesn't seem to have syntax error. the problem probably lies on the included php's: "connect.php" and "JSON.php". could you please post them too so we can find the error.
Link this into the beginning of your PHP-file:
header("Content-Type: text/javascript; charset=utf-8");

Categories

Resources