show product name in opencart order history - javascript

On my website its quite important to show products names on Order history (my_account/order_history), while in opencart there is only shown order id. I have partly solved the problem however I would very appreciate some hints how to proceed.
The topic was once opened in 2011 in http://forum.opencart.com/viewtopic.php?f=20&t=46387&p=437991#p437991
The main problem is that the file order_list.tpl doesnt have access to $product['name'] in controller order.php (where its defined in function info() instead of function index()), only order_info.tpl have. I tried to copy the parts of the code from the function info() to the function index() but it still didnt have access there. Any hint what I have to do ? Do i need to change something in model file ? or how to modify controller file (order.php) to allow order_list.tpl to have the right access ?
One approach I have tried is rendering the content order_info using javascript on the order_list.tpl in new div (as described in http://goo.gl/nMXhEu ) however as a newbie in js I coudlnt modify it to open right after page-load (not on moveover). I have tried to change mouseover to load, beforeload a few other without any success..
$("body").on("mouseover", function(e){
$(".order-info").load(e.target.href, function(){
$(e.target).addClass("unloaded");
});
});
Any help or hint how to proceed would be very appreciated

$(function () {
$(".order-info a").each(function () {
var $me = $(this);
$me.load($me.attr('href'),function(){
$me.addClass("unloaded");
};
});

thanks for help cske, I really appreciate it. However I still could not make it work. I also tried to make some small adjustments, without any success (but then I am not js developer).
So I decided to try once again to modify the controller file, to make $product['name'] accessible to order_list.tpl (as described in the question). I was able to do so by adding
$products = $this->model_account_order->getOrderProducts($result['order_id']);
and
foreach ($products as $product) {
$this->data['products'][] = array('name'=> $product['name'],);
}
after
foreach ($results as $result) {
which makes possible to call it in orders array for example
$this->data['orders'][] = array(
'product_name' => $product['name'],
It is working solution however:
1. it shows only one product per order
2. it throws notice
Notice: Undefined index: order_id
The notice can be turned off in Admin area.
I am Ok with this solution, but obviously it might not be the right solution for other shops.

I used the solution that only shows the first product for the order to figure out how to show all products for the order and their quantities.
Instead of:
foreach ($products as $product) {
$this->data['products'][] = array('name'=> $product['name'],);
}
use:
$this->data['products'] = array();
$prod = "";
foreach ($products as $product) {
$prod .= $product['quantity'] . " x " . $product['name'] .'<br>';
}
and in:
$this->data['orders'][] = array(
add:
'product_data' => $prod,
then in order_list.tpl you can get the product list with quantities with:
<?php echo $order['product_data']; ?>

Related

Delete previous row in database show the next row in database by clicking button

I need Help on this, base on what I already did: In the output every time I click the button it shows the row (comments) in database. But I want that If I click the next button it will show the row (comments) in the database and when I click it again It will delete the previous row (comments) in the database and show the next row (comments).
Here is the code:
<?php
include 'dbh.php';
$commentNewCount = $_POST['commentNewCount'];
$sql = "SELECT * FROM comments LIMIT $commentNewCount";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['id'];
}
} else {
echo "There are number!";
}
?>
This is for the button:
<script>
//jQuery code here!
$(document).ready(function() {
var commentCount = 0;
$("button").click(function() {
commentCount = commentCount + 1;
$("#comments").load("load-comments.php", {
commentNewCount: commentCount
});
});
});
</script>
You have AJAX tagged in your question, so I am assuming that you are somewhat familiar with the term. This can indeed be done by AJAX, but I don't see any AJAX attempts in your code?
Also, when you say delete, do you mean specifically delete by the literal sense, or simply that your comment display works as sort of a sliding function, removing the previous comment from display, showing the next comment in queue? I am going by the literal sense in my example, since that's what I have to assume really.
What you could do, is to have a file that handles all the comments, and displays them however you like. For instance,
<?php
$sql="SELECT * FROM comments ORDER BY id DESC";
$result_set=mysqli_query($conn, $sql);
while ($row=mysqli_fetch_assoc($result)) {
/*
html construction of displaying comments,
echo'ing the row value that displays the comments.
echo $row['comments']; as a guess
*/
}
?>
Let's call that PHP file comments.php for the sake of referencing later on. Also note, that I chose to make an ORDER BY in a descending order. Assuming your comment id is an auto increment, then this will always display the newest comments first, since the highest id's will be the latest entries.
Then, in another file, display-comments.php as an example, you could make a document.ready function, that loads your comments into an element, <div> element for example.
The AJAX function could look like this:
$( document ).ready(function() {
function loadCommentsAjax()
{
$.ajax({
type : "POST",
url : "comments.php",
data : { },
success: function (html) {
$("#commentContainer").html(html);
}
})
}
});
What I do here, is that I encapsulate an AJAX function in a document.ready function. What this does, is that when the document is ready, it fires the AJAX function.
How the AJAX function works, is that we declare a data type. The most common are probably POST and GET. You can look up the different data types, how to handle them, and what they mean specifically. The main difference between POST and GET for instance, is that GET displays its values as parameters in the URL. Since we aren't parsing any data, we could use a GET just fine, since it will have no influence. However, should you ever need to parse sensitive data, where you don't want the user to mingle with the data, then you should use POST.
We then tell the AJAX function, which page/file it should work with. In our example, it will be the comments.php that we created earlier. It will then in the success function, paste the html content into a container that we defined. In this case, commentContainer. Note that it's an id specific targeting, which means our container element needs to have that specific id. Note, that the container is in our main file, the display-comments.php file.
An example of the container could be the following:
<div id="commentContainer"></div>
This div element will then contain the comments and html logic that we made in our comments.php file.
In your button, you can then have another AJAX function, handling the comment deletion, and call our loadCommentsAjax() function on success, to reload our comments in the appropriate fashion.
The AJAX function handling the deletion of comments, would then again have a PHP file that will perform the delete. We'll call this delete-comments.php in our example.
example of our delete AJAX function:
function deleteNewestComment() {
$.ajax({
type : "POST",
url : "delete-comments.php",
data : { },
success: function (html) {
loadCommentsAjax();
}
})
}
Our delete-comments.php will look something like this:
<?php
/*
since you are deleting the latest entry each time, what we could do,
is make an SQL query that deletes the max id from the comments table
*/
$sql="DELETE FROM comments WHERE id=(SELECT max(id) FROM comments)";
$result=mysqli_query($conn, $sql);
?>
We will then have our button call the delete function like so:
<button onclick="deleteNewestComment();">Delete latest comment</button>
Let me know if this is what you were looking for at all, or whether you really just wanted a sliding kind of logic, where you simply iterate through your comments, displaying one at a time.
But in case you did mean literally delete, then wouldn't it be better to have delete buttons linked to each comment, so that you can delete them seperately, and independantly?

How to update the url with ajax

I am currently trying to output a number of records through pages. However I am already kinda failing at the beginning...
The <table> with all the records gets updated through ajax. However the problem I have is that whenever I click on the link which should update the part.php?page=1 it doesn't do anything.
file part.php
function activateEMode(aa){
//update all val etc
loadDoc("partB.php?page=1"+val+"&person="+person+"&status="+status+"&s_priortiy="+val1+"&s_uDate="+val2+"&s_fDate="+val3+"&search="+search+"&aa="+aa+"&q="+val, partiB);
}
file partB.php
$page = $_GET['page'];
for ($i=1;$i<5;$i++){
echo '<a href=part.php?page='.$i.'>'.$i.'</a>';
}
echo $page;
So what I am trying to achieve is that, when ajax function loadDoc is called it should set the ?page to the <a> pressed. Would be nice if you could help me :).
You can use window.location.replace to jump to a new link.
It will be like this:
var currnet_Location = windows.location;
var current_Location = current_Location.substring(0, current_Location.indexOf("page="));
var location_to_jump = current_Location+"New Location";
window.location.replace(location_to_jump);
Good Luck :)

PHP, Javascript, mysql, and selection lists

I'm working on a piece of some software that will grab information from a mysql database and throw it onto our form dynamically. I'm running into a couple problems, though. I'll give a quick rundown of some functionality.
When the form loads, we have a ton of selection lists. These are all populated through arrays with various keys/values in php. When I select an option from one list, we'll call it a "customers" list, on-click I need to check if that customer has a special flag (stored in the database), and update another selection list based on that data.
How I understand the core of my solution is I need to have a javascript trigger on-click, which I have. The function that is called references a php page that handles the database query through a class and it's function.
<script>
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer='+customer);
}
</script>
This function then talks to my php. The CustomerProvider class works 100%. I have tested that thoroughly on other pages. The problem arises when I try to actually get my selection list to change.
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != '')
{ ?> <script>var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';</script> <? }
else return;
}
?>
I'm coding in javascript literally for the first time ever and they kinda just threw me on this project. I know that my portion isn't being read as html or output as I intend. I know that every other part of the php and the first bit of javascript seems to be executing okay. Any help would be incredibly appreciated.
You seem to be on the right track but just for your own sanity here are a couple pointers. You shouldn't be returning Javascript from PHP for a situation like this. Instead you should be relying on Javascript promises to wait for a response containing just the data and continue the execution of your client code once you have your values returned. Take a look at this:
<script>
function setService() { // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer=' + customer, function(data) {
console.log(data + ' was returned from your php script!');
if(data.hasContract=='1')
$('#ticket_service').val('Contracted Hours');
else
$('#ticket_service').val('No Contracted Hours');
});
}
</script>
And then your PHP script will just look like this:
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){
$hasContract = 1;
}
else
$hasContract = 0;
echo json_encode(array('hasContract' => $hasContract));
}
?>
Therefore returning only the data needed for the client app to continue... not application logic
Your code isn't doing anything with the output of the PHP script. If you want the output to be inserted somewhere in the DOM, you should use .load() rather than $.get.
$("#someelement").load('thePage.php?key=setService?customer='+customer);
This will put the output into <div id="someelement">. If the output contains <script>, the script will be executed.
If you know the result is just a script, you could use $.getScript() instead of $.get. Then the output should just be the Javascript, not enclosed in HTML tags like <script>.
The problem here is that you are not using the result from the server. Your JavaScript may indeed be correct, but the browser never sees or runs it. From the docs:
Request the test.php page, but ignore the return results.
$.get( "test.php" );
Try this code, which utilizes the $.getJSON() shortcut function. I've written two versions, which you can see commented in the code. One moves the logic for determining contract status into the JS. Either should work.
PHP
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
// Default output
$output = array('hasContract' => false);
// Customer has contract
if ($s != '')
$output['hasContract'] = true;
echo json_encode($output)
// Alternative: PHP just returns getHasContract, JS determines action
// (this would replace $ouput, conditional, and echo)
// echo json_encode(array("hasContract" => $s));
}
?>
JavaScript
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.getJSON('thePage.php?key=setService?customer='+customer, function(result) {
// Alternative
// if (result.hasContract != "")
if (result.hasContract)
{
var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';
}
});
}
As others wrote, your code doesn't do a thing with the GET variables.
the element "ticket_service" doesn't exists on page and even if it was, the code has no impact on the page that sent the request, you should print/echo the result you want to display/return and then manipulate it with JS/Jquery.
since I'm against GET and pro POST which is safer method, here's an example with POST:
JS:
function postSomthing(customerID){
$.post(
'thePage.php',
{key:'setService',customer:customerID},
function(data){
if(data!='x'){
$('#ticket_service').val(data)
}
else{alert('no ticket');/*whatever you want to do*/}
});
}
PHP(thePage.php) :
if(isset($_POST['key']) && $_POST['key'] == 'setService'){
$customer = intval($_POST['customer']);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){echo 'x';/* false, or whatever you want*/}
else{echo 'Contracted Hours';}
}
notes:
you should create an element with the id "ticket_service" in the viewed page and not in the backstage one.

jQuery loading value from php file into html input on button click - not working

i have a text file with a number that is inside it. The number should be +1 inside the text file and the new value should be updated inside index.php all this should happen after a button inside index.php is clicked, but thats not happening.. i did a lot of googling and i tried many things from what i sow still it's not working, keeping in mind I'm new to jQuery. below is all the involved code explained. any help will be appreciated!
The php script inside index.php to retrieve the value from num.txt and place it inside the text input once index.php is loaded, this works perfectly:
<?php
$filename = "num.txt";
$file = fopen("num.txt","r+");
$number = fread($file, filesize($filename));
fclose($file);
?>
The text input code, as you can see will take the $number value from the above script and this works fine. keep in mind i used the id of the input and the class of it then i ended up adding a div and using its class, i didn't know what to do so i tested them all, same thing nothing worked:
<div class="on"><input type="text" id ="omlat" class="inv-number" value="<?php echo $number;?>"></input></div>
jQuery to update the value after clicking on the submit button. this function should only refresh the value of the input value by calling inum.php and taking the value inside inum.php after the code there is excited:
$(document).ready(function(){
$(".reloadpg").click(function(){
$(".on").load("http://localhost/einvoice/inum.php");
});
});
Code inside inum.php, this code works fine i tested it (this code takes the number inside num.txt and +1 the value as you can see):
<?php
header("Cache-Control: no-cache");
$filename = "num.txt";
$file = fopen("num.txt","r+");
$number = fread($file, filesize($filename));
$number = $number + 1; //the new number to proceed
file_put_contents('num.txt', $number);
echo $number;
fclose($file);
?>
-- Update --
The code bellow worked for the above part it worked perfectly but now I'm facing another problem. Another function that listens to the same button that was working before stopped working! so what i did was that i toke some of the code that the guys bellow provided and pot it inside the older function that was listening to the button click the whole code is as follows(please read the comments to understand the code):
$('.create-invoice').on('click',function()
{
//Below is the code i added from the first problem above its not working here.. when it was alone outside this function as the accepted answer it will work but it will stop this function from working!
$.get( "/einvoice/inum.php", function(data) {
$('.inv-number').val(data);
});
//Above is the code i added from the first problem..
//below is the original code for the function, keep in mind only the below code is bing excited the above is not.. its not refreshing the part of the page it should its calling the php script successfully tho, but i will have to refresh the page my self to see the number updated
grab_invoice_data();
// Declare a variable
var jsonObj = invoice_data;
// Lets convert our JSON object
var postData = JSON.stringify(jsonObj);
// Lets put our stringified json into a variable for posting
var postArray = {json:postData};
$.download("php/json.php", postArray, 'post');
//if cookie exists
var i_n = $('.inv-number').val();
$.cookie('lid', ++i_n, { expires: 365 } );
//invoices created
if( $.cookie('ic') ){
var ck_inv_created = ($.cookie('ic'));
$.cookie('ic', (++ck_inv_created));
} else {
$.cookie('ic', ++inv_created);
}
})
You're replacing the input with the number, rather than just updating its value. Try this instead...
$(document).ready(function(){
$(".reloadpg").click(function(){
$.get("http://localhost/einvoice/inum.php", function(data) {
$(".on input").val(data);
});
});
});
That uses jQuery's get() method to make an ajax call that passes the response into a callback function as a parameter. You can then do whatever you need with it inside that function.
You jquery part is not good. Try this :
$(document).ready(function(){
$(".reloadpg").click(function(){
$.get( "/einvoice/inum.php", function( data ) {
$("#omlat").val(data);
});
});
});

Is there a CakePHP component/plugin that does permanent links for ajax pages?

I'm using the JsHelper to write JS links to use ajax to load in a page. Like this:
<?= $this->Js->link($item['Series']['title'], array(
'controller' => 'series',
'action' => 'view',
$item['Series']['id']
), array('update' => '#menu-items')); ?>
This is working fine, but now I'd like to add it so that you can link to these pages. So, for example, when you click the link it would redirect you to example.com/#!/series/2. You could then also go to this url and the correct page would be loaded in the #menu-items div.
Is this something I'd have to write from scratch, or is there a CakePHP helper or plugin available that would do it for me? I have experience in doing something like this before, but never with CakePHP and unsure where to start.
Thanks,
I've had a go at tackling it myself now, as I figured that as there was no response then something like this wasn't already built for CakePHP.
So first, the javascript:
var hash = '';
window.setInterval(function() {
if(hash != location.hash) {
hash = location.hash;
if(hash.indexOf('#!/') != -1) {
var url = hash.substr(2);
$('#my-div').load(url);
}
}
}, 300);
What this does is check to see if the location.hash has changed, if it has, then it checks to see if it starts with #!/. (I.e #!/:controller/:action/:id is the hash that I'm looking for). It then just calls the jQuery load function to load that controller and action.
I then had to modify my links to use the url method in the HtmlHelper.
<?
$hashUrl = $this->Html->url(array(
'controller' => 'categories',
'action' => 'view',
$category['Category']['id']
));
echo $this->Html->link($category['Category']['title'], '#!' . $hashUrl);
?>
This creates a string for the controller and action, then appends it to #! in the link method. Doing it this way, may seem quite long winded (You could probably write a custom helper to make it one line) but it allows you to change the URLs in the config/routes.php later on. You end up with a url like this: #!/categories/view/2
Lastly, you need to make sure that in your controllers you have this at the end of each of method you use.
$this->render('view', 'ajax');
I'm not imagining that this is a perfect solution, but it does the job quite nicely at the moment. Open to suggestions for improvement too.
There are open source projects that may be able to help you along. Here's a good starting point: https://github.com/browserstate/history.js

Categories

Resources