Working on a web app , I just added the below update code and it's not working .
The summary of all the below code is :
Click a Button called update
It brings out the FORM which should contain the values of the clicked/current product.
Now when I hit save in this form it should update the database but it is not.
I am using $_GET in PHP file (update.php) to get the current Product ID.And then getting all data of that product via that ID.
PS: There is no error in console.
UPDATE CODE:
<?php
include "includes/connection.php";
switch($_GET['action']) {
case 'update_entry' :
$data = json_decode(file_get_contents("php://input"));
$index = $data->id;
$productname = $data->pname;
$company = $data->company;
$price = $data->price;
$quantity = $data->quantity;
if(isset($productname) && !empty($productname) && isset($company) && !empty($company) && isset($price) && !empty($price) && isset($quantity) && !empty($quantity)){
$query = "UPDATE `product` SET `id`='$index',`name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $index";
if(mysqli_query($con, $query)) {
return true;
} else {
echo "Error: " . $sql . "<br />" . mysqli_error($con);
}
break;
}
}
?>
Controller :
myApp.controller("updateCtrl",['$scope','$http','$routeParams','$location',function($scope,$http,$routeParams,$location){
$scope.update = function(){
var currentId = $routeParams.id;
$http.post("update.php?action=update_entry",{'id':currentId})
.then(function(data){
$location.path('/viewproduct');
});
}
}]);
HTML:
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
Update Button:
<td ng-controller="updateCtrl"><a class="btn btn-primary" href="#/updateproduct/action={{product.id}}" >Update</a></td>
Do like below
your view part
<form style="padding:10px" ng-controller="updateCtrl">
<div class="form-group">
<label for="ProductName">Product Name</label>
<input type="text" class="form-control" placeholder="{{product.name}}" ng-model="productname" required>
</div>
<div class="form-group">
<label for="company">Company </label>
<input type="text" class="form-control" placeholder="{{product.company}}" ng-model="company" required>
</div>
<div class="form-group">
<label for="company">Price </label>
<input type="text" class="form-control" placeholder="{{product.price}}" ng-model="price" required>
</div>
<div class="form-group">
<label for="company">Quantity </label>
<input type="text" class="form-control" placeholder="{{product.quantity}}" ng-model="quantity" required>
</div>
<button type="submit" class="btn btn-default" ng-click="update()">Save updated data</button>
Cancel
<h1 ng-if="successMessage == 0">Great Data is Updated!</h1>
</form>
<td><a class="btn btn-primary" ng-click="addProductData();" >Update</a></td>
Inside your controller do like below
$scope.addProductData=function(){
var updatedata=$.param({'action':'update','productname':$scope.productname,'company':$scope.company,'price':$scope.price,'quantity':$scope.quantity,'id':currentId});
$http({
method:'POST',
url:'update.php',
data:updatedata,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
alert(response.data['msg']);
},function errorCallback(response) {
alert(response.data['msg']);
});
}
your update.php file should like below.
<?php
include "includes/connection.php";
$result=array();
if(isset($_REQUEST["action"]) && $_REQUEST["action"] !=""){
if($_REQUEST["action"]=="update"){
$productname = $_POST['productname'];
$company = $_POST['company'];
$price = $_POST['price'];
$quantity = $_POST['quantity'];
$id=$_POST['id'];
$query = "UPDATE `product` SET `name`='$productname',`company`='$company',`price`='$price',`quantity`='$quantity' WHERE id= $id";
if(mysqli_query($con, $query)) {
$result['msg']="updated successfully";
}else{
header("HTTP/1.0 401 Unauthorized");
$result['msg']="unable to updated";
}
echo json_encode($result);
}
}
?>
i think you may basic idea.now you can implement in your way.
Try to use ng-model="{{product.name}}}" and not the placeholder in HTML.
And in your controller pass that model:
$http.post("update.php?action=update_entry",$scope.product)
Then you should get some data in your PHP.
Have you checked your php alone to make sure that you can fetch and update data using the php without angular? I would use post as it is more friendly for retrieving and updating data.
I would also b separate your call to the php endpoint into a service (factory). I would also just pass the entire object back through to ensure that you aren't missing something unless you have a concern about bandwidth.
I would unit test php first. Then separate logic in angular. Then b step through in debug to see what's being passed from the view.
I think you should check this: https://github.com/eliarms/CustomerManagerApp
This is a simple customer management app using Angularjs and PHP. The goal of the application is to highlight a lot of the different features offered by AngularJS and demonstrate how they can be used together.
Related
I am new to Jquery but I have done a lot with html/php in the past. What I need to do is submit for data from within a popup modal, insert that into a mysql database on localhost and then open teh next popup via javascript. As redirecting to the php page does not allow you to load js, I have looked into using jquery to post the data to my phpfile, which will then insert the data and return a code to the jquery, which will then load the next popup if the post was succesful. I have tried different tutorials, but I just cannot get the code to work. Below is my index.php file, which contains the popup form and jquery code...
<div id="survey1" class="w3-modal">
<div class="w3-modal-content w3-animate-top w3-card-4">
<div class="w3-container w3-padding-16">
<div class="section-heading text-center">
<div class="col-md-12 col-xs-12">
<h1>BASIC <span>DETAILS</span></h1>
<p class="subheading">The basics of your business and your website.</p>
</div>
</div>
<form role="form" class="login-form" method="post" action="http://localhost/basic.php" id="basicForm">
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Full Name" aria-describedby="basic-addon1" name="name" id="name">
</div>
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Email" aria-describedby="basic-addon1" name="email" id="email">
</div>
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Business Name" aria-describedby="basic-addon1" name="bname" id="bname">
</div>
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Business Type" aria-describedby="basic-addon1" name="btype" id="bemail">
</div>
<div id="response"></div>
<button class="btn" type="submit" id="submit1" name="submit1" style="width:40%; float: right;"></button>
</form>
<script>
$(document).ready(function(){
$('#basicForm').on('submit', function(e){
e.preventDefault();
$('#submit1').prop('disabled', true);
var name = $('#name').val();
var email = $('#email').val();
var bname = $('#bname').val();
var btype = $('#bemail').val();
if(name == '' || email == '' || bname == '' || btype == '')
{
$('#submit1').prop('disabled', false);
}
else
{
$.post(
'http://localhost/TDS/basic.php',
$('#basicForm').serialize(),
function(data)
{
$('form').triggered("reset");
$('#submit1').prop('disabled', false);
}
);
}
});
});
</script>
</div>
</div>
</div>
And this is my php insert file...
<?php
require('connection.php')
if(isset($_POST["name"]))
{
$name = mysqli_real_escape_string($con, $_POST["name"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$bname = mysqli_real_escape_string($con, $_POST["bname"]);
$btype = mysqli_real_escape_string($con, $_POST["btype"]);
$insert_query = "INSERT INTO Details ('Name', 'Email', 'Business Name', 'Businesss
Type') VALUES ('".$name."', '".$email."', '".$bname."', '".$btype."')";
if(mysqli_query($con, $insert_query))
{
echo json_enchode(success => 1);
}
else
{
echo json_enchode(success => 0);
}
}
?>
Any help would be much appreciated!
The code itself is OK, but you need to load jQuery itself.
Put this somewhere in the beginning of your HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
(the tips on how to include jQuery see here: https://www.w3schools.com/jquery/jquery_get_started.asp)
Except this, the code worked for me:
- The form was submitted correctly;
- The PHP endpoint received the correct POST data;
The saving to DB I didn't check, but it looks OK.
Anyways, the PHP part is out of the scope of the question.
Also, a small issue is in the code itself: there's no such method as "$('form').triggered('reset');", use "$('form').trigger('reset');" instead.
I have the following form which I then send upon submit via AJAX to insert to a MySQL DB through Ajax. All inputbox in form have their own Id and I get them all in my .php process file except the ones "cas" and "dat" that do not seem to go through the AJAX posting process.
The form:
<form id="form">
<div class="form-group">
<label class="lab" for="nm">id</label>
<input disabled type="text" id="id" name="id" class="form-control" placeholder="Id">
</div>
<div class="form-group">
<input type="text" class="form-control" name="cas" id="cas" value="2">
<input type="text" class="form-control" name="dat" id="dat" value="2017-11-30">
</div>
<div class="form-group">
<label class="lab" for="nm">Product</label> <?php
//// function populate ($sql, $class,$name, $id, $title, $value,$option)
echo populate ("SELECT * FROM product_family order by product_type_id ASC","form-control","nm","nm","Select Product", "product_family", "product_family");?>
</div>
<div class="form-group">
<label class="lab" for="em">Win</label>
<input type="text" id="em" name="em" class="form-control allow_decimal" placeholder="Win">
</div>
<div class="form-group">
<label class="lab" for="hp">Drop</label>
<input type="text" id="hp" name="hp" class="form-control allow_decimal" placeholder="Drop">
</div>
<div class="form-group">
<label class="lab" for="ad">Currency</label> <?php
//// function populate ($sql, $class,$name, $id, $title, $value,$option)
echo populate ("SELECT * FROM currency order by id ASC","form-control","ad","ad","Select Currency", "currency", "currency");?>
</div>
<button type="button" id="save" class="btn btn-success" onclick="saveData()">Save</button>
<button type="button" id="update" class="btn btn-warning" onclick="updateData()">Update</button>
</form>
I then have the following JavaScript code triggering the Insert upon "save data" click in order to post the different inputbox values to my .php processing file:
function saveData(){
var id = $('#id').val();
var name = $('#nm').val();
var email = $('#em').val();
var phone = $('#hp').val();
var address = $('#ad').val();
var casino = $("#cas").val()
var date = $("#dat").val();
$.post('server.php?p=add', {id:id, nm:name, em:email, hp:phone, ad:address, cas:casino, dat:date}, function(data){
viewData()
$('#id').val(' ')
$('#nm').val(' ')
$('#em').val(' ')
$('#hp').val(' ')
$('#ad').val(' ')
})
}
function viewData(){
$.get('server.php', function(data){
$('tbody').html(data)
})
}
Then I try to read my "$_post" values on the PHP side:
if($page=='add'){
try{
$id = $_POST['id'];
$nm = $_POST['nm'];
$em = $_POST['em'];
$hp = $_POST['hp'];
$ad = $_POST['ad'];
$casino_id = $_POST['cas'];
$date = $_POST['dat'];
}
I perfectly get all variables except the dat and cas posts that do no appear in the $_post list. Listing all $_Post the following way:
$myfile = fopen("LOGPOST.txt", "w") or die("Unable to open file!");
foreach ($_POST as $key => $value){
$txt= $txt."{$key} = {$value}//";
gives the following output: id = //nm = F&B Sales//em = 1000//hp = 500//ad = EUR//
What am I doing wrong?
Have been working on a form with Ajax and used to work on a version with no extras (css and so on) before. It worked all fine, data has been inserted successfully into the database and I have been able to show and hide two divs.
Now I used to apply it to the form I've been working on. It acts different from the previous version, so it's exactly the same (sure, changed some names, added some inputs), like no "success message" from the PHP-file, suddenly all data visible in the URL, the current form doesn't hide and shows the next one.
I can't understand the sudden change in behavior, took a look for mistakes, compared the codes, but have no idea. It seems to be such a small mistake that I don't spot it or something is wrong with the whole construction.
The current file is:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?
require 'config.php';
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
?>
<script type="text/javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "demo_ajax.php",
data:'country_id='+val,
success: function(data){
$("#region").html(data);
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
var size=$("#size").val();
var industry=$("#industry").val();
var country=$("#country").val();
var region=$("#region").val();
var url=$("#website").val();
var fb=$("#fb").val();
var lkdn=$("#lkdn").val();
$.ajax({
type:"post",
url:"process2.php",
data:"size="+size+"&industry="+industry+"&country="+country+"®ion="+region+"&url="+url+"&fb="+fb+"&lkdn="+lkdn,
success:function(data){
$("#theform").hide();
$("#info").html(data);
//$("#partone").css();
$("#partone").show();
alert("Hello");
}
});
});
});
</script>
<?php include 'js/js.html'; ?>
<?php include 'css/css.html'; ?>
</head>
<body class="w3-blue r_login_corp_body">
<div id="info" style="color:white"></div>
<div class="r_login_corp_body"></div>
<div class="w3-content w3-white r_siu r_centered_div">
<header class="w3-camo-black w3-container">
<div class="w3-container ">
<span class="w3-xlarge r_caption">eRecruiter</span> <span class="large">Corporate Login</span>
</div>
<div class="w3-black">
<a href="javascript:void(0)" onclick="selectForm('register');">
<div class="w3-half tablink w3-hover-text-yellow w3-padding w3-center w3-padding-16">Register</div>
</a>
</div>
</header>
<!-- Register -->
<div id="register" role="form" class="r_form_elements">
<form name="formone" class="form" autocomplete="off">
<div id="profed" class="w3-container w3-padding-16">
<div class="alert alert-error"></div>
<label>Company Industry</label>
<input class="w3-input" name="industry" id="industry" type="text" placeholder="Your Industry" >
<label>Company Size</label>
<input class="w3-input" name="size" id="size" type="integer" placeholder="Your Company Size" >
<label >Country:</label>
<select name="country" id="country" class="demoInputBox" onChange="getState(this.value);" >
<option value="">Select Country</option>
<?php
$sql1="SELECT * FROM pentagonal_country";
$results=$mysqli->query($sql1);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["country_code"]; ?>"><?php echo $rs["country_name"]; ?></option>
<?php
}
?>
</select>
<label>State:</label>
<select id="region" name="region" onKeyup="checkform()">
<option value="">Select State</option>
</select>
<label>Website</label>
<input class="w3-input" name="website" id="website" type="url" placeholder="Your Website-Address" >
<label>Facebook</label>
<input class="w3-input" name="fb" id="fb" type="url" placeholder="https://facebook.com/" >
<label>Linkedin</label>
<input class="w3-input" name="lkdn" id="lkdn" type="url" placeholder="https://linkedin.com/in/">
</div>
<div class="w3-row">
<button type="submit" id="submit" class="w3-button w3-black w3-half w3-hover-yellow" >Add</button>
<button class="w3-button w3-black w3-half w3-hover-pale-yellow">Forgot Password</button>
</div>
</form>
</div>
<!-- Register -->
<div id="partone" style="display:none">
<form>
name : <input type="text" name="name" id="name">
</br>
message : <input type="text" name="message" id="message">
</br>
</br>
name : <input type="text" name="url" id="url">
</br>
message : <input type="text" name="fb" id="fb">
</br>
name : <input type="text" name="lkdn" id="lkdn">
</br>
</br> </br>
Send;
</form>
</div>
</div>
</body>
</html>
and the PHP-file to insert data is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "remotejobs";
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$industry=$_POST["industry"];
$size=$_POST["size"];
$country=$_POST["country"];
$region=$_POST["region"];
$website=$_POST["url"];
$fb=$_POST["fb"];
$lkdn=$_POST["lkdn"];
$usrid=$id;
$sql = "INSERT INTO corp_user_profile (id, industry, size, nation, region, url, facebook, linkedin)
VALUES ('$usrid', '$industry','$size', '$country', '$region', '$website', '$fb', '$lkdn')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I used to work with the previous file I've worked with just to be sure that everything's right after a week of bug fixing.
Can somebody tell me where the problem is, probably why it is a mistake to avoid future problems like this?
The most obvious bug (aside from the SQL injection stuff mentioned above) is that
<button type="submit" will cause the form to submit normally via postback, unless you prevent it using script. Add event.preventDefault() to the first line of your "click" handler.
$("#submit").click(function(event){
event.preventDefault(); //prevent default postback behaviour
var size=$("#size").val();
//...etc
You're seeing the data in the URL because the form is posting normally (before the ajax has chance to run) and doing a GET because there's no other method specified in the form's markup, and GET is the default..
You may want to prevent the default behavior by passing the event to your click function and calling event.preventDefault().
HeyHeyHey!
I am having this problem, for some reason it won't add the Data to my MYSQL Database and I have no idea why. I looked at a lot of other posts here on StackOverflow, but can't seem to find a post that helps me :)
Here is my code:
<script>
$('.alert-saved-changes-success2').hide();
$(".save-tradelink-profile").click(function() {
$tradelinkvalue = document.getElementById("tradelink").value;
if ($.trim($('#tradelink').val()) == '') {
alert('Tradelink can not be blank');
} else if ($tradelinkvalue.indexOf("https://steamcommunity.com/tradeoffer/new") >= 0) {
<?php //TRYING TO UPDATE DATA
$TradelinkValue = $_POST['GetTradelinkValue'];
mysql_query("UPDATE item-jackpot-users SET tradelink=$TradelinkValue WHERE steam_id=$steamid") or die(mysql_error());
?>
$("#alert-saved-changes-success").slideDown("slow");
} else {
alert('Tradelink has to be valid');
}
});
$(".logout-button-profile").click(function(){
window.location.href = "steamauth/logout.php";
});
</script>
It seems like the php tag gets loaded before everything else, since the
$('.alert-saved-changes-success2').hide();
doesn't load. It finds the error, and then just killing everything else.
Respecting the fact that yes, php is performed before your webbrowser receives the js text, you could use a form, that sends your update information into post(like using a form tag), reload the page, and make the page perform the update with your post data. You could also use ajax.
<form name="login" class="form-horizontal" method="post" action="refer to this file" >
<div class="form-group">
<label class="col-sm-3 control-label">
Username
</label>
<div class="col-sm-2">
<input class="pull-right" type="text" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">
Password
</label>
<div class="col-sm-2">
<input class="pull-right" type="password" name="password" />
</div>
</div>
<div class="form-group">
<div class=" col-sm-offset-3 col-sm-2">
<button type="submit" name="submitbtn" class="btn btn-default pull-right">
Sign in
</button>
</div>
</div>
</form>
<?php
$user = $_POST['username'];
$pwd = $_POST['password'];
//DO SOME SANITIZATION!
//Store $user and $pwd
?>
Ofcourse you could include the php part somewhere else in the file, like inside of a script tag.
I have a html page which contains
a form with fields for sign up (registration / new member)
a form for sign in (login for already member)
The sign in form is :
<form class="dialog-form">
<div class="form-group">
<label>E-mail</label>
<input type="text" placeholder="email#domain.com" class="form-control">
</div>
<div class="form-group">
<label>PAssword</label>
<input type="password" placeholder="My PAssword" class="form-control">
</div>
<input type="submit" name="sign_in" value="Connexion" class="btn btn-primary">
</form>
The sign up form is :
<form class="dialog-form" action="bat/user_validation.php" method="post">
<div class="form-group">
<label>E-mail</label>
<input type="text" placeholder="email#domain.com" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" placeholder="My secret password" class="form-control">
</div>
<div class="form-group">
<label>Repeat Password</label>
<input type="password" placeholder="Type your password again" class="form-control">
</div>
<input type="submit" name="sign_up" value="Inscription" class="btn btn-primary">
</form>
One the other side, I have a php script file which contains function to check and insert a userid.
function getPassword($utilisateur) {
try {
$dbh = new PDO(DSN, USER, PASS);
$uid = $utilisateur;
$sql = "SELECT password FROM cc_users WHERE uid =:uid";
$sth = $dbh->prepare($sql);
$sth->execute(array(':uid'=>$uid));
$result = $sth->fetchAll();
return (count($result) == 1) ;
} catch (PDOException $e) {
print "Erreur ! : " . $e->getMessage() . "<br/>";
die();
}
}
function setPassword($uid, $pass) {
$dbh = new PDO(DSN, USER, PASS);
$sql = "UPDATE cc_users SET password =:pass where uid =:uid";
$sth = $dbh->prepare($sql);
$sth->execute(array(':pass'=>$pass ,':uid'=>$uid));
echo $count = $sth->rowCount();
return $dbh->exec($sql);
}
function newPassword($utilisateur, $pass) {
$crypt = crypt($pass);
return setPassword($utilisateur, $crypt);
}
function checkPassword($utilisateur, $pass) {
if (empty($pass)) return FALSE;
$interne = getPassword($utilisateur);
$crypt = crypt($pass, $interne);
return ($interne === $crypt);
}
print_r($_POST);
My questions are :
How I can check on which form the user is coming?
How can I do an $.ajax call for checking the form? If yes how?
Thanks
HTML:
Form 1:
<form id="form1">
<input type="submit" value="submit" />
</form>
Form 2:
<form id="form2">
<input type="submit" value="submit" />
</form>
jQuery:
$('form').on('submit', function () {
console.log($(this).attr('id')); // Logs the id of the submitted form
});
Give name for <form>
<form class="dialog-form" name="signin">
<form class="dialog-form" action="bat/user_validation.php" method="post" name="signup">
You can check $_POST global to see if it contains the name of your <input type="submit" />. It will contain either sign_up or sign_in, depending on what button did the user press.
For example:
if(isset($_POST['sign_up']){
$signingUp = true;
}
If you want to submit the form using jQuery ajax, you can use the following code snippet:
$.post('bat/user_validation.php', $('form.dialog-form').serialize());
Though the selector should be more concrete, probably including a form ID to distinguish between the two forms.