sending the cart details through php mail -ajax - javascript

Im working on a JS shopping cart site and I am trying to send the cart details to mail at the check out function using php mail,here im passing my cart details to php via ajax.
in php when try to send all the cart values using foreach im only able to recive the just last row of cart as foreach is repalcing the previous value
how do i retrive the cart values and send them in a format
js
function SendMail() {
var tableContent = localStorage.getItem('productsInCart');
$.post('read.php', {tableContent: tableContent}, function (data) {
console.log(tableContent);
});
}
php
if (isset($_POST['tableContent'])) {
$tableContent = json_decode($_POST['tableContent']);
foreach ($tableContent as $tableContent) {
$name = ($tableContent->name);
$price = ($tableContent->price);
$quantity = ($tableContent->inCart);
}
$mailTo = "xxxxxxxxxxxxx";
$Subject = " order details ";
$headers = "from :" . $contact;
$txt = "New registration \n Item:" . $name . "\n Quantity:" . $quantity . "\n Price:" . $price . "\n\n\n CUSTOMER DERAILS\n\n Name:" . $contact . "\n Reg No:" . $reg;
mail($mailTo, $Subject, $txt, $headers);
header("location: read.php?mailsend");
}

You're currently overwriting the same variables on each iteration of the loop, which is why they will only contain the last entry.
You should append the values instead, doing something like:
$tableContent = json_decode($_POST['tableContent']);
// Define a variable to store the items in
$items = '';
// Let's add a total sum as well
$total = 0;
// Let's also use different variable names here
foreach ($tableContent as $item) {
// Append to the variable (notice the . before the =)
$items .= 'Item: ' . $item->name . "\n";
$items .= 'Quantity: ' . $item->inCart . "\n";
$items .= 'Price: ' . $item->price . "\n\n";
// Add the price to the total (I'm assuming that the price is an integer)
$total += $tableContent->price;
}
Now when outputting the email body, we have all the items and the total in those variables:
$txt = "New registration \n" . $items . "Sum total: " . $total . "\n\n\n CUSTOMER DERAILS\n\n Name:".$contact."\n Reg No:".$reg;
As you can see, I changed the layout of the mail a bit since the cart seems to be able to contain several items while your email body was written as if only could contain one.
A warning about this approach
You shouldn't get the cart values, like name and price, from the client in a POST request like this. The client should only send the item id and quantity and then you would fetch the name and price from a database or similar in the backend. Otherwise, anyone can modify the price to be anything they want before it's posted. Never ever trust user data.

Related

AJAX won't call the PHP file when using $.post()

I have been trying to export a search result to an Excel file (type .xls), before this, I have been using purely PHP and it works.
However, my client requests to have "live search" effect, so I have to shift to AJAX.
Here is the starting point: User clicks "Export" button, and in the javascript (in the main php file viewdata.php):
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
....
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$.post("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
cbXDate is an input field of type date to let user choose a date from whence to export the data, and cbsearch is a text input field to include a search keyword. console commands are added to see where the code execution has went through.
in the export_contact.php:
<?php
echo '<script> console.log("Export PHP activated."); </script>';
?>
I removed the PHP MySQL data selection code just to debug the problem (full source code below).
Problem is: export_contacts.php is never called. The "Export PHP activated" message never popped up in the console. The console only displayed the data values and "Completed", i.e. export_contacts.php was never called.
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Complete
Out of curiosity, I replaced $.post(...) with $("#export_div").load(...) and the console message showed up:
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$("#export_div").load("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Export PHP activated.
Complete
But this is not what I want, I want to write the output to a file, not display them in a div in the webpage. However, the data shown in the "export_div" div is correct, but the header part is not running, I know the quirkyness in header() calls, but I didn't output anything before the header() calls (unless output from the calling viewdata.php file also count?), here is the full export_contacts.php source code:
<?php
include("./php/auth.php");
$guid = $_POST['sGuid'];
$date = $_POST['sDate'];
$skey = $_POST['sKey'];
$searchKey = $_POST['sKey'];
if($searchKey == "")
{
$skey = "'%'";
}
else
{
$skey = "'%".$searchKey."%'";
}
$sql = "SELECT *, FROM_UNIXTIME(ROUND((date / 1000), 0) + 46800) AS date
FROM contacts
WHERE owner = '$guid' AND contact <> ''
AND (contact LIKE $skey OR name LIKE $skey) ";
if(!empty($date))
{
"AND date >= '$date' ";
}
$sql .= "ORDER BY contact;";
if($result = mysqli_query($link, $sql))
{
$columnHeader = '';
$columnHeader = "Owner" . "\t" . "Contact" . "\t" . "Name" . "\t" . "SaveDate" . "\t";
$setData = '';
while($rows = mysqli_fetch_assoc($result))
{
$rowData = '';
foreach ($rows as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
// in case of .load() used,
// code works up until this point
// code doesn't work since here...
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=contact_".$guid.".xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
// until here
// this will show in console in case of .load() used
echo '<script> console.log("Export PHP activated."); </script>';
die();
}
else
{
echo "<script>window.alert('ERROR: '".mysqli_error($link).")</script>";
}
include("./php/cleanup.php");
?>
This code is working in the pure PHP version. I don't know why this header() part isn't working in here, could be due to its output got redirected to the div?
To make things clear, my question is: "Why $.post(...) isn't calling the PHP file, while $("#export_div").load(...) did?".
The header() part is just a sub question, and is fine if it's ignored.
As Kmoser pointed out, I was doing things wrong. None of the tutorial sites I visited did mention that $.post() will not return any result at all, while my php code is expecting the return of the search result and write them in a file in the header() calls.

how to store and edit the mobile number with country codes?

I've asked once but I didn't get the answers.
var phoneno = /^\+?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
this is how I learnt to validate the numbers + error and...
I also have the Mobile bigint(20) & country varchar(200), in my table "users".
what I want to do is to use another file "countries.php" to get their codes in mobile input in "signup.php" page and store them both into the database.
for example, user chooses 'US +1' the country code will appear in mobile section.
$countryArray = array(
'AD'=>array('name'=>'ANDORRA','code'=>'376'),
'AE'=>array('name'=>'UNITED ARAB EMIRATES','code'=>'971'), ...
function countrySelector($defaultCountry = "", $id = "", $name = "", $classes = ""){
global $countryArray; // Assuming the array is placed above this function
$output = "<select id='".$id."' name='".$name."' class='". $classes."'>";
foreach($countryArray as $code => $country){
$countryName = ucwords(strtolower($country["name"])); // Making it look good
$output .= "<option value='".$code."' ".(($code==strtoupper($defaultCountry))?"selected":"").">".$code." - ".$countryName." (+".$country["code"].")</option>";
}
$output .= "</select>";
return $output; // or echo $output; to print directly
}
not to mention I downloaded the file zip. and I don't really know how to add or use the " use", please be more specific, like give with examples. thanks

Updating MySQL Database with checkboxes and PHP

I am trying to update a MySQL database with checkboxes and PHP. I have read a lot of code examples online and read many questions on here but I seem to be stuck at the last hurdle.
My code first queries MySQL to bring back a list of users and then a checkbox (which is either 0 or 1 in MySQL) next to each one, indicating whether or not the user is completed.
What I am wanting to do is when the checkbox is checked, for that to update the MySQL database and update the column with 1, or if it is unchecked, for it to change the column to 2.
Here is my code so far:
HTML Snippet (Checkboxes):
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Firstname'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Department'] . "</td>";
echo "<td>" . $row['RequestedBy'] . "</td>";
echo "<td>" . $row['StartDate'] . "</td>";
echo "<td class='tbl-chk'> <input type='checkbox' name='WSCompleted' value='"; echo $row['ID'] . "'" ; if ($row['WSCompleted']=='1') { echo "checked='checked'";} echo "/></td>";
Here is my jQuery that successfully retrieves the values and IDs and then posts them:
$(document).ready(function(){
$('input[name=WSCompleted]').click(function(){
var wsCompleted = $(this).is(':checked') ? 1 : 0;
var wsCompletedID = $(this).attr('value');
$.ajax({
type: "POST",
url: "/usr-handler.php",
data: {id: wsCompletedID, wsCompleted: wsCompleted},
success: function(){
$('div.success').fadeIn();
}
});
return true;
});
});
And finally here is a snippet of my PHP:
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['wsCompletedID'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
I am setting the value of the checkbox to what is actually the row ID in MySQL, then I can use the checkbox value to select the correct row in MySQL, and update it.
The problem I am having is that currently, how the code is, I get the following response from FireBug:
Unidentified index: WSCompletedID
After looking online it was suggested to change:
$id = $_POST['wsCompletedID'];
To:
$id = (ISSET($_POST['wsCompletedID']));
But doing so clears the error message, but then doesn't actually update the value on MySQL.
If I manually set the $id to something, the update works, but obviously that isn't right as it would only ever update the ID I have chosen it to.
I am completely stumped as to what is causing the problem. I have tried finding out online but cannot get anywhere with it.
Any help is greatly appreciated.
Thank you
You are loading data here in your javascript AJAX code
data: {id: wsCompletedID, wsCompleted: wsCompleted},
This will create the following $_POST array
id => whatever was in wsCompletedID
wsCompleted => whatever was in wsCompleted
So your PHP code should be looking for $_POST['id'] and $_POST['wsCompleted'] as these are the names you have given in your data:...
$wsCompleted = $_POST['wsCompleted'];
$id = $_POST['id'];
$query = "UPDATE newusers SET WSCompleted = '$wsCompleted' WHERE id = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
HOWEVER: Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements

How to retrieve data from .php and display in <select> within Cordova hybrid app?

I am writing a hybrid app using Visual Studio with Cordova exetnstion and trying to pull data from www.a.com/b.php
My b.php code is:
<?php
// Connect to database server
mysql_connect("http://www.yo.com", "ya", "ye") or die (mysql_error());
// Select database
mysql_select_db("oh") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Properties ORDER BY number DESC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
echo '<select name="Address" id="address_search" style="width:282px; display:block;" required>';
while($row = mysql_fetch_array($rs))
{
// Write the value of the full address including unit code, address, city, state, zipcode (which is now in the array $row)
echo '<option value="'. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .'">'
. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .
'</option>';
}
echo '</select>';
// Close the database connection
mysql_close();?>
I already add select tag form directly in php code, but I don't know how to display the whole select box (with options being retrieved data) in .html.
Any help or tutorial? Thanks.
I have solved this issue like this:
First, in the server side-code (php in this case), in "file.php", I have an array with the database elements and I do the following:
$arrayElements = json_encode($arrayElements );
echo $_GET['jsoncallback'] . '(' . $arrayElements . ');';
After that, in the app js code, I use jQuery method $.getJSON() for getting the php array we prepare before. When the function get the server answer, then execute the code inside. Note that the variable "respuestaServer" is the array you have sent from php file, so you can go throw it with a loop and taking its values to your select (if you need to pass variables to your php file and receive them via GET just add the js variables inside the {}, in this example I send the variable datosUsuario and in php I receive it $_GET['usuario']).
var archivoValidacion = "http://example.com/file.php?jsoncallback=?";
var select = document.getElementById("idSelect");
$.getJSON( archivoValidacion, { usuario:datosUsuario ,password:datosPassword})
.done(function(respuestaServer) {
for(var i = 0; i < respuestaServer.length;i++){
var option = document.createElement("option");
var textNode = document.createTextNode(respuestaServer[i]);
option.appendChild(textNode);
select.appendChild(option);
}
})
I hope this can help you. If you have some questions just tweet me #ulisesveraes ;)
it is not clear how you call this code
I suppose you do this with jQuery ajax function
so your code will like something this
$('box-selector').load('b.php');

How can I specify a specific value in a column retrieved via php?

I would like to add an if statement regarding the 'type' column. Is there something after the .attr('type') which will allow me to specify a particular value for type?
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var address = '<p>'+ $(this).attr('address') +'</p>';
var type = $(this).attr('type');
So $(this).attr('type'); is loading all the rows in my tables 'type' column value. eg:
Table
Name, Address, Type*
Name1, Address1, TypeA,
Name2, Address2, TypeB,
Name3, Address3, TypeA,
etc
How can I 'get access' to what actually the value of the 'type' column; eg. $(this).attr('type').<something>('TypeA');
Is this possible?
Edit2: map_process.php end
// Select all the rows in the markers table
$query = "SELECT * FROM markers";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo 'description="' . parseToXML($row['description']) . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
You have two options:
(1) If you have full control over the ajax page you are calling, the best solution would be to:
"send the selected checkbox value into map_process.php and get the
selected value from table and update the markers again in Map." –
Krish R
//jQuery
var cbVal = "TYPEA"; //Assign with checkbox value's associated string
$.get("map_process.php?checkboxval=" + cbVal, function (data)
{
//do something with the data returned
});
//PHP
$query = "SELECT * FROM markers where type = '".$_GET["checkboxval"]."'";
(2) If you don't have control over the source of the ajax call (for example from a third party source), OR you want to return all markers every time, consider using the jQuery Filter method.
//jQuery
var cbVal = "TYPEA"; //Assign with checkbox value's associated string
$(data).filter(function(index,val)
{
return $(val).attr('type') === cbVal;
}).each(function ()
{
//do something with the data returned
});
See the example for option (2) on this JSFiddle

Categories

Resources