didn't really succes with assigning values to new ids in my while(row) statement:
Here is an easy example, hope you understand what I want to do. Thanks
<?php...
$id=0;
while(rows = mysql_fetch_data){
$id = $id + 1;
$teamname = rows['team'];
?>
<script>
var team = '<?php echo $teamname; ?>';
var id = 'id_<?php echo $id; ?>';
//Here I want to save the teamnames as javascript variable "id_1", "id_2" etc, which I can use outside the while statement.
//For each row id = id_1, id_2, id_3, id_4.
//I want to make id_1 a variable which outputs teamname
//So that
//var id_1 = team; //team 1
//var id_2 = team; //team 2
<?php
}
?>
var id_1;
var id_2;
document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>
I would recommend using an array rather than individual variables, as you have a list of team names:
<?php
$teamnames = [];
while(rows = mysql_fetch_data){
$teamnames[] = rows['team'];
}
?>
<script>
var teamnames = <?php echo json_encode($teamnames); ?>;
</script>
Then you end up with a client-side JavaScript array of team names. While you could then output them with document.write, there's probably a better option.
But here's your document.write updated to use the array:
var n;
for (n = 0; n < teamnames.length; ++n)
{
// Note: There's almost certainly a better choice than `document.write`
document.write("Teamname " + (n + 1) + " = " + teamnames[n] + "</br>");
}
Replace your code with the following and it should give you the output that you're after...
<script>
<?php
//...
$id_counter = 1; //Initialise counter
while($row = mysql_fetch_assoc()){
echo 'var id_'.$id_counter.' = "'.$rows['team'].'";'; //Echo row in the format: var id_X = "team_name";
$id_counter++; //Increment the counter
}
?>
document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>
Related
I'm incorporating PHP code into JQuery like this:
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
/* This is the line */var c = $c;
$('#data').load('data.php?v=' + count + '&c=' + c)
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
})</script>";
The PHP variable shows as blue, there are no errors showing, but when I run it it refuses to work. I've tested everything else and I'm 100% sure PHP is the one causing the problem.
How can I fix this?
If $c is your php variable you will need to quote and join it inside an echo tag.
But as Carton (+1) said, is it a string, integer, object?
If it's an integer, this should work...
<?php
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
var c = " . $c . ";
$('#data').load('data.php')
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
});
</script>";
If it's a string this should work...
<?php
echo "<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
var count = ($('.data').length + 25);
var c = '" . $c . "';
$('#data').load('data.php')
$('.btn-data').click(function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c)
})
});
</script>";
If it's an object, you will have to parse the var or encode it.
Sometimes if you want to echo or return big blocks of html inside php, you can use an output buffer to capture the html, and then you can either return the html via a function, or echo it. This just makes your html easier to read when it's not wrapped inside echo quotes tags.
<?php
// c sting php var
$c = 'string';
// start output buffer
ob_start();
?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
let count = ($('.data').length + 25);
let c = '<?=$c?>';
$('#data').load('data.php');
$(this).on('click', '.btn-data', function() {
count = count + 25;
$('#data').load('data.php?v=' + count + '&c=' + c);
});
});
</script>
<?php
// store everything between ob_start() and here into a php variable
$script = ob_get_clean();
// return script html
return $script;
// or echo script html
echo $script;
// not both together obviously
?>
I am exporting WooCommerce orders to a google sheets using WooCommerce Webhooks and Apps Script
I have two queires
1) How do I reference WooCommerce "add-ons" data
2) Parent order ID is not showing in google sheet
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var timestamp = new Date();
var order_number = myData.number;
var parent_id= myData.parent_id;
var order_status = myData.status;
var billing_first_name = myData.billing.first_name;
var billing_last_name = myData.billing.last_name;
var billing_phone = myData.billing.phone;
var billing_email = myData.billing.email;
var order_total = myData.total;
var billing_address_1 = myData.billing.address_1;
var billing_address_2 = myData.billing.address_2;
var billing_city = myData.billing.city;
var billing_address = billing_address_1 + ", " + billing_address_2 + ", " + billing_city;
var billing_postcode = myData.billing.postcode;
var shipping_first_name = myData.shipping.first_name;
var shipping_last_name = myData.shipping.last_name;
var shipping_address_1 = myData.shipping.address_1;
var shipping_address_2 = myData.shipping.address_2;
var shipping_city = myData.shipping.city;
var shipping_address = shipping_address_1 + ", " + shipping_address_2 + ", " + shipping_city;
var shipping_postcode = myData.shipping.postcode;
var lineitems=""
for (i in myData.line_items)
{
var product_name = myData.line_items[i].name;
var itemName = myData.line_items[i].name;
var quantity = myData.line_items[i].quantity;
var linetotal = myData.line_items[i].total;
var product_items = quantity + " x " + itemName + ": £"+linetotal +"\n";
var lineitems =lineitems+product_items;
}
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([timestamp,order_number,parent_id,order_status,billing_first_name,billing_last_name,billing_phone,billing_email,lineitems,order_total,billing_address,billing_postcode,shipping_first_name,shipping_last_name,shipping_address,shipping_postcode]);
}
What is missing from your question is:
We don't know from from where and how you get the order data in javascript
We don't know where you need to display the order Number.
So we can only make a generic answer.
Also note that asking multiple questions at once is not allowed in StackOverFlow.
1) The WooCommerce add-ons data within an WooCommerce order is stored as order item custom meta data:
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// The loop to get the order items which are WC_Order_Item_Product objects since WC 3+
foreach( $order->get_items() as $item_id => $item ){
// Get the special meta data in an array:
$meta_data = $item->get_meta_data();
echo '<pre>'; print_r($meta_data); echo '<pre>'; // Testing raw output
// Get all additional meta data (formatted in an unprotected array)
$formatted_meta_data = $item->get_formatted_meta_data( ' ', true );
echo '<pre>'; print_r($formatted_meta_data); echo '<pre>'; // Testing raw output
// Get the specific meta data from a meta_key:
$meta_value = $item->get_meta( 'custom_meta_key' );
}
Related: Get Order items and WC_Order_Item_Product in WooCommerce 3
2) To get the parent order number from a subscription you will use:
From the subscription ID we can get the order ID very easily:
$order_id = wp_get_post_parent_id( $subscription_id );
From a WC_Subscription Object we can also get the order ID very easily:
$order_id = $subscription->get_parent_id();
Then from this order ID you can get the order number with:
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
$order_mumber = $order->get_order_number();
or with:
$order_mumber = get_post_meta( $order_id, _order_number, true );
I'm trying to populate a Drop-Down menu from a csv file located on a network share.
I've come as far to get the file to create all the options successfully when the file is in the wwwroot folder however, now I'm faced with the external url reference issue.
Ajax does not support local File:/// directories and when attempting to use the network share location it also fails: \\Server\Folder\File.csv
Is there any way to read the data from the csv file using php or other server-side language in order to perform my work on the data?
Code Below for your reference:
<script>
function SubmitBy(){
$.ajax({
url: encodeURI('./PrinterLookup.csv'),
success: function(data) {
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Looking for something like this,,, to bypass the ajax url limitation:
<script>
function SubmitBy(){
<?php
$Datapath = "\\Server\Folder\Document.csv";
$Data = file_get_contents($Datapath);
?>
var data = $Data;
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Any assistance on this will be greatly appreciated.
Thank you in advance.
in this line var data = $Data; you need to print $Data see below
<script>
function SubmitBy(){
<?php
$Datapath = "file:///Server/Folder/Document.csv";
$Data = file_get_contents($Datapath);
?>
var data = <?php echo $Data; ?> //correction here
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
Please check first this is .php file .
If this is .php file.
<?php
$Datapath = "\\Server\Folder\Document.csv";
$Data = file_get_contents($Datapath);
?>
<script>
function SubmitBy(){
var data = <?php print_r( $data ); ?>;
var splitData=data.split("\n");
for (var i = 0; i < splitData.length; i++) {
var colData = splitData[i];
var strucData = colData.substr(0, colData.indexOf("="));
$('#SubmitBy').append("<option value=\"" + strucData + "\">" +
strucData + "</option>");
}
}
});
}
</script>
I'm trying to make a simple "search" box using Javascript, AJAX, php and JSON. For this project, I'm just using the database "world" I downloaded from mqsql website.
I'm running into a problem when trying to extract the information from my database. It just takes the first line of information and then I get this
error: "SCRIPT5007: SCRIPT5007: Unable to get property 'Continent' of undefined or null reference
ajaj.js (65,3)"
Thanks in advance for any help you are able to give me!
Here is my ajaj.js code:
var ajaxRequest=new XMLHttpRequest();
var input;
var button;
function init(){
input = document.getElementById('search');
input.addEventListener("keyup", sendRequest, false);
button = document.getElementById('sendButton');
button.addEventListener("click", sendSecondRequest, false);
}
function sendRequest(){
ajaxRequest.onreadystatechange = getRequest;
var searchTxt = "country=" + input.value;
ajaxRequest.open("GET", "getCountries.php?" + searchTxt, true);
ajaxRequest.send();
}
function getRequest(){
if (ajaxRequest.readyState==4 && ajaxRequest.status==200){
var jsonObj = JSON.parse(ajaxRequest.responseText);
var dataList = document.getElementById('countries');
dataList.innerHTML="";
for(var i = 0; i<jsonObj.length; i++){
var option = document.createElement('option');
option.value = jsonObj[i]['Name'];
dataList.appendChild(option);
}
}
}
function sendSecondRequest(){
ajaxRequest.onreadystatechange = getSecondRequest;
var infoCountry = "country=" + input.value;
ajaxRequest.open("GET", "getCountries2.php?" + infoCountry, true);
ajaxRequest.send();
}
function getSecondRequest(){
if (ajaxRequest.readyState==4 && ajaxRequest.status==200){
alert(ajaxRequest.responseText);
var jsonObj2 = JSON.parse(ajaxRequest.responseText);
document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>";
document.getElementById("result2").innerHTML = "LANDSKOD: " + jsonObj2[2]["Continent"] + "<br>";
document.getElementById("result3").innerHTML = "LANDSKOD: " + jsonObj2[7]["Population"] + "<br>";
}
}
window.addEventListener("load",init,false);
It's here where the problem lies, I just don't know how to get it to work:
document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>";
document.getElementById("result2").innerHTML = "LANDSKOD: " + jsonObj2[2]["Continent"] + "<br>";
document.getElementById("result3").innerHTML = "LANDSKOD: " + jsonObj2[7]["Population"] + "<br>";
I've tried a few different solutions but I can't get it working, I've tried to combine the code into one line using:
document.getElementById("result").innerHTML = "LANDSKOD: " + jsonObj2[0]["Code"] + "<br>" + "Continent: " + jsonObj2[2]["Continent] + "<br>";
but that doesn't seem to work for me either.
Rest of my code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AJAX</title>
<script type="text/javascript" src="ajaj.js"></script>
</head>
<body>
<h1>Sök information om ett land</h1>
<input type="text" list="countries" id = 'search' placeholder="Land">
<datalist id="countries">
</datalist>
<button type="button" id="sendButton">Hämta information</button>
<p id="result"></p>
<p id="result2"></p>
<p id="result3"></p>
</body>
</html>
getCountries.php
<?php
include_once('db.inc.php');
$country = $_GET['country'];
// Kör frågan mot databasen world och tabellen country
$stmt = $db->prepare("SELECT * FROM country WHERE Name Like ? ORDER BY Name");
$stmt->execute(array("$country%"));
$tableRows = array();
// Lägger resultatet i vår array
$tableRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Här konverteras och skickas resultatet i JSON-format
echo json_encode($tableRows);
?>
getCountries2.php
<?php
include_once('db.inc.php');
$country = $_GET['country'];
// Kör frågan mot databasen world och tabellen country
$stmt = $db->prepare("SELECT * FROM country WHERE Name Like ? ORDER BY Name");
$stmt->execute(array("$country"));
$tableRows = array();
// Lägger resultatet i vår array
$tableRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Här konverteras och skickas resultatet i JSON-format
echo json_encode($tableRows);
?>
db.inc.php
<?php
define ('DB_USER', 'root');
define ('DB_PASSWORD', 'Abc12345');
define ('DB_HOST', 'localhost');
define ('DB_NAME', 'world');
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8';
$db = new PDO($dsn, DB_USER, DB_PASSWORD);
?>
EDIT: I just got the answer from the comments, the information is on the same row, not different, therefore it didn't work with
jsonObj2[2]["Continent"]
but it did work with
jsonObj2[0]["Continent"]
Thank you #sean!
It means that jsonObj2[2] isnt object. It seems like you dont have 3 rows (jsonObj2[2]) in database return array.
Try
jsonObj2[0]["Code"] + jsonObj2[0]["Continent"] + sonObj2[0]
["Population"]
It should work but dont know why you target to rows 0,2,7.
Hi I'm trying to get the xml data from php to javascript using DOM document and it keeps giving me : XML or text declaration not at start of entity error.(on firebug)
I tried saving it to a real xml file and it outputs a well formatted xml.
I guess the reason for this is white space on top of the xml file. I tried using ob_start(); and ob_end_flush(); but couldn't get that working
BTW I'm new to Ajax!
JS script
var xh = createRequest();
var xhrObject = false;
if (window.XMLHttpRequest)
{
xHRObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData()
{
if ((xh.readyState == 4) &&(xh.status == 200))
{
alert("hi");
var serverResponse = xh.responseXML;
var header = serverResponse.getElementsByTagName("good");
var spantag = document.getElementById("sp");
var x;
spantag.innerHTML = "";
x = "<table cellpadding='1' cellspacing='6' border='0'>";
x += "<tr><td>ID</td><td>price</td><td>quantity</td><td>Total</td><td>Remove</td></tr>";
for (i=0; i<header.length; i++)
{
var id = header[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
var price = header[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;
var qty = header[i].getElementsByTagName("quantity")[0].childNodes[0].nodeValue;
var total = header[i].getElementsByTagName("total")[0].childNodes[0].nodeValue;
if(qty=="0")
{
continue;
}
x += "<tr>"
+ "<td>" + id + "</td>"
+ "<td>" + price + "</td>"
+ "<td>" + qty + "</td>"
+ "<td>" + total + "</td>"
+ "<td>" + "<a href='#' onclick='AddRemoveItem(\"Remove\","+id+");'>Remove Item</a>" + "</td>"
+ "</tr>";
}
x += "</table>";
if (header.length != 0)
spantag.innerHTML = x;
}
}
PHP code
function toXml($shop_goods)
{
$doc = new DomDocument();
$goods = $doc->createElement('goods');
$goods = $doc->appendChild($goods);
foreach ($shop_goods as $Item => $ItemName)
{
$good = $doc->createElement('good');
$good = $goods->appendChild($good);
$title = $doc->createElement('ID');
$title = $good->appendChild($title);
$value = $doc->createTextNode($Item);
$value = $title->appendChild($value);
$price = $doc->createElement('price');
$price = $good->appendChild($price);
$value3 = $doc->createTextNode($ItemName["price"]);
$value3 = $price->appendChild($value3);
$quantity = $doc->createElement('quantity');
$quantity = $good->appendChild($quantity);
$value2 = $doc->createTextNode($ItemName["qty"]);
$value2 = $quantity->appendChild($value2);
$total = $doc->createElement('total');
$total = $good->appendChild($total);
$value3 = $doc->createTextNode($ItemName["total"]);
$value3 = $total->appendChild($value3);
}
$strXml = $doc->saveXML();
//echo("<br>----- DATA RECOREDED!!! ----");
return $strXml;
}
As others have noted, this could be an encoding issue.
Check your code for the Xml byte order mark.
Check the document is returning the correct mime type.
Not sure of your constraints but have you considered serializing your data to Json format. It's much easier to work with in the browser.
Finally consider using a library like JQuery to handle your ajax requests, much easier for cross browser compatibility.