I am using the following php code with a form which updates a table. However I want to add a javascript variable to the sql so that the variable will be added to a column in the database.
The variable is in a different file to the php.
php :=
$name = $_POST['firstname'];
$lastname = $_POST['lastname'];
$userAddress = $_POST['address'];
$userPostCode = $_POST['postcode'];
$delivery = $_POST['deliverytype'];
$sql = "INSERT INTO USERS (FIRSTNAME, SECONDNAME, ADDRESS, POST_CODE, DELIVERY_TYPE) VALUES ('$name', '$lastname', '$userAddress', '$userPostCode', '$delivery') ";
$conn->exec($sql);
i then want to add to that a totalcost variable from the following javascript that will go in Total_Order_Cost and $totalCost
here is the js function that i wish to take the variable totalPrice from
function displayBasket(){
basket = document.getElementById("basket");
string = "";
var basketStorage = localStorage.getItem("basket");
jsonBasket = JSON.parse(basketStorage);
var totalPrice = 0;
itemTotal = 0;
for (var property in jsonBasket){
var qPrice = jsonBasket[property ].quantity * jsonBasket[property ].cost;
var total = jsonBasket[property ].quantity;
string += "<section id='basketPageSection'>";
if(jsonBasket.hasOwnProperty(property )){
string += "<p>Item: " + jsonBasket[property ].name + "</p>";
string += "<p>Price: £" + jsonBasket[property ].cost + "</p>";
string += "<p>Quantity: " + jsonBasket[property ].quantity + "</p>";
}
totalPrice += qPrice;
itemTotal += total;
string += "</section>";
}
string += "<section id='basketSection'> <h3> Total Cost: £" + parseFloat(totalPrice).toFixed(2) + "</h3></section>"
basket.innerHTML = string;
displayQuant();
}
You could use a hidden input field change it value attribute and submit along with rest of the form.
<input type="hidden" name="calc" id="calc" value="">
Use Jquery to set its value
$('#calc').val(someval);
Update Javascript
document.getElementById("calc").value="Your Value";
You can use ajax.
It is the best solution for me :
Use a code like that in your javascript :
value1= ... ; // firstname
value2= ... ; // lastname
$.ajax({
type: 'post',
url: 'post.php',
data: 'firstname='+value1+'&lastname='+value2+'&address= ....,
success: function () {
alert('data sent');
}
});
Another Way
$.ajax({
type: 'post',
url: 'post.php',
data: $('#formID').serialize()+"&extraval=1&extraval2=2...",
success: function () {
alert('data sent');
}
});
Related
I am new in php . I have the following code to retrieve categorytype data from database?. I want to add them into php object for temporary using while loading page. First, I want to load all predefined data, then i will use it when i click function. Could you enlighten me how to create it
categoryDao.php
namespace category;
use Exception;
use PDO;
class categoryDao{
public function categorytype(PDO $connection){
$conn = $connection;
try {
$conn = $connection;
$sql="SELECT * FROM `tb_category` WHERE id != parent_id;";
$categorytype = $conn->prepare($sql);
$categorytype->execute();
$data1 = array();
while (
$result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
return $data1;
} catch (Exception $e) {
echo $e;
throw $e;
}
}
}
categoryservice.php
use category\categoryDao;
require '../dao/categoryDao.php';
require 'Dao.php';
class categoryService{
public function categorytype(){
$dao = new Dao();
$conn= $dao->connect();
$conn->beginTransaction();
$categoryDao = new categoryDao();
//$data1 = array();
$data1=$categoryDao->categorytype($conn);
return $data1;
$dao->disconnect($conn);
}
}
categorytypecontroller.php
<?php
require '../service/categoryService.php';
require '../service/categoryService.php';
$categoryname = #trim(stripslashes($_POST['category']));
$category = new categoryService();
//$ctype = array();
$ctype = $category->categorytype();
$return["json"] = json_encode($ctype);
echo $return["json"];
Head.php
function categorytype() {
//var hosname =window.location.protocol + "//" + window.location.hostname + window.location.pathname;
var hosname1 = window.location.protocol + "//" + window.location.hostname+ "/servicegateway/sgw/modules/controller/categorytypecontroller.php";
alert (hosname1);
//var ur = hosname + "/modules/controller/categorycontroller.php";
$.ajax({
url:hosname1 , //the page containing php script
type: "POST", //request type,
dataType: 'json',
data: '',
success:function(data1){
alert(data1);
var obj =data1;
// var leng = Object.keys(obj).length;
var areaOption = "<option value=''>Select Category </option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#c_type").html(areaOption);
}
});
}
A couple of things. If you want the data to be an array of records, you'll probably want to change this part:
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
as that is putting all the fields, one after the other, into a normal array.
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = array(
'id' => $result['id'],
'c_name' => $result['c_name']
);
}
That will create a small associative array of the id and name fields and put it into another array, with the other records. PHP associative arrays will turn into Javascript objects when sent via ajax.
Then, in Javascript, you'll want to make use of those objects to create your options, so:
areaOption += '<option value="' + obj[i].id + '">' + obj[i].c_name + '</option>'
$('#save').click(function() {
var loopvalue = "<?php echo $count; ?>"
var datajson = '[';
//alert(loopvalue + "length of array")
for (i = 1; i < loopvalue; i++) {
var fetchid = '.A' + i;
var fetchid_code = '.C' + i;
datajson = datajson + "{" + "maincode :" + $('#company').val() + ",acode : " + $(fetchid_code).text() +
" , Amount :" + $(fetchid).val() + ", periodfrom :" + $('#dFrom').val() +
", periodto : " + $('#dTo').val() + ", danounc : " + $('#dano').val() +
", period : " + $('#period').val() + ", fyear : " + $('#fyear').val() +
", frequency : " + $('#freq').val() + ", stype : " + $('#stype').val() +
", sseq : " + $('#sseq').val() + " }, "
}
datajson = datajson + ']'
//console.log(datajson);
$.ajax({
type: 'POST',
url: 'jsondecode.php',
data: {
datajson: JSON.stringify(datajson)
},
//data:postArray,
dataType: "json",
success: function(data) {
console.log("success:", data);
},
failure: function(errMsg) {
console.error("error:", errMsg);
}
});
});
first i remove last comma in json object and second when i am calling ajax page but it is displaying NULL value in jsonencode.php page how can I solve this problem any can suggest me this is my server site script now
<?php
header('Content-Type: application/json');
$data = json_decode($_POST["datajson"]);
// will echo the JSON.stringified - string:
echo $_POST["datajson"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach ($data as $Object) {
echo "maincode: " . $Object->maincode . ", Acode: " . $Object->acode . "<br/>";
}
?>
Or maybe you should use actual object instead of string-concatenation
Try this
var datajson = [];
for (i = 1; i < loopvalue ; i++)
{
var fetchid = '.A' + i;
var fetchid_code = '.C' + i;
var obj = {
maincode : $('#company').val(),
acode : $(fetchid_code).text(),
Amount : $(fetchid).val(),
periodfrom : $('#dFrom').val(),
periodto : $('#dTo').val(),
danounc : $('#dano').val(),
period : $('#period').val(),
fyear : $('#fyear').val(),
frequency : $('#freq').val(),
stype : $('#stype').val(),
sseq : $('#sseq').val()
}
datajson.push( obj );
}
datajson = JSON.stringify( datajson ); //converting to string here
Before you append ] to datajson, substring that value to remove last ,. That is.
datajson = datajson.toString().subString(0, datajson.toString().length - 1);
Then Append ]
It is not needed to use JSON.stringify(datajson) in data attribute of $.ajax because you are sending the json string. not json object.
Hope this helps
Write the single elements of your look into an array and then join the elements.
See here: javascript join
But of course building JSON yourself is not necessary. Use JSON.stringify for that.
To start i'm using jquery,php,sql,html & css.
I am facing a issue that is giving me serious problem. I am trying to run a $.post function to retrieve values from my database of a party group(4 members value stored in 4 columns in the database. After retrieving the value, i run a while loop and append each value of the party onto a listview.
Then i send the current while loop value over to another $.post function to check for the rating score for the member i'm currently checking, and retrieve the result to display onto the li that i am currently appending.
This is what i have
$('body').on("pagebeforeshow","#p-partyDetail",function(){
var teamID = globalIndex;
var currentMem = "";
$.post("retrieveMemDetails.php",
{
teamID:teamID, // data to pass into php
username:globalUsername,
}, // data to pass into php
function(response)
{
var x = 1; // define value as 1
while(x<=4){ // if loop is below or equal to 4, run loop
//member = response.mem + x;
member = response['mem' + x]; // define member1 in variable,
currentMem = member;
console.log("current x value is " + x);
if(member !=""){
var y = x.toString();
console.log("y is " + y);
$.post("retrieveRatingDetails.php",
{
username:currentMem, // data to pass into php
}, // data to pass into php
function(response2)
{
$("p#" +y).html(response2.rating);
console.log("full name is " + response2.name + " rating is " + response2.rating);
console.log("retrieve rating valued:"+response2.rating+" to p#"+y);
console.log("end of loop cycle" + y);
}, 'json'
);
$("#partyDetail-listview").append('<li> <img src="images/final-fantasy-7-final-fantasy-vii-6973833-1024-768.jpg"> <h2>'+ member + '</h2> <p id="'+ x +'"></p> </li>').listview("refresh");
console.log("appended count:" + x);
}
x++;
}
}, 'json'
);
});
my php for retrieving member detail
include_once('db.php');
session_start();
$teamID = ($_POST['teamID']);
$username = ($_POST['username']);
$result = $db->query("SELECT * FROM `studentparty` WHERE `id` = '".$teamID."'");
$result3 = $db->query("SELECT *` FROM `userdetails` WHERE `username` = '".$username."'");
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_array($result);
$mem1 = $row["mem1"];
$mem2 = $row["mem2"];
$mem3 = $row["mem3"];
$mem4 = $row["mem4"];
$result2 = json_encode(array("mem1"=>$mem1, "mem2"=>$mem2, "mem3"=>$mem3, "mem4"=>$mem4));
echo $result2;
}
my php for retrieving rating scores
include_once('db.php');
session_start();
$username = ($_POST['username']);
$result4 = $db->query("SELECT * FROM `userdetails` WHERE `username` = '".$username."'");
if(mysqli_num_rows($result4)>0)
{
$row = mysqli_fetch_array($result4);
$rating = $row["Rating"];
$name = $row["FullName"];
$result5 = json_encode(array("rating"=>$rating, "name"=>$name));
echo $result5;
}
my member & rating are under different table so i called $.post twice.
Apparently after debugging for hours, i found out that it will loop through
console.log("current x value is " + x);
then
console.log("y is " + y);
then
console.log("appended count:" + x);
running through a total loop count of 4 before it run
console.log("full name is " + response2.name + " rating is " + response2.rating);
console.log("retrieve rating valued:"+response2.rating+" to p#"+y);
console.log("end of loop cycle" + y);
this caused the rating to only keep updating on the value y, as the flow of the function are already wrong.
My ideal flow is
-retrieve party member details from php
-while displaying mem1 from php using while loop, append a li only my ul.
-send the current mem1 data into my next $.post function to retrieve rating data
-update the li with the rating data
-end of loop and begin with member2
Can someone point out to me what wrong with my script? Thanks!
I strongly recommend that one ajax request is enough to get requested data. If you make inner ajax request, you have to wait other lines to be executed. Because it is asynchronous functions. You can also set your ajax call synchronously with the code as in below:
$.ajax({
...
async: false,
...
});
But then you have to wait until your callback function is executed. So, sometimes it is dangerous for your performance.
If you change your php side as in below, you will get an array with objects which have member and member's detail.
include_once('db.php');
session_start();
$teamID = ($_POST['teamID']);
$result_detail = $db->query("SELECT * FROM `studentparty` WHERE `id` = '".$teamID."'");
if(mysqli_num_rows($result_detail) > 0)
{
$data = array();
$mem = array();
$row = mysqli_fetch_array($result);
$mem[0] = $row["mem1"];
$mem[1] = $row["mem2"];
$mem[2] = $row["mem3"];
$mem[3] = $row["mem4"];
for($i = 0; $i < count($mem); $i++) {
$result_rating = $db->query("SELECT *` FROM `userdetails` WHERE `username` = '".$mem[$i]."'");
$rating_array = array();
if(mysqli_num_rows($result_rating) > 0)
{
$row2 = mysqli_fetch_array($result_rating);
$rating = $row2["Rating"];
$name = $row2["FullName"];
$rating_array = array("rating"=>$rating, "name"=>$name));
}
$data[$i] = array_merge(array("member" => $mem[$i]), $rating_array);
}
$result_json = json_encode($data);
echo $result_json;
}
I also adopted your javascript code to new response. I couldn't test both. I hope it will work well.
$('body').on("pagebeforeshow","#p-partyDetail",function(){
var
teamID = globalIndex,
currentMem = "",
callback = function(response) {
var member, id;
$.each(response, funciton(i, obj) {
member = obj['member'];
id = (i+1); // if you have ids for members, you can send in php additionally. it would be better than (i+1)
$("#partyDetail-listview").append('<li> <img src="images/final-fantasy-7-final-fantasy-vii-6973833-1024-768.jpg"> <h2>'+ member + '</h2> <p id="'+ id +'"></p> </li>').listview("refresh");
console.log("appended count:" + id);
if (member) {
$("p#" + id).html(obj['rating']);
console.log("full name is " + obj['name'] + " rating is " + obj['rating']);
console.log("retrieve rating valued:"+obj['rating']+" to p#" + id);
console.log("end of loop cycle" + id);
}
});
};
$.post("retrieveMemDetails.php",
{
teamID:teamID, // data to pass into php
username:globalUsername,
}, // data to pass into php
callback, 'json');
});
I have a dilema. I've created this order request page for a website I'm building, and here's how it works:
You check/uncheck core items, and based on it's state (active or unactive), it'll apply a true/false value to a boolean in the coresponding order.js. Likewise, it'll take desired unit count for other items, and your information, and apply them to variables.
It groups those variables into arrays and, right now, console.log() them.
Here's where the trouble comes...this is a snippet of the order.js file.
function compileInfo() {
console.log("compileInfo active");
var name = "Name: " + $("#name").val() + "\n";
var email = "Email: " + $("#email").val() + "\n";
var phone = "Phone: " + $("#phone").val() + "\n";
var weddingDate = "Wedding Date: " + $("#date").val() + "\n";
var comments = "Comments: " + $("#comments").val() + "\n";
var base = "Base Experience: " + $("#base").hasClass("active") + "\n";
var special = "Special Edition: " + $("#special").hasClass("active") + "\n";
var teaser = "Teaser Trailer: " + $("#teaser").hasClass("active") + "\n";
var raw = "Raw Footage: " + $("#raw").hasClass("active") + "\n";
var standard = "Standard Shipping: " + $("#standard").hasClass("active") + "\n";
var expedited = "Expedited Shipping: " + $("#expedited").hasClass("active") + "\n";
var dvd = "Standard DVD: " + a + "\n";
var br = "Standard Blu-Ray: " + b + "\n";
var dvdSe = "Special DVD: " + x + "\n";
var brSe = "Special Blu-Ray: " + y + "\n";
var info = new Array();
info[0] = name;
info[1] = email;
info[2] = phone;
info[3] = weddingDate;
info[4] = comments;
var services = new Array();
services[0] = base;
services[1] = special;
services[2] = teaser;
services[3] = raw;
var delivery = new Array();
delivery[0] = standard;
delivery[1] = expedited;
var extras = new Array();
extras[0] = dvd;
extras[1] = br;
extras[2] = dvdSe;
extras[3] = brSe;
var dataVar = info + "\n" + services + "\n" + delivery + "\n" + extras;
var dataVarJSON = JSON.stringify(dataVar);
console.log(dataVar);
$.ajax({
type: "POST",
url: "order.php",
data: {data : dataVarJSON},
success: function() {
console.log("SUCCESS");
}
});
}
function validate() {
var name = $("#name").val();
var email = $("#email").val();
var weddingDate = $("#date").val();
if (name === "" || email == "" || weddingDate == "") {
alert("You must complete all required fields to send this request.");
} else {
console.log("working");
compileInfo();
return true;
}
}
Here's my recieving PHP:
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
$body = json_decode(stripslashes($_POST['data']));
$to = "thekevinhaube#gmail.com";
$subject = "Order Request";
function sendInfo() {
mail($to, $subject, $body);
}
?>
Now, I'm far from a PHP expert. This is my first encounter with it, in fact. How can I get it to send. It seems to POST just fine, but isn't sending to the email adress listed. Any and all help is appreciated! Again, this is my first time with PHP, so...
You need to give sendInfo some parameters:
function sendInfo($to, $subject, $body) {
...
}
And don't try mail() on your localhost, try it - if possible - online.
I need little help.
First, I have page with some values from Database in form, like this:
out.println("<form method=\"post\" action=\"update.jsp?id=" +
rs.getString(1) +"\" onSubmit=\"return editF(this)\" id=\"editDiv"+ rs.getString(1) +"\" >" + SelectCat() +" </form>")
public String SelectCat()
{
String result = "<select name=\"category\" >";
try
{
String request = "SELECT * FROM cat";
Statement st = getConnection().createStatement();
ResultSet rs = st.executeQuery(request);
while (rs.next())
{
result += "<option value=\"" + rs.getString(1) + "\">" + rs.getString(2) + "</option>";
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
result += "</select>";
return result;
}
And my javascript function is
function editF(form)
{
alert("a");
string header = form.header.value;
string text = form.text.value;
string category = form.category.selectedIndex.value;
var e = document.getElementByName("category");
//var category = e.selectedIndex;
form.action = form.action + "&header="+header+"&text="+text+"&categoryID="+category;
return true;
};
But I can't get selected value.
Can you help me?
Thanks!
var category = form.category.options[ form.category.selectedIndex ].value;
Also, javascript is not a strongly-typed language, you cannot define its type when declaring it. Instead, use var.