I am trying to figure out how to update an URL that I am using to parse the XML (using simplexml_load_file()).
There is a button that has a $productid that is assigned to it by the user when they add their shortcode [show_cart_button productid=#].
//code for the button input that gets called
function print_add_cart_button($productid, $atts = array()) {
//some other form code for the button
$replacement .= '<input type="hidden" name"cart_product" value"' . $productid . '"/>';
return $replacement;
}
This is the function I am using to display and call the product information:
function show_shopping_cart_handler($atts) {
if (isset($_POST['cart_product'])) {
$id = "&PRODUCTID=" . $_POST['cart_product'];
// uses the input name from the button
}
$url = "https://secure.bmtmicro.com/cart?CID=2/WP" . $id;
$xml = simplexml_load_file($url) or die("error.");
foreach ($xml->producttable->row as $product) {
$output .= '<span>' . $product->productname . '</span>';
}
return $output;
}
The way the URL will work properly is to have a &PRODUCTID=(product#) added to the end of the URL. For example, if you click two different buttons, the URL should look like this: https://secure.bmtmicro.com/cart?CID=2/WP&PRODUCTID=1&PRODUCTID=2 (obviously 1 and 2 will need to display the buttons $productid number).
As you should be able to see from my code above, every time a button gets clicked, it just rewrites the URL and displays that one product, instead of adding a new one to the list. I tried to set the simplexml_load_file() into a foreach(), but that would not display any products when the button was clicked. Does anyone know a way I could get that URL to update/work properly?
Everytime
if (isset($_POST['cart_product'])) {
$id = "&PRODUCTID=" . $_POST['cart_product'];
// uses the input name from the button
}
Is called, it's overwriting $id. You need to get any existing values for the url.
You'll have to get all of the current values ($_GET['cart_productions']), throw them into an array, grab the new post, add it to the array and add all of them to them the url using http_build_query().
Related
I am building a WordPress shopping cart plugin that will tie into our server through a URL that will produce an XML page, which I will then have to parse the info to the WordPress page.
The server contains a session id (ShoppingCart.SessionID) that I need to get and use to help store which button was clicked and then pull the product info and add it to the cart. Each button is given a product id via shortcode (product_id="some#") from the page owner and that ID is pulled from the server to display the product's info.
How the buttons are set up:
In the shortcode file, I am using a function and have the button set up as
<?php
add_shortcode('add_cart_button', 'add_cart_button_handler');
function add_cart_button_handler($atts) {
extract(shortcode_atts(array(
'product_id' => '',
), $atts));
return print_add_cart_button_for_product($product_id, $atts);
}
In the main plugin file:
This file handles the printing of the button and the function to display the cart
<?php
session_id();
session_start();
// This function prints the button with its assigned $product_id
function print_add_cart_button_for_product($product_id, $atts = array()) {
$replacement .= '<form method="POST" class="cart-button-form" style="display:inline" action="">';
$replacement .= '<input type="hidden" name="bmt_cart_product" value="' . $product_id . '" />';
$replacement .= '</form>';
$replacement .= '</div>';
return $replacement;
}
Here is the function for what is supposed to be displaying the cart/product info:
function show_shopping_cart_handler($atts) {
$output = "";
$form = '';
$output .= '<table style="width: 100%;">';
$output .= '<tr class="cart_item_row">
<th class="cart_item_name_th">' . (__("Item Name", "wordpress-simple-paypal-shopping-cart")) . '</th><th class="cart_price_th">' . (__("Price", "wordpress-simple-paypal-shopping-cart")) . '</th><th></th>
</tr>';
# For now, I am using this to print the headers that display the
# ShoppingCart.SessionID="somevalue", but on every button click it changes the value of the session id.
if (isset($_POST['add_cart_submit'])) {
// The server reads the ID from "&PRODUCTID=product#"
$id = "&PRODUCTID=" . $_POST['cart_product'];
$url = "https://secure.bmtmicro.com/cart?CID=2/WP" . $id;
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'GET',
'content' => http_build_query($data)
)
);
//$context = stream_context_create($options);
$context = stream_context_set_default($options);
$output .= file_get_contents($url, false, $context);
}
print_r(get_headers($url));
$output .= '</table>';
return $output;
}
What the XML page looks like with an example product
Not sure if this is needed, but the more info provided, the better (right?). The product ID that is sent will populate these fields and keep adding a new row and then I will parse the necessary fields to the WordPress page.
<shoppingcart sessionid="88582813">
<producttable>
<row number="0">
<productid>22804</productid>
<productname>XFree86 CD</productname>
<quantity>1</quantity>
<productprice>$15.00</productprice>
<discount>$0.00</discount>
<rowtotal>$15.00</rowtotal>
</row>
</producttable>
</shoppingcart>
I am pretty new to PHP and learning as I go (reading/research), but have not been able to find the solution or steps to tackle my issue. Essentially, I believe my question should be (in short):
How can I grab the ShoppingCart.SessionID from the 3rd party server and use it to populate the cart without refreshing the Session so more than one product will display when more than one button is clicked? Also, is there a better/more productive way to accomplish what I am trying to do?
Thanks in advance and let me know if there's any info I need to add to the question!
In case anyone comes across this with a similar issue:
My way around this was to send the button data to an <iframe> and then set the <iframe> to width="0" height="0".
Example code:
<form method="POST" action="URL" target="the_iframe">
// add some <input> fields data
</form>
<iframe type="hidden" name="the_iframe" width="0" height="0"></iframe>
Not sure if this is THE BEST way to do it, but it works and I was able to add some JQuery to manipulate things even further (I tried using AJAX before this, but the server was set to "same origin", so the data wouldn't send from another URL).
I'm working with Selectize.js currently and am stuck on a problem relating to HTML entities not displaying correctly in Selectize fields, and therefore failing checks after submission. We use PHP on the backend and run every Selectize option through htmlspecialchars($option);. We then export the PHP array to a JSON array in preparation for adding it to the Selectize script/field.
//Array of options
$options = getOptions();
$optionsArray = array();
foreach($options as $item) {
$optionsArray[] = array('text' => htmlspecialchars($item), 'value' => htmlspecialchars($item));
}
//Create html script to run selectize initialization
$htmlcode = "<script>";
...
$htmlcode .= "var optionList = " . json_encode($"optionsArray") . ";";
$htmlcode .= "$('#selector').selectize({ options: optionList });";
...
$htmlcode .= "</script>";
The point here is to protect against malicious entries by encoding. This typically wouldn't be a problem, as browsers will detect the entities and convert them automatically (ie. will detect & and display as &. However, that is NOT happening inside the selectize. As you can see in the image below, outputting an option with an ampersand displays correctly on the page, but it doesn't display accurately in the Selectize field.
Example:
The problem then becomes larger, as we are comparing the selected item against the database after submission, to ensure that the selected entry actually exists. If the entry testOption&stuff actually exists, the form submission will check testOption&stuff against it, and will obviously fail the check.
//For simplicity, checking against static option
var $selectedOption = $_POST["options"];
if ($selectedOption == "testOption&stuff") {
//Do success
} else {
//Do failure
}
How can I resolve this and make it so that the Selectize field will store and display the correct entry (ie. &)?
Thanks!
I've seen a solution here that I, quite frankly, don't understand.
On the administration side of a website I'm working on, an administrator can edit blog posts. When the administrator goes to the page to edit the blog post, it also displays all of the comments on that post. Instead of adding a new table for each new blog post which contains comments, I simply created one table which holds all the information for the blog post, including a column for the comments.
Comments and comment-content is delimited. I.E. internally, a blog post comment column would look similar to this...
Name:Content:Email>Name2:Content2:Email
Etc.
This is how I display the comments on the admin page:
$post_query = "SELECT * FROM `$blog_table` WHERE id=$identifier";
$post_result = $connection->query($post_query);
$post = $post_result->fetch_assoc();
$comments_value = $post["comments"];
$original_comments_array = explode(">", $comments_value);
$comments_array = [];
foreach($original_comments_array as $comment) {
$individual_comment_array = explode(":", $comment);
$comments_array[] = $individual_comment_array;
}
foreach($comments_array as $index=>$comment) {
if ($comment_deletions_array[$index] === $index) {
$checked = "checked";
}
echo '<div class="content-border comment-margin"><span class="comment-name">';
echo $comment[0];
echo '</span><br /><p class="comment-content">';
echo $comment[1];
echo '<br /></p>';
echo $comment[2];
echo '<br /><br /><input name="comment_deletions[]" type="checkbox" value="' . $index . '" ' . $checked . '/> Delete This Comment';
echo '</div>';
}
As you may have noticed from the code above, each comment renders with its own checkbox input, the value of which is determined by the index.
Each checkbox shares the same name. I get all the values of the checkboxes like this:
$comment_deletions_array = $_POST["comment_deletions"];
In the snippet I provided earlier, there is an if statement within the foreach loop which determines if the comment was marked for deletion, and if so checks the check box. (This function is to replace the user's input if there was an error.)
The problem is that the indexes do not line up. If there is a checkbox which is not checked, it does not return false or null or anything of the sort to the $comment_deletions_array rather the array is just populated by value of the next input which WAS checked.
Is there a way I can return a value if the checkbox is not checked in order to maintain the correct index?
I am trying to dynamically build a drop down menu using PHP. The idea is: the elements are formed from a loop which calls and array. If the array element matches the data held in session then it adds the "selected" attribute to the tag, meaning that the page displays the previously selected option.
I have tried to include one complete set of code here, all the way from defining the variables from session data to echoing the HTML for the form element.
It doesn't currently work - the drop down menu appears, but is blank, and has no options. I've debugged it with ideone and it seemed to run successfully, and I can't see where I am going wrong, however this is my first PHP function! So I'm sure I've screwed it up somehow :)
Any help much appreciated.
<?php
session_start();
//if the session data has been set, then the variable $sv_02 is defined
//as the data held in the session under that name, otherwise it is blank
if (isset($_SESSION['sv_02'])) {$sv_02=$_SESSION['sv_02'];} else {$sv_02="";}
//define the array
$dm_sv_02 = array('-Year','-2012','-2011','-2010','-2009');
//create the function
function dropdown($dropdownoptions, $session_data)
{
foreach($dropdownoptions as $dropdownoption){
if($session_data == $dropdownoption){
echo '<option value="' . $dropdownoption . '" selected>' . $dropdownoption . '</option>';
} else {
echo '<option value="' . $dropdownoption . '">' . $dropdownoption . '</option>';
}
}
}
//echo the HTML needed to create a drop down, and populate it with
//the function which should create the <option> elements
echo '<select name="sv_02">';
dropdown($dm_sv_02, $sv_02);
echo '</select>';
?>
Try this:
foreach ($dropdownoptions as $dropdownoption) {
echo ($dropdownoption == $sv_02) ? "<option selected=\"selected\" value=\"$dropdownoption\">$dropdownoption</option>" : "<option value=\"$dropdownoption\">$dropdownoption</option>";}
This turned out to be a result of the fact I was using {smarty} tags to build my php, the code was as written but only worked when it was all included in one smarty tag, I'm not sure I understand why that should be the case but in any regard it was fixed by including it all in one tag.
I have an onclick event called in a PHP foreach loop for several items whose author name I need to click. Only one name was getting generated, so I know that I must have a unique id for each HTML element. I already have a variable $objkey for a counter used in the loop so I appended it to the id.
<?php
//This is the item that appears in the loop.
//Currently, clicking on each one that is generated only generates the first author name
//The correct author as passed by PHP displays in the loop.
//$closest is the value of the author's name.
echo 'Click name to add <span><button id="closest' . $objkey . '" onClick="setAuthor()">' . $closest . '</button></span><br />';
?>
I have done a print_r('$objkey); and the appropriate value for the counter is getting passed along.
I want the value of this button element $closest to be passed to an input field. I have appended the variable to both the input's id and name elements (not sure if that helps) (UPDATE: There is an input field for each of the authors that needs to get the value):
<?php
echo '<input id="author_name' . $objkey . '" type="text" name="author_name' . $objkey . '" value="' . $author . '" />';
?>
Where I'm stuck is with my function:
<script type="text/javascript">function setAuthor() {
var author = document.getElementById("closest").innerHTML;
window.alert(author);
document.forms["myform"].elements["author_name"].value = author; }</script>
How do I create a variable in the function for the unique ids so that each looped item generates distinct names?
One way to do it is to pass this to the the setAuthor function:
<?php
//This is the item that appears in the loop.
//Currently, clicking on each one that is generated only generates the first author name
//The correct author as passed by PHP displays in the loop.
//$closest is the value of the author's name.
echo "Click name to add <button id='closest_{$objkey}' onClick='setAuthor(this)'>{$closest}</button><br/>";
?>
With this approach, you can access the element within setAuthor:
<script type="text/javascript">
function setAuthor(el) {
var author = el.innerHTML,
id = el.id.replace(/^closest_/, '');
if (console) {
console.log(author);
}
document.forms["myform"].elements["author_name_" + id].value = author;
}
</script>
However, you shouldn't set onclick inline and for each element. You should use an event registration function.