I'm having problem to sent only one echo = 'true_user' back to jquery. Right now, the true_user will sent back to jquery based on $id that user have selected.
Second, how to combine when echo ='false' and echo ='failed' are sent back to jquery? I tried to use || and still not working.
jQuery / AJAX
<script>
jQuery(document).ready(function(){
jQuery("#delete_user").submit(function(e){
e.preventDefault();
var formData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "delete_users.php",
data: formData,
success: function(html){
if (html=='false_user'){
$.jGrowl("Please select user", { header: 'Error' });
alert(html);
}else if (html=='failed'){
$.jGrowl("Cannot delete your own account", { header: 'Account Protected' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else if(html=='true'){
$.jGrowl("Loading Please Wait......", { sticky: true });
$.jGrowl("Successfully Deleted", { header: 'User Deleted' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else if (html=='true_user'){
$.jGrowl("Loading Please Wait......", { sticky: true });
$.jGrowl("Successfully Deleted", { header: 'Users Deleted' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else if (html=='false','failed'){
$.jGrowl("Cannot delete your own account", { header: 'Account Protected' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}else{
$.jGrowl("Please try again", { header: 'Error' });
alert(html);
var delay = 1000;
setTimeout(function(){ window.location = 'admin_user.php' }, delay);
}
}//success
});
return false;
});
});
</script>
delete_users.php
<?php
error_reporting(E_ALL&~E_NOTICE);
include('dbcon.php');
include('session.php');
//if (isset($_POST['delete_user'])){
$id=$_POST['selector'];
//$id = array(61);
$N = count($id);
if ($N == 0){ //if no selected
echo 'false_user';
} else { //if selected
for($i=0; $i < $N; $i++)
{
$stmt = $conn->prepare("select * from users WHERE user_id=:id");
$stmt->bindParam(':id',$id[$i]);
$stmt->execute();
$result = $stmt->fetchObject();
$userType = $result->user_type;
//$user_type = $row['user_type']
if ($userType >= 1){ //if user type not 0 = developer
if ($id[$i] == $session_id){ // cannot delete own account
echo 'failed';
} else if($N==1){
$stmt = $conn->prepare("DELETE FROM users where user_id=:id");
$stmt->bindParam(':id',$id[$i]);
$stmt->execute();
$stmt->rowCount();
echo 'true';
} else if ($N > 1){ // if select more than one
$stmt = $conn->prepare("DELETE FROM users where user_id=:id");
$stmt->bindParam(':id',$id[$i]);
$stmt->execute();
$stmt->rowCount();
$testing = 'true_user';
//return;
}
}else{ //other error
echo 'false';
}
}
}
?>
Related
How to join two queries from the same table?
The problem is I'm not able to JOIN these 2 MySql queries properly. The 1st query is for fetching the data from the database through AJAX and the second one is for AJAX page scroll.
These work individually, but I'm not getting the required output.
Updated: I was able to join the queries through union all, but when I select the relevant cities, it doesn't run as it should and also scroll isn't working, neither I'm returning the $output at the last for 'no data'.
Thanks!
PHP Code
<?php
require'connect_mysqli.php';
if(isset($_POST["city_id"], $_POST["limit"], $_POST["start"]))
{
if($_POST["city_id"] != '') {
$sql = ("SELECT * FROM playschools_8states WHERE city_id = '".$_POST["city_id"]."' limit 0, 5
union all SELECT * FROM playschools_8states order by city_id DESC LIMIT ".$_POST["start"].", ".$_POST["limit"]."");
}
else {
$sql = "SELECT * FROM playschools_8states limit 0, 5";
}
$result = mysqli_query($link, $sql);
$output = '';
while($row = mysqli_fetch_array($result))
{
$output .= '<div class="col-md-12 module">
<div class="img-thumbnail img-responsive pull-right" style="margin:2px;"><img src="'.$row["logo"].'" /></div>
<p class="p_title_PS">'.$row["name"].'
<p class="p_state_city">'.$row["state"].', '.$row["pincode"].' </p>
<p class="p_rohit_adm"><b>School Type: </b> '.$row["schoolType"].'</p>
<p class="p_rohit_adm"><b>Co-Ed: </b> '.$row["coed"].'</p>
<p class="p_rohit_ad"><b></b> '.$row["private"].'</p></div>';
}
if ($output =='') {
echo 'Sorry! No matching results found';
}
else
echo $output;
}
?>
JavaScript
<script>
$(document).ready(function(){
$('#state').change(function(){
var state_id = $(this).val();
$.ajax({
url:"fetch_statedd.php",
method:"POST",
data:{stateId:state_id},
dataType:"text",
success:function(data)
{
$('#city').html(data);
}
});
});
});
</script>
<script>
$(document).ready(function(){
$('#city').change(function(){
var city_id = $(this).val();
$.ajax({
url:"ps_load_data.php",
method:"POST",
data:{city_id:city_id},
success:function(data){
$('#show_playschool').html(data);
}
});
});
});
</script>
<script>
$(document).ready(function(){
var limit = 7;
var start = 0;
var action = 'inactive';
function load_city_data(limit, start)
{
$.ajax({
url:"ps_load_data.php",
method:"POST",
data:{limit:limit, start:start},
cache:false,
success:function(data)
{
$('#load_data').append(data);
if(data == '')
{
$('#load_data_message').html("No Data Found");
action = 'active';
}
else
{
$('#load_data_message').html("<h4>Please wait...</h4>");
action = "inactive";
}
}
});
}
if(action == 'inactive')
{
action = 'active';
load_city_data(limit, start);
}
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
{
action = 'active';
start = start + limit;
setTimeout(function(){
load_city_data(limit, start);
}, 1000);
}
});
});
</script>
I have a script where I want to process form data using ajax. The script is returning the success message but not the error message. Have a look at the scripts below.
AJAX Script
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val()
};
$.ajax({
type: "POST",
dataType : "json",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#submit").show();
$("#loading").hide();
},3000);
}
});
return false;
});
});
PHP Script
<?php
session_start();
include'config/db.php';
$msg = null;
$sessionid = (!empty($_SESSION['login']))?$_SESSION['login']:null;
$wp = $pdo->prepare("SELECT set_cointoss_wp, set_cointoss_prob FROM settings");
$wp-> execute();
$sp = $wp->fetch();
$percent = $sp['set_cointoss_wp'];
$probablity = $sp['set_cointoss_prob'];
$bal = $pdo->prepare("SELECT mb_acbal, mb_wallet FROM mem_balance WHERE mb_id = :mem");
$bal-> bindValue(':mem', $sessionid);
$bal-> execute();
$bf = $bal->fetch();
$balance = $bf['mb_acbal'];
$wallet = $bf['mb_wallet'];
$coin = (!empty($_POST['flip']))?$_POST['flip']:null;
$amount = (!empty($_POST['amount']))?$_POST['amount']:null;
if($_POST){
if($wallet < $amount){
$msg = "<div class='message-error'>Sorry buddy! You have insufficient balance. Please <a href=''>recharge</a> your wallet.</div>";
}else{
$deduct = $wallet-$amount;
$prob = rand(1, 10);
//set new wallet balance after bet amount deduction
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_wallet = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $deduct);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
if($coin == ''){
$msg = "<div class='message-error'>Sorry buddy! Fields cannot be left empty.</div>";
}else{
if($coin == "head"){
if($prob <= $probablity){
$result = 1;
}else{
$result = 2;
}
if($result == 1){
// win
$wa = $amount*$percent;
$win_amount = $wa/100;
$final_cash = $win_amount+$balance;
// update database with winning amount
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $final_cash);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
$msg = "<div class='message-success'>Congratulations buddy! You won... <strong>$".$win_amount."</strong> has been credited to your account.</div>";
}else{
// loose
$msg = "<div class='message-error'>Sorry buddy! You lost... But do not loose hope. Try your luck again :)</div>";
}
}else{
if($prob <= $probablity){
$result = 2;
}else{
$result = 1;
}
if($result == 1){
// loose
$msg = "<div class='message-error'>Sorry buddy! You lost... But do not loose hope. Try your luck again :)</div>";
}else{
// win
$wa = $amount*$percent;
$win_amount = $wa/100;
$final_cash = $win_amount+$balance;
// update database with winning amount
$stmt = $pdo->prepare("UPDATE mem_balance SET mb_acbal = :bal WHERE mb_user = :user");
$stmt-> bindValue(':bal', $final_cash);
$stmt-> bindValue(':user', $sessionid);
$stmt-> execute();
$msg = "<div class='message-success'>Congratulations buddy! You won... <strong>$".$win_amount."</strong> has been credited to your account.</div>";
}
}
}
}
echo json_encode(array('status' => $msg, 'deduct' => $deduct));
}
?>
Here in the scripts above, when if($wallet < $amount) condition is false and else condition is executed, the scripts works fine and returns <div class='message-success'> as required. But, if if($wallet < $amount) condition is true then its not returning <div class='message-error'> and the loading image keeps on moving (as if waiting for the response) but does not receives any response in return. I am stuck since a few days on this but not being able to find any solution for the same. Please help.
I am not sure but I think in your php script $deduct has been declared inside the else block.
so when the script executes and if ($wallet < $amount) condition evaluates to true, then the else part is skipped and you directly return this:-
return echo json_encode(array(
'status' => $msg,
'deduct' => $deduct
));
so it might be the case that $deduct is not recognized. try executing by declaring the $deduct before the if block.
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.
I have been trying check email availibity using ajax and jquery script as follows,
my controller:
$get_result = $this->user->check_email_availablity();
if($get_result == FALSE ) {
$validate['message'] = '<p>Email is not available.</p>';
} else {
$validate['message'] = '<p>Email is available.</p>';
}
$this->load->view('user/signup', $validate);
my model:
function check_email_availablity() {
$email = $this->input->post('u_email');
$query = $this->db->query('SELECT u_email FROM tbl_users where u_email = "'.$email.'"');
if($query->num_rows() === 1) {
return FALSE;
} else {
return TRUE;
}
}
my js:
$(document).ready(function() {
/// make loader hidden in start
$('#Loading').hide();
$('#email').blur(function(){
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
// check if email is valid
if(filter.test(a)){
// show loader
$('#Loading').show();
$.post("<?php echo base_url()?>main/signup", {
email: $('#email').val()
},
function(response){
//#emailInfo is a span which will show you message
$('#Loading').hide();
setTimeout("finishAjax('Loading', '"+escape(response)+"')", 400);
});
return false;
}
});
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
});
my view:
<?php echo form_input('u_email', set_value('u_email'), 'class="form-control" id="email"'); ?>
<span id="Loading"><?php echo $message; ?></span>
My problem is model always returns TRUE and shows 'email is available' message, how do I check the email availability live
In your model change the if condition in query row:
function check_email_availablity() {
$email = $this->input->post('u_email');
$query = $this->db->query('SELECT u_email FROM tbl_users where u_email = "'.$email.'"');
if($query->num_rows() > 0) {
return FALSE;
} else {
return TRUE;
}
}
And in your controller:
$get_result = $this->user->check_email_availablity();
if(!$get_result) //if email already exist in your database
{
$validate['message'] = '<p>Email is not available.</p>';
} else {
$validate['message'] = '<p>Email is available.</p>';
}
$this->load->view('user/signup', $validate);