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?
Related
Here is my basic form:
<form id="mgstaskvuephonecall" name="contactform" method="POST" >
<div class="mb-3">
<div class="input-group" id="fld1">
<input type="text" name="contact1" id="contact1" class="form-control tvc username" placeholder="Contact" aria-label="Username" alt="1">
<input type="text" name="phone1" id="phone1" class="form-control phone-number tvp" placeholder="Ex: +(000) 000-00-00" alt="1">
</div>
</div>
<div class="mb-3">
<div class="input-group" id="fld1">
<input type="text" name="contact2" id="contact2" class="form-control tvc username" placeholder="Contact" aria-label="Username" alt="2">
<input type="text" name="phone2" id="phone2" class="form-control phone-number tvp" placeholder="Ex: +(000) 000-00-00" alt="2">
</div>
</div>
<!-- ... a total of 5: contact1-contact5, phone1-phone5 -->
</form>
I am using AJAX to call php to pull data from the database, how then would I use the result to populate my form. I am stuck on handling the fields with same names just differenced by the sequential number on the end of it. Here's what I have so far, just stuck on how to manipulate results:
// fetch table data based on date
$("#form-date").on('change', function(){
var date = $(this).val();
$.ajax({
url: 'dynamic-pop-form.php',
method: 'POST',
data:{
"date":date
},
success: function(data){
var len = data.length;
...
}
}
});
});
dynamic-pop-form.php:
include('connection.php');
$formDate = $_POST['date'];
$formDate = strtotime($formDate);
$formDate = date('Y-m-d', $formDate);
$stmt = $conn->prepare("SELECT * FROM `my_table` WHERE `form_date` = ? LIMIT 5");
$stmt->bindParam(1,$formDate,PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode( $result );
Hello I have a problem on how should I send a JavaScript value to PHP.
Here is my form:
Dropdown Question from database:
fiddle code
<form action="action/survey">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Select Question</label>
<div class="col-sm-10">
<select class="form-control" id="mySelect" onchange="option()">
<?php
$sql = mysqli_query($con,"SELECT *,(SELECT GROUP_CONCAT(answer) AS `option`FROM `survey_anweroptions` WHERE survey_qID = sq.survey_qID) `option` FROM `survey_questionnaire`sq WHERE sq.survey_ID = $id");
while ($q = mysqli_fetch_array($sql)) {
?>
<option value="<?php echo $q[0]?>"><?php echo $q[2]?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label " for=""></label>
</div>
<?php
$sql = mysqli_query($con,"SELECT *,(SELECT GROUP_CONCAT(answer) AS `option`FROM `survey_anweroptions` WHERE survey_qID = sq.survey_qID) `option` FROM `survey_questionnaire`sq WHERE sq.survey_ID = 1 AND survey_qID = 1");
$d1= mysqli_fetch_array($sql);
?>
<div class="form-group">
<label class="control-label col-sm-2" for="">Question</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="" value="<?php echo $d1[2]?>">
</div>
</div>
<?php
$variable = $d1[3];
$z = 1;
$piece = explode(",", $variable);
foreach ($piece as $key => $value) {
?>
<div class="form-group">
<label class="control-label col-sm-2" for="">Option <?php echo $z?> </label>
<div class="col-sm-10">
<input type="text" class="form-control" id="" placeholder="" value="<?php echo $value?>">
</div>
</div>
<?php
$z++;
}
?>
<div class="text-center">
<button type="submit" class="btn btn-default" name="">Update</button>
</div>
</form>
JavaScript:
function option(){
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
What I want is if I select 1 value on the drop-down, the value of option must be sent to a PHP variable in this query:
SELECT *, (
SELECT GROUP_CONCAT(answer) AS `option`
FROM `survey_anweroptions`
WHERE survey_qID = sq.survey_qID
) `option`
FROM `survey_questionnaire`sq
WHERE sq.survey_ID = 1
AND survey_qID = (**the value of option will go here**)
You should use name instead of id. and do print_r($_POST) to check weather post data coming or not. also you dont need javascript for this until you are using ajax to call your php script
like #Coder said you the inputs send to the server with it's name attribute not id attribute
you should change the select element to
<select class="form-control" id="mySelect" name="my_select" onchange="option()">
and retrieve it's value with
$_POST['my_select'] // if you use POST method on form submition
$_GET['my_select'] // if you use GET method on form submition
$_REQUEST['my_select'] // if you accept any method
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.
I have a javascript using send text and photo, my problem is photo not send in my directory folder and empty column photo in database.
How to fix this? I'm confused :(
This is my screenshot result
index.php
<script>
$(function () {
$('#fr_testi').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'testi.php',
data: $('#fr_testi').serialize(),
success: function () {
document.getElementById("sc_testi").innerHTML = "Succes :)";
$('#nama_testi').val("");
$('#status_testi').val("");
$('#foto_testi').val("");
$('#komentar_testi').val("");
}
});
});
});
</script>
<form method="POST" id="fr_testi" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Nama</label>
<div class="controls">
<input name="nama" id="nama_testi" maxlength="100" type="text" required>
<input type="hidden" value="<?php echo $sk->kode?>" name="kode">
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<input id="status_testi" name="status" maxlength="100" type="text" required>
</div>
</div>
<div class="control-group">
<label class="control-label">Foto</label>
<div class="controls">
<input name="foto" id="foto_testi" type="file" required>
</div>
</div>
<div class="control-group type2">
<label class="control-label">Komentar</label>
<div class="controls">
<textarea maxlength="250" id="komentar_testi" name="komentar" required></textarea>
</div>
</div>
<center>
<button type="submit" class="button button_type_2 button_grey_light">Send</button><br/><br/>
<font color="green" id="sc_testi"></font>
</center>
</form>
testi.php
<?php
include "element/koneksi.php";
$nama = $_POST['nama'];
$kode = $_POST['kode'];
if ($nama!=NULL or $kode!=NULL) {
date_default_timezone_set("Asia/Jakarta");
$tglnya = date("Y-m-d");
$status = $_POST['status'];
$komentar = $_POST['komentar'];
$warna = "#52B3D9";
$kon = "NO";
$namafile_tmp = $_FILES['foto']['tmp_name'];
if($namafile_tmp){
$namafile = $_FILES['foto']['name'];
$file = $kode."_".$tglnya."_".$namafile;
copy($namafile_tmp, "images/sekolah/testimoni/{$file}");
unlink($namafile_tmp);
}
$query= "INSERT INTO sekolah_testimoni VALUES(id_testi,'$kode','$nama','$komentar','$status','$file','$warna',now(),'$kon','$kon')";
mysql_query($query);
}
else
{
echo "<script language='JavaScript'>window.history.back() </script>";
}
?>
The jquery method serialize doesn't include input file type.
If you just want to register filename on DB, you can use JS like below instead of serialize.
sendData = "";
$.each($("#formulario input, #formulario select"), function () {
if ($(this).prop("type") == "submit") return;
sendData += sendData!=""?"&":"";
sendData += $(this).prop("name") + "=" + $(this).val()
});
But if you want to upload file, save on the server and then register the location on DB, you should post directly from HTML or use FormData javascript object to perform this task.
fileInputElement = document.getElementById("yourFileInputID");
var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
// if you need to upload multiple files you should loop through the fileInputElement.files array, appending one by one
var request = new XMLHttpRequest();
request.open("POST", "http://yourURL/");
request.send(formData);
Unfortunately this method doesn't work on old browsers. To get upload working on those you should use an iframe solution (post form to an invisible iframe without leaving the page).
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.