Update sql data using AngularJS - javascript

I need to update data using angular
I have SQL table(task list) with columns: id, taskname, date, prior
I need to have possibility to update only current field, using keypress
Field need to be updated according to its id.
HTML
<div class="task-list" ng-repeat="x in names">
<div class="col-md-1">
<input type="text" value="{{x.prior}}" ng-keypress="UpdateInfo()"/>
</div>
<div class="col-md-5">
<input type="text" value="{{x.taskname}}" ng-keypress="UpdateInfo()"/> <input type="submit" name="btnInsert" class="btn btn-info" ng-click="DeleteInfo()" value="Delete"/>
</div>
<div class="col-md-5">
<input type="date" value="{{x.startdate}}" ng-keypress="UpdateInfo()"/>
</div>
</div>
Controller
$scope.UpdateInfo = function(){
$http.post(
"update.php",
{'taskname':$scope.taskname, 'comments':$scope.comments, 'prior':$scope.prior, 'startdate':$scope.startdate }
).success(function(data){
alert(data);
if (data == true) {
getInfo();
}
});
}
PHP
There I tried to update only taskname
$data = json_decode(file_get_contents("php://input"));
if(count($data) > 0)
{
$id = mysqli_real_escape_string($connect, $data->id);
$taskname = mysqli_real_escape_string($connect, $data->taskname);
$comments = mysqli_real_escape_string($connect, $data->comments);
$startdate= mysqli_real_escape_string($connect, $data->startdate);
$prior= mysqli_real_escape_string($connect, $data->prior);
$query = "UPDATE tbl_user SET taskname='$taskname' WHERE id='$id'";
if(mysqli_query($connect, $query))
{
echo "Data Update...";
}
else
{
echo 'Error';
}
}
After keypress I see only "Data Update...".But taskname isn't updated.

You are sending a POST request so I don't think you need:
$data = json_decode(file_get_contents("php://input"));
Instead refer to the variables as $_POST['taskname'] and so on ..

Related

Use get url parameter in sql sent with ajax

I can successfully send post data with ajax and get data into mysql database. However I can't display when I use POST parameter in sql statement. İf I remove POST parameter from sql, data perfectly display where it should be.
What am I missing? Here what I've got.. thanks
**index.php**
<form method="POST" id="ask1">
<div class="form-group">
<input type="text" name="name" />
</div>
<div class="form-group" >
<textarea name="content" ></textarea>
</div>
<div class="form-group" >
<input type="hidden" name="service" value ="<?php echo ''.htmlentities($_GET["service"]).'' ?> ">
<input type="submit" name="submit" value="Submit" />
</div>
</form>
<div><span id="message" ></span></div>
<div id="display_message" ></div>
**ask.php**
$service = $_POST['service'];
$query = "SELECT * FROM ask WHERE comment_id = '0' and
service='".mysqli_real_escape_string($conn,$service)."' ";
$statement = $conn->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<div class="panel-body" style="font-size:12px;">"'.$row["name"].'"</div>
';
$output .= get_reply_comment($conn, $row["id"]);
}
echo $output;
Ajax
<script>
load_comment();
function load_comment()
{
$.ajax({
url:"ask.php",
method:"POST",
success:function(data)
{
$('#display_message').html(data);
}
})
}
</script>

Provide a valid password before proceeding (Codeigniter)

Newbie here. I have a modal where staff can transfer fund to a client. Before transferring fund, the staff must input his/her password before proceeding to transaction. My goal is to have a WORKING FUNCTION about the password validation. I made a slightly working function. I have provided a video below for better explanation.
https://streamable.com/z4vgtv //Correct or wrong password, the result is the same. "Password not match"
Controller:
public function form_validation($userID)
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$password = $this->input->post('password');
$exists = $this->networks->filename_exists($password);
$count = count($exists);
if($count >=1)
{
if($this->form_validation->run())
{
$ref= $this->session->userdata('uid') + time ();
$id = $this->input->post('userID');
$pData = array(
'userID' => $id,
'transactionSource' => 'FR',
'refNumber' => 'FI-0000' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"in",
);
$this->networks->fundin($pData);
$ref= $this->session->userdata('userID') + time ();
$data1 = array(
'userID' => $this->session->userdata('uid'),
"transactionSource" => 'FR',
"refNumber" => 'FO' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"out",
);
?>
<script> alert("password match");</script>
<?php
$this->networks->insert_data($data1);
redirect(base_url() . "network/agents");
}
else
{
$this->index();
}
}
else
{
?>
<script> alert("Password not Match");</script>
<?php
}
}
Model:
function filename_exists($password)
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('password', $password);
$query = $this->db->get();
$result = $query->result_array();
return $query->result();
}
Views:
<form id="doBetting" method="post" action="<?php echo base_url('network/form_validation');?>/<?php echo $rows->userID; ?>">
<div class="input-group input-group-sm" style="width: 100%" >
<input type="hidden" id="usertransferid" name="userID">
<div class="col-lg-12" >
<input type="number" placeholder="Enter Amount" name="amount" class="form-control" id="box" required>
<br>
<input type="password" placeholder="Enter Password" name="password" class="form-control" id="cpass" required onblur="check_if_exists();">
<br>
<!-- buttons -->
<input type="submit" class="btn btn-success text-bold" name="save" id="insert" value="Transfer">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Ajax:
<script>
<script>
function check_if_exists() {
var password = $("#cpass").val();
$.ajax(
{
type:"post",
url: "<?php echo site_url(); ?>network/form_validation",
data:{password:password},
success:function(response)
{
// remove alert();
}
});
}
check_if_exists();
</script>
User always saved password on database with encoded form,but in your case,firstly you need to encode your password(format md5 or which format you are using to encode) and then check with your user password.
public function form_validation($userID)
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$password = md5(trim($this->input->post('password')));
$exists = $this->networks->filename_exists($password);
.........
}

Confirmation message after inserted data in new page

Good day all, I'm new to PHP and I really need some help. I'm trying to make a confirmation message in new page after inserting data. I tried echo and print the results, But nothing work to me!!!!. This is the only problem I faced which I could not solved !!!
Code for request.php page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body dir="rtl">
<div class="container" style="width:400px;">
<div ng-app="myapp" ng-controller="formcontroller">
<form name="userForm" id="contact" ng-submit="insertData()">
<label class="text-success" ng-show="successInsert">{{successInsert}}</label>
<div class="form-group">
<label>name<span class="text-danger"></span>
</label>
<input type="text" name="name" ng-model="insert.name" class="form-control" /><span class="text-danger" ng-show="errorname">{{errorname}}</span>
</div>
<fieldset class="frmain">
<label>contact</label>
<div class="form-group">
<input type="text" name="em" ng-model="insert.em" class="form-control" placeholder="اemail" />
<span class="text-danger" ng-show="errorem">{{errorem}}</span>
<input type="text" name="telph" ng-model="insert.telph" class="form-control" placeholder="mobile" />
<span class="text-danger" ng-show="errortelph">{{errortelph}}</span>
</div>
<div class="form-group">
<label>department<span class="text-danger"></span>
</label>
<select ng-model="insert.dept" name="dept" class="form-control" style="font-family: times new roman;font-size: 18px;" />
<option value=""></option>
<option value="accounting department" </option>
<option value="huamn resources"></option>
<option value="IT department"></option>
</select>
<span class="text-danger" ng-show="errordept">{{errordept}}</span>
</div>
<div class="form-group" style="width: 320px;">
<label>details<span class="text-danger"></span>
</label>
<textarea name="det" ng-model="insert.det" class="form-control"></textarea>
<span class="text-danger" ng-show="errordet">{{errordet}}</span>
</div>
<div class="form-group">
<button name="submit" type="submit">send</button>
</div>
</form>
</div>
</div>
</body>
</html>
<script>
var application = angular.module("myapp", []);
application.controller("formcontroller", function($scope, $http) {
$scope.insert = {};
$scope.insertData = function() {
$http({
method: "POST",
url: "req_add.php",
data: $scope.insert,
}).success(function(data) {
if (data.error) {
$scope.errorname = data.error.name;
$scope.errorem = data.error.em;
$scope.errortelph = data.error.telph;
$scope.errordept = data.error.dept;
$scope.errordet = data.error.det;
$scope.successInsert = null;
} else {
$scope.insert = null;
$scope.errorname = null;
$scope.errorem = null;
$scope.errortelph = null;
$scope.errordept = null;
$scope.errordet = null;
$scope.successInsert = data.message;
}
});
}
});
</script>
Code for req_add.php page: (to insert data into DB)
<?php
//req_add.php
$connect = mysqli_connect("localhost", "root", "", "testing");
$form_data = json_decode(file_get_contents("php://input"));
mysqli_query($connect,'set names utf8') or die (mysqli_error($connect));
$data = array();
$error = array();
$date1 = date('Y/m/d H:i:s');// 2017-07-12 10:35:45
$today = date("Ymd");
$rand = strtoupper(substr(uniqid(sha1(time())),0,4));
$no1 = $today . $rand;
if(empty($form_data->name))
{
$error["name"] = "name is required";
}
if(empty($form_data->em))
{
$error["em"] = "email is required";
}
if(empty($form_data->telph))
{
$error["telph"] = "mobile number is required";
}
if(empty($form_data->dept))
{
$error["dept"] = "department is required";
}
if(empty($form_data->det))
{
$error["det"] = "details are required";
}
if(!empty($error))
{
$data["error"] = $error;
}
else
{
$name = mysqli_real_escape_string($connect, $form_data->name);
$em = mysqli_real_escape_string($connect, $form_data->em);
$telph = mysqli_real_escape_string($connect, $form_data->telph);
$dept = mysqli_real_escape_string($connect, $form_data->dept);
$det = mysqli_real_escape_string($connect, $form_data->det);
$no = mysqli_real_escape_string($connect, $form_data->no1);
$reqdate = mysqli_real_escape_string($connect, $form_data->reqdate);
$answer = mysqli_real_escape_string($connect, $form_data->answer);
$query = "INSERT INTO requests(name, em, telph, dept, det, no, reqdate, answer) VALUES ('$name','$em', '$telph', '$dept', '$det', '$no1', '$date1', 'no answer')";
if(mysqli_query($connect, $query))
{
$data["message"] = "thank you for your request, your request nymber is: " .$no1;
}
}
echo json_encode($data);
?>
One useful option is to use mysqli_insert_id to get the last id inserted.
This function get the last id in the DB, not only in the inserted table, but is sufficient.
Another is in manual form, where the query return a custom value.
In your code :
$query ="INSERT INTO requests(name, em, telph, dept, det, no, reqdate,answer)
VALUES ('$name','$em', '$telph', '$dept', '$det', '$no1','$date1', 'no answer')";
if(mysqli_query($connect, $query))
{
$data["message"] = "thank you for your request, your request nymber is: " .$no1;
}
}
echo json_encode($data);
Add this changes :
$query = "INSERT INTO requests(name, em, telph, dept, det, no, reqdate, answer)
VALUES ('$name','$em', '$telph', '$dept', '$det', '$no1', '$date1', 'no answer')";
$query .="; select 1 as insert_ok;";
if($stmt=mysqli_query($connect, $query)) // Get result
{
$fetch = mysql_fetch_object($stmt);
if ($fetch->insert_ok) {
$data["message"] = "thank you for your request, your request nymber is: " .$no1;
}else{
$data["message"] = "The register wasn't inserted";
} // else
} //if $stmt
echo json_encode($data);
And in your script code: validate the insert_ok value returned from the php script.

post data from html form to php script and return result to ajax/js/jquery

i want to excecute php script with ajax or javascript from html form. I need receive result from php page to html page.
My changepsw.php
<?php
//Change a password for a User via command line, through the API.
//download the following file to the same directory:
//http://files.directadmin.com/services/all/httpsocket/httpsocket.php
$system = $_POST['system'];
$db = $_POST['db'];
$ftp = $_POST['ftp'];
$id = $_GET['id'];
$psw = $_POST['userpw'];
$queryda = "SELECT * FROM paugos where id = '$id'"; //You don't need a ; like you do in SQL
$resultda = mysql_query($queryda);
$rowda = mysql_fetch_array($resultda);
if($system == "" or $system == "no" or $system !== "yes"){
$system = "no";
}
if($db == "" or $db == "no" or $db !== "yes"){
$db = "no";
}
if($ftp == "" or $ftp == "no" or $ftp !== "yes"){
$ftp = "no";
}
$server_ip="127.0.0.1";
$server_login="admin";
$server_pass="kandon";
$server_ssl="N";
$username = $rowda['luser'];
$pass= $psw;
echo "changing password for user $username\n";
include 'httpsocket.php';
$sock = new HTTPSocket;
if ($server_ssl == 'Y')
{
$sock->connect("ssl://".$server_ip, 2222);
}
else
{
$sock->connect($server_ip, 2222);
}
$sock->set_login($server_login,$server_pass);
$sock->set_method('POST');
$sock->query('/CMD_API_USER_PASSWD',
array(
'username' => $username,
'passwd' => $pass,
'passwd2' => $pass,
'options' => 'yes',
'system' => $system,
'ftp' => $ftp,
'database' => $db,
));
$result = $sock->fetch_parsed_body();
if ($result['error'] != "0")
{
echo "\n*****\n";
echo "Error setting password for $username:\n";
echo " ".$result['text']."\n";
echo " ".$result['details']."\n";
}
else
{
mysql_query("UPDATE paugos SET lpass='$pass' WHERE id='$id'");
//echo "<script type='text/javascript'> document.location = 'control?id=$id&successpw=1'; </script>";
//header("Location: control?id=1&successpw=1");
echo "$user password set to $pass\n";
}
exit(0);
?>
if script fails, it returns
Error setting password for $username. If success then php script return $user password set to $pass.
So i want to return answer from php page to html page with jquery/ajax.
My html form, from where I post data to my php script
<form action="changepsw.php?id=<?=$id;?>" method="post" role="form">
<label for="disabledSelect">Directadmin account</label>
<input name="usern" class="form-control" style="width:220px;" type="text" placeholder="<?=$luser;?>" disabled>
<div class="form-group">
<label>New password</label>
<input name="userpw" class="form-control" style="width:220px;" placeholder="Enter new password">
</div>
<div class="form-group">
<label>Change password for:</label>
<div class="checkbox">
<label>
<input type="checkbox" name="system" value="yes">Directadmin
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="ftp" value="yes">FTP
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="dabatase" value="yes">MySQL
</label>
</div>
</div>
<button type="submit" id="col" class="btn btn-default">Submit Button</button>
<button type="reset" class="btn btn-default">Reset Button</button>
</form>
In your HTML page you can user AJAX post request and in php you must use the die method as follows:
$.post('url',{parameters},function(data){
if(data==='1'){
alert('Done');
}else if(data==='0'){
alert('Error');
}else{
alert(data);
}
});
In PHP code use as follows:
die('1'); or die('0'); or
echo 'error occurs';
die;

issue with ajax login script

I'm very new to ajax, and I'm trying to make a login script that doesn't require a page reload - it's working well except I attempt to set a session variable on the processing page, but no session variable is set.
My form:
<div class="form-bottom">
<form role="form" class="login-form">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="submit" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
<? echo $_SESSION['Name']; ?>
</div>
My ajax:
<script type="text/javascript" >
$(function() {
$("#submit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+ username + '&password=' + password;
if(username=='' || password=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
});
}
return false;
});
});
</script>
My php script:
include('./static/config.php');
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
I was able to get it working the way I wanted it to.
Form:
<div id="box">
<div class="row">
<div class="col-sm-6 col-sm-offset-3 form-box">
<div class="form-top">
<div class="form-top-left">
<h3>Log-in</h3>
<span id="error" class="error"></span>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
</div>
<div id="box" class="form-bottom">
<form class="login-form" action="" method="post">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="login" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
</div>
</div>
</div>
</div>
AJAX Code:
<script src="js/jquery.min.js"></script>
<script src="js/jquery.ui.shake.js"></script>
<script>
$(document).ready(function() {
$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');},
success: function(data){
if(data)
{
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
else
{
$('#box').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
PHP (ajax/login.php):
<?php
include("../static/config.php");
session_start();
if(isSet($_POST['username']) && isSet($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,$_POST['password']);
$result=mysqli_query($con,"SELECT Name FROM techs WHERE Username='$username' and Password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION['Name']=$row['Name'];
echo $row['Name'];
}
}
?>
Since you've stated you're very new to Ajax, you start off pretty well.
There are however a couple of things to know how this works.
You want to avoid a page refresh, yet you don't print out any responses because you're not returning anything in the ajax request. You instead set a session variable which will show up at the next page request (so a refresh)
$.ajax({
type: 'POST',
url: 'ajax/login.php',
data: { username: $("#username").val(), password: $("#password").val() },
success: function (data) {
$('.form-bottom').html(data); // here we replace the form with output of the ajax/login.php response.
}
});
And for the PHP side of things:
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
if(($result = mysqli_query($con, $sql)) != false){ // always verify if your query ran successfully.
if(mysqli_num_rows($result)){ // or compare with == 1, but assuming a username is unique it can only be 1 so it equals to true.
echo mysqli_fetch_assoc($result)['name']; // index, columns, etc should always be lower cased to avoid confusion.
// Obviously you can store it in a session
// But for now just output the data so we can use it as our response.
// json is very usefull with sending large amounts of data.
}
}
The idea of Ajax is that you can request an update, but you need to update your page with javascript manually in order to make it work.
I think you forget to start the session.So start the session at the top of your script. Hope it will help.
session_start();
include('./static/config.php');
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
3 things you could try:
On the page where you are trying to set the session variable you would have to use proper php opening tags like <?php
Second thing is that you would have to put a value in your session like $_SESSION['hello'] = 'hello';
Third thing, on every page where you handle your session you would have to call <?php session_start(); ?> for it to work.
Goodluck!

Categories

Resources