change userlevel on button click in codeigniter - php

I am trying to update userlevel when click on button. i have a page where it will display all users there i have change level button.by default every user will be in normal level(means 3) so when i click on a button it has to change to 5(lead
) and if i click again it has to change to 9(admin)
here is my view page code:
<div class="col-md-4">
<form method="post" class="change_userlevel" action="" onclick="getConfirmation(9);">
<input type="hidden" name="id" value="<?php echo $user->id; ?>">
<button type="submit" class="widget-icon" name="login"><span class='icon-arrow-up'></span></button>
</form>
</div>
<td>
<?php
if($usertype==9)
{
echo 'Admin';
}
elseif($usertype==5)
{
echo 'Teamlead';
}
else
{
echo 'Normal';
}
?>
</td>
Here is my script code with ajax:
<script type='text/javascript'>
function getConfirmation(id){
$.ajax({
url: "User/change_status",
type: "post",
data: id,
success: function (response) {
location.reload();
}
});
}
</script>
Here is my controller code method change_status:
function change_status(){
$id = $this->input->post('id');
$status = $this->db->query("select userlevel from users where id=9")->row()->userlevel;
if($status==3){
$status = 5;
} else {
$status = 9;
}
$data=array('userlevel'=>$status);
$this->db->where('id','id');
$this->db->update('users',$data);
}
I dont know where i have done mistake it is not working.
can anyone help me how to solve this.
Thanks in advance.

Hope this will help you :
Your ajax code should be like this :
<script type='text/javascript'>
function getConfirmation(id)
{
if (id != '')
{
$.ajax({
url: "<?=site_url('User/change_status');?>",
type: "post",
data: {'id' : id},
success: function (response) {
alert('success');
//location.reload();
}
});
}
}
</script>
Your method change_status should be like this :
function change_status()
{
$id = $this->input->post('id');
$status = $this->db->select('userlevel')->where('id', $id)->get('users')->row()->userlevel;
if($status == 3)
{
$status = 5;
} else
{
$status = 9;
}
$data = array('userlevel' => $status);
$this->db->where('id', $id);
$this->db->update('users',$data);
echo TRUE;exit;
}

Related

How to show error message when the values was not in mysql database?

I have fetch(placing in inputboxes) the customer name and Dob from database through Customer phone . I am done the work but if I put the wrong customer number(there is no number in database) there will be show a alert box...that didn't know to me for how to do that...Can you please anyone solve my code...
<input type="text" class="search">phone
<input type="text" id="cname">name
<input type="text" id="cdob">date of birth
This is the script tag
<script>
$(document).ready(function() {
$('.search').keyup(function() {
var mobile_no = $(this).val();
$.ajax({
url: "get_customer_info.php",
method: "POST",
dataType: "json",
data:{
search : mobile_no
},
success:function(data){
$.each(data,function(id, val){
$("#cname").val(val.cname);
$("#cdob").val(val.cdob);
});
}
});
});
});
</script>
and this is query page
<?php
include("config.php");
$mobile=$_POST['search'];
$sql="SELECT * FROM `cm` WHERE cphone ='$mobile'";
$result = mysqli_query($conn,$sql,true);
if($result===true)
{
$mainarray=array();
while($row=$result->fetch_assoc())
{
$row['cm_id'];
$row['cname'];
$row['cdob'];
array_push($mainarray, $row);
}
echo json_encode($mainarray);
}
else
{
echo 'There is no data';
}
?>
Front end file:
<input type="text" class="search">phone
<input type="text" id="cname">name
<input type="text" id="cdob">date of birth
Your Script file:
<script>
$(document).ready(function() {
$('.search').keyup(function() {
var mobile_no = $(this).val();
if(mobile_no.length >= 10 ){
$.ajax({
url: "get_customer_info.php",
method: "POST",
dataType: "json",
data:{
search : mobile_no
},
success:function(responce){
if($.trim(responce)){
$.each(responce,function(id, val){
$("#cname").val(val.cname);
$("#cdob").val(val.cdob);
});
} else{
alert("no data");
}
}
});
}
});
});
</script>
This is your get_customer_info.php file
<?php
include("config.php");
$mobile=$_POST['search'];
$sql="SELECT * FROM `cm` WHERE cphone ='$mobile'";
$result = mysqli_query($conn,$sql,true);
if($result==true)
{
$mainarray=array();
while($row=$result->fetch_assoc())
{
$row['cm_id'];
$row['cname'];
$row['cdob'];
array_push($mainarray, $row);
}
echo json_encode($mainarray);
}
else
{
echo 'There is no data';
}
?>

How to return output on the same page ajax php

I want to organize the selection query from index.php to action, so i can be able to call the file with ajax to show the data on the page.(index.php). So, the activity I want to do is to able to submit data of the form to the database and to display result on the same page(index.php) without refreshing the page. Help please
Here's my files
1.action.php
2.index.php
3.maker.js
//-----------------------action.php-----------------------------
<?php
include ("db_connect.php"); // Connecting to the database
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$action = $_REQUEST['action'];
if ($action=="add")
{
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
?>
//index.php
<div id="table_content"></div>
<script type="text/javascript" src="maker.js">
<?php
function ShowForm($AnswerCommentId)
{ ?>
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerCommentId);?>"/>
<button type='button' OnClick=SendComment()>Comment</button>
</form>
<?php
}
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
function tree($treeArray, $level, $pid = 0)
{
global $AnswerId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
?>
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60);?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) { echo 'Reply'; }
echo 'Delete';
?> </div> <?php
if ($AnswerId == $item[0])
{
?><div id="InnerDiv"><?php ShowForm($AnswerId); ?></div>
<?php
}
?> </div> <?php
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable, 0);
?>
//maker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
clean_form();
}
});
return false;
}
So you are basically trying to make ajax based comment system, From what i see, your code organization is not clear based on there tasks, specifically your index.php file so here is what you can do to simplify things :
your action.php should hanlde all php database releted tasks
Move your html code to some other file (Create Template)
Here is the modified code that i have come up with (This is just for your reference, you should modify this accoring to you needs, and as Xorifelse suggested in comment you should always use prepared statements in production system because of security concerns):
Action.php
<?php
include ("db_connect.php"); // Connecting to the database
$action = $_REQUEST['action'];
if ($action=="add")
{
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$text = $_REQUEST['text'];
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
if ($action=="get")
{
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
$mytable = array();
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
tree($mytable, 0, $AnswerId);
}
function tree($treeArray, $level, $ansId, $pid = 0)
{
$AnswerId = $ansId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
include('comments.template.php');
tree($treeArray, $level+1,$AnswerId, $item[0]); // Recursion
}
}
}
?>
index.php
<html>
<head>
<title>Test page</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="maker.js"></script>
</head>
<body onload="loadComments();">
<div id="table_content">
</div>
</body>
</html>
comments.template.php
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60); ?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) {
echo 'Reply';
}
echo 'Delete';
?>
</div>
<?php if ($AnswerId == $item[0]) { ?>
<div id="InnerDiv"><?php include('commentForm.template.php'); ?></div>
<?php } ?>
commentForm.template.php
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerId);?>"/>
<button type='button' OnClick="SendComment()">Comment</button>
</form>
marker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "action.php",
data: "AnswerId="+id+"&action=get",
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
return false;
}
function loadComments (){
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "action=get",
success: function(html){
$("#table_content").html(html);
//clean_form();
}
});
return false;
}

PHP code to insert data into mysql database is not working

I'm trying to insert data without refreshing the page using ajax and php, but the data is not getting inserted into the database.
Here is my code
<?php
require 'validation_class.php';
$obj_menufacture = new Validation_Class();
if (isset($_POST['btn'])) {
$menufacture = $obj_menufacture->menufacture_add($_POST);
}
?>
<!DOCTYPE html>
<html>
<head>
<script src='js/jquery-3.0.0.js'></script>
</head>
<body>
<div id='form_id'>
<form action='' method='post'>
<input type='text' class='m_name' name='m_name' id='m_name' onchange="names('m_name')" onkeyup="names('m_name')"/>
<span style='color:red;' id='m_name_error'></span>
<input type="submit" name='btn' value="submit" id='save'/>
</form>
</div>
<div id='cool'></div>
<style>
.border_input{
border-color:red;
}
.border_input1{
border-color:green;
}
</style>
<script>
$(document).ready(function () {
$('#save').on('click', function (e) {
e.preventDefault();
var m_name = $.trim($('#m_name').val());
var dataString = 'name='+ m_name;
if (m_name === '') {
if (m_name == '') {
$('#m_name_error').html('Please enter your name');
$('#m_name').addClass('border_input');
}
} else {
$.ajax({
url: 'validation.php',
method: 'post',
data:dataString,
success: function () {
$("#form_id").slideUp("slow");
}
});
}
});
});
function names(id) {
var val = $.trim($('#' + id).val());
if (val === '') {
$('#' + id + '_error').html('');
$('#' + id).addClass('border_input');
} else {
$('#' + id + '_error').html('');
$('#' + id).addClass('border_input1');
}
}
</script>
</body>
</html>
Here is my insert code
<?php
class Validation_Class{
public $link;
public function __construct() {
$HOST = "localhost";
$USER = "root";
$PASS = "";
$DATABASE = "store";
$this->link = mysqli_connect($HOST, $USER, $PASS, $DATABASE);
if (!$this->link) {
die('database query problem' . mysqli_error($this->link));
}
}
public function menufacture_add($data) {
$sql = "INSERT INTO menufacture(m_name)VALUES('$data[m_name]')";
if (mysqli_query($this->link, $sql)) {
$menufacture = "Menufacture insert successfully";
return $menufacture;
} else {
die('menufacruere query problem' . mysqli_error($this->link));
}
}
}
please help me what can i do to solve this
<form name="signup" id="reg" action="" method="post"enctype="multipart/form-data">
<input type='text' class='m_name' name='m_name' id='m_name' onchange="names('m_name')" onkeyup="names('m_name')"/>
<span style='color:red;' id='m_name_error'></span>
<input type="submit" name='btn' value="submit" id='save'/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#save").submit(function () {
var form_data = $('#reg').serialize();
$.ajax({
type: "POST",
url: 'setting.php',
data: $('#reg').serialize(),
success: function (data) {
alert('Data save Successfully');
}, error: function () {
alert('Some Internal Error.');
}
});
});`
</script>
settting.php
<?php
include("db_connection.php"); // include connection file
if(isset($_POST)) {
$fname = $_POST['m_name'];
$insert = "INSERT INTO `table_name`(`column_name`)VALUES('".$fname."')";
$insertion = mysqli_query($conn, $insert);
}
?>
$("#save").on("click", function () {
var form_data = $('#reg').serialize();
$.ajax({
type:"POST",
url:'setting.php',
data: $('#reg').serialize(),
success: function(data){
alert("Data save Successfully");
},error: function () {
alert('Some Internal Error.');
}
});
});

On onblur event ajax get calles but it not returning to the original page

In my code the onblur event ajax method gets called in that it goes to ajaxcarmake.php. It executes the logic correctly but it does not come back to the addcarmake.php page. It also doesn't show me the alert message inside success:
plz give me the answer what i did wrong.
addcarmake.php
<form name="addcategoryfrm" id="addcategoryfrm" action="addcarmake1-process.php" method="GET">
<div style="width:100%;height:auto;float:left;margin-top:50px;">
<div class="txttitle">Car Make Name </div>
<div class="txtinputouter1">
<input type="text" name="name" class="categoryname" onblur="check_carmake(this);"/>
</div>
</div>
<div style="width:100%;height:auto;float:left;margin-top:10px;">
<div class="txtinputouter1" style="padding-left:30%;padding-top:40px;">
<input type="submit" value="Submit"/>
</div>
</div>
<div id="demo"></div>
</form>
Script
<script>
function check_carmake(name) {
$name = name.value;
$.ajax({
type: "GET",
url: 'ajaxaddcarmake.php',
data: {
$name: $name
},
success: function(result) {
if (result == 1) {
alert("Car make name already present");
}
},
error: function(err) {
alert(err);
}
});
}
</script>
ajaxaddcarmake.php
<?php
session_start();
if (isset($_SESSION['username1'])) {
include("../config/database.php");
$name = $_GET['$name'];
$query = "select * from add_car_make where name='$name'";
$result = mysql_query($query) or die(mysql_error());
echo $query;
$rows = mysql_num_rows($result);
if ($rows > 0) {
echo 1;
} else {
echo 0;
}
}
?>
Few things that we have missed .
script
script should like this .
data should send like this
data: {
name: $name
},
not
data: {
$name: $name
},
we were passing '$' in the variable.
<script>
function check_carmake(name) {
$name = name.value;
$.ajax({
type: "GET",
url: 'ajaxaddcarmake.php',
data: {
name: $name
},
success: function(result) {
if (result == 1) {
alert("Car make name already present");
}
},
error: function(err) {
alert(err);
}
});
}
</script>
ajaxaddcarmake.php
Also in this php script , we have small changes.
we have to get variable like this
$name = $_GET['name']; // remove '$' not $name = $_GET['$name'];
<?php
session_start();
if (isset($_SESSION['username1'])) {
include("../config/database.php");
$name = $_GET['name'];
$query = "select * from add_car_make where name='$name'";
$result = mysql_query($query) or die(mysql_error());
echo $query;
$rows = mysql_num_rows($result);
if ($rows > 0) {
echo 1;
} else {
echo 0;
}
}
?>
Hope this will help!

How to pass variables through ajax?

I want to pass variables from post.php to addcomment.php through the AJAX request. I have tried the code below but it does not seem to work. It reloads the page but nothing happens nor is data inserted in database
post.php
//variables to pass
$userid = $row['userid'];
$uid = $row['uid'];
$postid = $row['postid'];
<form method='post' name='form' action='' class='commentbox'>
<textarea name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit' class='comment_button'/>
</form>
<script type="text/javascript" >
var userfrom = '<?php echo $uid ?>';
var userto = '<?php echo $userid ?>';
var postid = '<?php echo $postid ?>';
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
dataString: dataString,
userfrom: userfrom,
userto: userto,
postid: postid
}
cache: false,
success: function(html){
$(".display").show(html);
}
});
}
return false;
});
});
</script>
addcomment.php
if (isset($_POST['dataString'], $_POST['userto'], $_POST['userfrom'], $_POST['postid'])) {
$userid = $_POST['userto'];
$uid = $_POST['userfrom'];
$postid = $_POST['postid'];
$comment = $_POST['dataString'];
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, post) VALUES (:comment, :userto, :userfrom, :post)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':post'=>$postid));
}
Create hidden fields for userid, uid and postid and assign the values.
Get the values as var userfrom = $("#uid").val(); in script (post.php). It will Work
Please try below code, just replace below code.
your page is reloaded because of add button type submit, for ajax event you need to set type button, Please check below code :
<?php
//variables to pass
$userid = $row['userid'];
$uid = $row['uid'];
$postid = $row['postid'];
?>
<form method='post' name='form' action='' class='commentbox'>
<textarea name='content' id='content'></textarea><br />
<input type='button' value='Comment' name='submit' class='comment_button'/>
</form>
<script type="text/javascript" >
var userfrom = '<?php echo $uid ?>';
var userto = '<?php echo $userid ?>';
var postid = '<?php echo $postid ?>';
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
dataString: dataString,
userfrom: userfrom,
userto: userto,
postid: postid
},
cache: false,
success: function(html){
$(".display").show(html);
}
});
}
return false;
});
});
</script>

Categories