Vue.js data in HREF through PHP - javascript

How do I pass the result of the vue DATA into PHP. I tried this way but when I see the link in HREF (href = $ where $ name) it gives me a strange string and not the url one I get from the VUE code.
Instead if I put: href = "$ where $ name" or v-bind: href = "$ where $ name" instead I get the white screen WITHOUT table.
How can I solve this problem and be able to put the right link in the href?
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label v-on:click="giallo()" class="btn btn-secondary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked> Giallozafferano
</label>
<label v-on:click="benedetta()" class="btn btn-secondary">
<input type="radio" name="options" id="option2" autocomplete="off"> Fatto in Casa da Benedetta
</label>
<label v-on:click="nonna()" class="btn btn-secondary">
<input type="radio" name="options" id="option3" autocomplete="off"> Ricette della nonna
</label>
</div>
</div>
$sql = "SELECT id,scadenza,nome,quantita,tipoMisura,categorieP,categorieD FROM Prodotti WHERE utente = '$us' ORDER BY scadenza";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0){
echo "<table class='top table table-striped'>";
echo "<thead>";
echo "<tr>";
echo "<th scope='col'>Ricetta</th>";
echo "</tr>";
echo"</thead>";
echo"<tbody>";
}
while ($row = mysqli_fetch_assoc($result)) {
$name=$row['nome'];
$where="{{dove}}";
echo "<td> <a target='_blank' href='$where$name'>Found recipe </a> </td>";
echo "</tr>";
}
//VUE CODE
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
dove: "https://www.giallozafferano.it/ricerca-ricette/"
},
methods : {
giallo: function(){
this.dove="www.giallozafferano.it/ricerca-ricette/";
},
benedetta: function(){
this.dove="https://www.fattoincasadabenedetta.it/?s=";
},
nonna: function(){
this.dove="https://www.ricettedellanonna.net/?s=";
}
}
});
</script>

First of all you should use :href, then your html would be like:
<a target='_blank' :href='{{dove}}yourstringinname'>Found recipe </a>
I think problem is that your second string is not matched for Vue as string, you should insert it as string for Vue:
<a target='_blank' :href='{{dove}} + `yourstringinname`'>Found recipe </a>
In PHP like:
<a target='_blank' :href='$where + `$name`'>Found recipe </a>
As far as i now Vue shoud place errors in browser console, so you can debug it with console.

Related

adding multiple inputfield using javascript in php not working

i have a form in php in which i am trying to add multiple fields on button click, i did the following code:
function add_fields() {
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
';
objTo.appendChild(divtest)
}
<div id="room_fileds">
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
</div>
<input type="button" id="more_fields" onclick="add_fields()" value="Add More" />
however this is not working, i am getting the following error:
** Uncaught ReferenceError: add_fields is not defined
at HTMLInputElement.onclick **
can anyone please tell me what is wrong in here, thanks in advance
As per the comment previously about cloning content and appending that the following goes a step further and uses a content Template to store the content that you wish to add with each button click. This template could hold the generated select menu and would be invisible until added to the DOM. This means you do not have a huge, bloated function that gets called - only some quite simple code to find the template, create a clone and append to the designated parent node.
The below example has the PHP commented out so that the display here looks OK but would need the PHP code re-enabled to produce the actual results you need. None of the code within the template has an ID attribute so there is no need to worry about duplicating IDs.
const clonetemplate=(e)=>{
let parent=document.getElementById('room_fields');
let tmpl=document.querySelector('template#rfc').content.cloneNode( true );
parent.append( tmpl )
}
// Button click handler
document.querySelector('input#add').addEventListener('click',clonetemplate );
// pageload... display initial menu
clonetemplate();
#room_fields > div{margin:1rem;padding:1rem;border:1px solid grey;font-family:monospace;}
#room_fields > div label{display:block;width:80%;padding:0.25rem;margin:0.1rem auto;float:none;}
#room_fields > div select,
#room_fields > div input{float:right}
<div id="room_fields">
<!-- add content here -->
</div>
<input type="button" id='add' value="Add More" />
<!--
Generate the content once that will be repeated
and keep it within a content template until
needed.
-->
<template id='rfc'>
<div>
<div class='form-group col-md-6'>
<label>Item
<select class='form-control' name='item'>
<option>Select Item
<!-- Uncomment this PHP for live version
<?php
$sql = 'select * from `inventory` order by `categoryname` asc';
$res = $con->query( $sql );
$group=array();
while( $rs=$res->fetch_object() ){
$group[ $rs->categoryname ]=$rs;
}
foreach( $group as $key => $values ){
printf('<optgroup label="%s">',$key);
foreach( $values as $obj )printf( '<option>%s',$obj->name );
print('</optgroup>');
}
?>
-->
<option>Hello
<option>World
<option>No IDs
<option>Simples...
</select>
</label>
</div>
<div class='form-group col-md-6'>
<label>Weight
<input name='weight' type='text' class='form-control' placeholder='Weight' />
</label>
</div>
</div>
</template>
In the string that you define in the function add_fields and assign to divtest.innerHTML you have line breaks. You probably also get an error when loading the script saying that you have a syntax error. You should try to avoid line breaks in strings. An alternative solution could be to use backticks for your string. YOu can read about it here: Template literals (Template strings).
Here are two examples. The first fails with both syntax and reference error, the next works fine (but does not do anything).
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = '
test
';
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = `
test
`;
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />

Using AJAX to update a dynamic webpage

I made a webpage that consists of projects, where each project consists of a list of files. All of this information is acquired from a MySQL database. I've implemented a feature that allows users to comment on each file and reply to each other's comments. I have a php function called "place comments" which recursively places comments for each file shown below.
This is executed for every file and every file is displaced similarly using a while loop and some statements that echo html code.
However, the issue I'm having is using AJAX to post comments without the page refreshing. Since each file id is different, I would have to update every selector with a particular file id and run placeComments again for every file.
However I'm not sure how to accomplish this. I'm able to update my database through AJAX everytime I submit a comment.
I know you can do something like the following and it will update any selector with the id "id":
$(document).ready(function() {
$.get('comments.php', function (data) {
$('#id').html(data);
});
});
But I'm not sure how I can do this iteratively for every file id where each file id is a php variable?
Is there a way I can communicate with JS through PHP so it updates comments
for all file ids? If so, how?
I realized that this is a terrible design, but I'd like to do this without starting my project from scratch.
Place comments function:
function placeComments($mysqli, $parentId, $fileId) {
$sql = "SELECT * FROM Comments WHERE parent = $parentId AND file = $fileId ORDER BY UNIX_TIMESTAMP(date) ASC";
$comments = $mysqli->query($sql);
while($comment = $comments->fetch_assoc())
{
echo '
<ul class="comments">
<li class="clearfix">
<div class="post-comments">
<p class="meta"> '. $comment['date'] .' '. $comment['username'] .' says : <i class="pull-right">
<p>'
.
$comment['content']
.
'</i></p><br><br>';
echo '<div class = "col-sm-12 reply panel-group">';
echo '<div class="panel panel-default">';
echo '<p><a data-toggle="collapse" href="#'. $comment[
'file'] . '-' . $comment['id'] . '"> Reply </a></p>';
echo '<div id="'. $comment['file'] . '-' . $comment['id'] .'" class="panel-collapse collapse">';
echo '<div class="panel-body">';
if(isset($_POST['submitComment-' . $comment['file'] . '-' . $comment['id']]))
{
$user = $_POST['username'];
$content = $_POST['content'];
$fileId = $_POST['id'];
$parent = $_POST['parent'];
$date = date('Y-m-d H:i:s', time());
filterComment($mysqli, $fileId, $user, $parent, $content, $date);
}
echo '<form method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group">
<div class="col-sm-10 form">
<h5><b> Name: <b></h5>
</div>
<div class="col-sm-10 form">
<textarea class="form-control" name="username" id="username" rows="1"></textarea>
</div>
<div class="col-sm-10 form">
<h5><b> Reply: <b></h5>
</div>
<div class="col-sm-10 form">
<textarea class="form-control" name="content" id="content" rows="3"></textarea>
</div>
<div>
<input class = "form-control" type = "hidden" value = '. $comment['file'] . ' name = "id" id = "id" />
</div>
<div>
<input class = "form-control" type = "hidden" value = '. $comment['id'] . ' name = "parent" id = "parent" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10 form">
<button class="btn btn-success btn-circle text-uppercase" type="submit" id="submitComment" name = "submitComment-'. $comment['file'] .'-' . $comment['id'] . '"><span class="glyphicon glyphicon-send"></span> Reply </button>
</div>
</div>
</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div><br><br>';
placeComments($mysqli, $comment['id'], $comment['file']);
echo '</div>';
echo '</li>';
echo '</ul>';
}
$comments->free();
}

How to send href value in tablesorter to dialog modal?

Problem
I have problem in sending/passing href value in tablesorter to my dialog modal.
It's become complicated when the target location is the dialog modal.
Example (table.php)
This is a partial of my code since above it is a PDO PHP query to get my data from database. Important point is at the href code inside foreach
if($stmt->rowCount() > 0){
$r=$stmt->fetchAll();
echo "<table class='tablesorter-dropbox' id='myTable' style='width:97%; table-border: 1'>";
echo "<thead>";
echo "<tr style='text-align: center;'>";
echo "<th style='text-align: center;'>No.</th>";
echo "<th style='text-align: center;'>Conference Name</th>";
echo "<th style='text-align: center;'>Conference Sponsor</th>";
echo "<th style='text-align: center;'>Date (Start)</th>";
echo "<th style='text-align: center;'>Date (End)</th>";
echo "<th style='text-align: center;'>Budget</th>";
echo "<th style='text-align: center;'>Status</th>";
echo "<th style='text-align: center;'>Approve</th>";
echo "<th style='text-align: center;'>Reject</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
//echo "<td><a href='reject.php?idstudent=".$row['matricno']."&idbook=".$row['serialno']."'><img src='pic/remove-icon-png-15.png' width=15px></a></td>";
foreach ($r as $row){
echo "<tr align='center'><td>".$row['id']."</td><td>". $row['conf_name'] ."</td><td>". $row['conf_sponsor'] ."</td><td>". $row['conf_fDate'] ."</td><td>". $row['conf_lDate'] ."</td><td>RM ". $row['conf_budget'] ."</td><td>". $row['conf_status'] ."</td><td><a href='#' onclick='this.href='indexSuperUser.php?idconf=".$row['id']."' role='button' data-toggle='modal' data-target='#login-modal3?idconf=".$row['id']."'><img src='images/good.png' width=15px></a></td><td><a href='#?idconf=".$row['id']."' role='button' data-toggle='modal' data-target='#login-modal4'><img src='pic/remove-icon-png-15.png' width=15px></a></td></tr>";
//$startrow++;
}
echo "</tbody>";
echo "</table>";
}
else{
echo "<p align='center'>Nothing to show you :( I am really sorry for this T_T </p>";
}
Example #2 (dialogmodal.php)
Now here is where i want to display the variable from the table. Just for testing purpose i am trying to display the idconf to see if the id displayed successfully.
<!-- BEGIN # MODAL LOGIN -->
<div class="modal fade" id="login-modal3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" align="center">
<img style="position:relative; LEFT:20px; WIDTH:100px; HEIGHT:100px" id="img_logo" src="images/logofpeNEW2.png">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</div>
<!-- Begin # DIV Form -->
<div id="div-forms">
<!-- Begin # Register Super User Form -->
<form id="approved-form">
<div class="modal-body">
<div id="div-register-msg">
<div id="icon-register-msg" class="glyphicon glyphicon-chevron-right"></div>
<span id="text-register-msg">Approve this event?.</span>
</div>
<input type="text" id="idconf" class="form-control" value="<?php echo $_GET['idconf']; ?>">
</div>
<div class="modal-footer">
<div>
<button type="submit" class="btn btn-primary btn-lg btn-block" style="background-color: green">Approve</button>
</div>
</div>
</form>
<!-- End # Register Super User Form -->
</div>
<!-- End # DIV Form -->
</div>
</div>
</div>
<!-- END # MODAL LOGIN -->
<!--END LOGIN AREAD--------------------------------->
Result
The result? Its either undefined index: idconf or nothing. Means that im trying to send variable like this #?idconf=".$row['id']."....... since if i put like this dialogmodal.php?idconf=".$row['id'].".. my dialog ends up opening another dialog that is weird to say.
Flow
The flow is simple. Start from the table.php where it will grab the data from my database and display using tablesorter plugins. Then it will open at the dialog modal. Right side of the table have approved and rejected. So this two things comes from the href itself. Just like on the picture.
Duplicated?
Maybe yes. but its a little bit different. I give here two link almost the same problem as me:
Dynamically load information to Twitter Bootstrap modal
Send parameter to Bootstrap modal window?
However. My problem a bit slightly difficult i think. Mine is not about show the data when button clicked. But instead, i need to click the button to open the modal dialog first then clicked href button to open each row with unique id.
my stackoverflow account could be blocked at any time since i got many downvoted question. I dont know what happen to people nowadays. So i try to do proper and detailed here. If still downvoted, it will be my last here.. :)
Oh never mind. I got it work out by using from someone. I can't remember the link but credit to him for mentioning about using "data-your variable" and call it using jquery and send it back to the modal dialog id. Like this
<a id='approved' href='#' role='button' data-toggle='modal' data-target='#login-modal3' data-id='".$row['idconf']."' data-confname='".$row['conf_name']."' data-confsponsor='".$row['conf_sponsor']."' data-conffdate='".$row['conf_fDate']."' data-confldate='".$row['conf_lDate']."' data-confbudget='".$row['conf_budget']."' data-confstatus='".$row['conf_status']."' data-useremail='".$row['email']."' data-username='".$row['name']."' data-balanceuser='".$row['balance']."' data-m='".$row['matricNo_fk']."'><img src='images/good.png' width=15px></a>
See how many data i send? Then call it using jquery like this..
$(document).on("click", "#approved", function () {
var idconf = $(this).data('id');
var confname = $(this).data('confname');
var confsponsor = $(this).data('confsponsor');
var conffdate = $(this).data('conffdate');
var confldate = $(this).data('confldate');
var confbudget = $(this).data('confbudget');
var confstatus = $(this).data('confstatus');
var useremail = $(this).data('useremail');
var username = $(this).data('username');
var balanceuser = $(this).data('balanceuser');
var m = $(this).data('m');
After declare this variable, then on the next line of this code, send it to the modal dialog id such as this.
$(".modal-body #idconf").val( idconf );
$(".modal-body #nameconf").val( confname );
$(".modal-body #sponsorconf").val( confsponsor );
$(".modal-body #dateSconf").val( conffdate );
$(".modal-body #dateEconf").val( confldate );
$(".modal-body #budgetconf").val( confbudget );
$(".modal-body #statusconf").val( confstatus );
$(".modal-body #emailuser").val( useremail );
$(".modal-body #nameuser").val( username );
$(".modal-body #balanceuser").val( balanceuser );
$(".modal-body #m").val( m );
$('#addBookDialog').modal('show');
On the modal dialog, use the id mentioned.
<form id="approved-form">
<div class="modal-body">
<div id="div-register-msg">
<div id="icon-register-msg" class="glyphicon glyphicon-chevron-right"></div>
<span id="text-register-msg">Approve this event?.</span>
</div>
<input type="hidden" id="idconf" class="form-control" value="" disabled>
<input type="text" id="nameconf" class="form-control" value="" disabled>
<input type="text" id="sponsorconf" class="form-control" value="" disabled>
<input type="text" id="dateSconf" class="form-control" value="" disabled>
<input type="text" id="dateEconf" class="form-control" value="" disabled>
<input type="text" id="balanceuser" class="form-control" value="" disabled>
<input type="text" id="budgetconf" class="form-control" value="" disabled>
<input type="text" id="statusconf" class="form-control" value="" disabled>
<input type="text" id="emailuser" class="form-control" value="" disabled>
<input type="text" id="nameuser" class="form-control" value="" disabled>
<input type="hidden" id="m" class="form-control" value="" disabled>
</div>
I am not saying this is efficient in terms of speed or whatever. but it solved my problem and user problem. Case solved

hide or remove checkbox which is on colorbox popup after selected in dropdown

I have dropdown list and checkbox popup(colorbox popup) list in which data comes from complaint.csv file.
complaint.csv File
1,complaint type 1
2,complaint type 2
3,complaint type 3
etc...
I want to hide/remove checkbox from the popup checkbox list when item is selected from dropdown. e.g. if 'complaint type 1' is selected from dropdown then 'complaint type 1' from checkbox list should be removed/hide.
Here is some code.
PHP code:
<label class="question-name" ng-class="{error:hasError()}">
<span class="ng-binding" ng-hide="question.nameHiddenOnMobile">
Chief Complaint
</span>
<span class="icon-required" ng-show="question.required"></span>
</label>
<select name="Language.PrimarySpoken" ng-hide="showAddAnswer"
ng-model="question.response.value"
ng-options="a.text as a.getText() for a in question.answers.items"
id="Language.PrimarySpoken" ng-value="a.text" class="input-wide"
ng-class="{error:hasError()}" onchange="changeEventHandler(event);">
<option class="hidden" disabled="disabled" value=""></option>
<?php
$file_handle = fopen("../complaint.csv", "r");
while (!feof($file_handle)) {
$lines_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
foreach ( $lines_of_text as $line_of_text):
?>
<option value="<?php print $line_of_text[1]; ?>">
<?php print $line_of_text[1]; ?></option>
<?php endforeach; ?>
</select>
<br/> <br/>
<label class="question-name" ng-class="{error:hasError()}">
<span class="ng-binding" ng-hide="question.nameHiddenOnMobile">
Additional Complaint
</span>
<span class="icon-required" ng-show="question.required"></span>
</label>
<div class="form-row added ng-binding" ng-bind-html="question.getText()" id="text" ></div>
<div class="form-row addlink ng-binding"
ng-bind-html="question.getText()">
<em><a class='inline' href="#inline_content">+ Add/Edit</a></em>
</div>
<div style='display:none'>
<div id='inline_content' style='padding:25px; background:#fff; font-size: 17px;'>
<form action="" id="popup_form">
<?php
// Setup ---------------------------------------------------------------
define('numcols',4); // set the number of columns here
$csv = array_map('str_getcsv', file('../complaint.csv'));
$numcsv = count($csv);
$linespercol = floor($numcsv / numcols);
$remainder = ($numcsv % numcols);
// Setup ---------------------------------------------------------------
// The n-column table --------------------------------------------------
echo '<div class="table">'.PHP_EOL;
echo ' <div class="column">'.PHP_EOL;
$lines = 0;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
foreach($csv as $item) {
$lines++;
if ($lines>$lpc) {
echo ' </div>' . PHP_EOL . '<div class="column">'.PHP_EOL;
$lines = 1;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
}
echo ' <label class="checkbox" for="checkbox'.$item[0].'" style="font-size:20px;">
<input type="checkbox" name="complaint" value="'.$item[1].'" id="checkbox'.$item[0].'" data-toggle="checkbox">'
.$item[1].
'</label><br />';
}
echo ' </div>'.PHP_EOL;
echo '</div>'.PHP_EOL;
// The n-column table --------------------------------------------------
?>
<br/>
<input type="submit" name="submit" id="update"
class="button button-orange"
style="width: 90px; margin-top: 450px; margin-left:-1062px;"
value="Update">
<input type="submit" name="cancel" id="cancel"
class="button button-orange"
style="width: 90px; background-color:#36606e;"
value="Cancel">
</form>
</div>
</div>
JS code
<script type="text/javascript">
function changeEventHandler(event) {
$('.inline').colorbox({onLoad: function() {
// alert('You have ' + event.target.value + ' complaint.');
$('input[type=checkbox][value=' + event.target.value + ']').parent().hide();
}});
}
</script>
In above JS code I am getting alert of selected value from dropdown (the line of alert which is commented) but the checkbox item having that selected value is not removing somehow.(for this line $('input[type=checkbox][value=' + event.target.value + ']').parent().hide(); , I am getting just loading icon on popup)
Can anyone please tell me how should I do that?
Note: I am reading data from complaint.csv file for both dropdown list and checkbox popup list in php as shown in above code.
make following changes and check
$('input[type=checkbox][value="' + event.target.value+ '"]').parent().hide();

Make Wish List Dynamic for each item/ article

HI i got a little Problem i have whish list script which adds artivcles from shop into a session and saves them but when i click on the which list he only adds the first item how to male it dynamic that every wish list click is for the individual item in the shop
my article structure, onclick of wlbutton1 or wlbutton2 he should add the article with id1 or 2 to the wishlist:
echo '<div class="span3 filter--'.$obj->product_prop1.'" data-price="'.substr($obj->price, 0, -3) . '" data-popularity="3" data-size="s|m|xl" data-color="pink|orange" data-brand="'.$obj->product_brand.'">';
echo '<div class="product">';
echo '<div class="product-img featured">';
echo '<form method="post" action="../cart_update.php">';
echo '<div class="picture"><img src="images/'.$obj->product_img_name.'">';
echo '<div class="img-overlay"><button class="add_to_cart btn more btn-primary">Kaufen</button>...mehr</div>';
echo '</div>';
echo '</div>';
echo '<div id="result"></div>';
echo '<div class="main-titles"><h4 class="title">'.$currency.$obj->price.'</h4>';
echo '<h5 class="no-margin isotope--title" id="product'.$obj->id.'">'.$obj->product_name.'</h5>';
echo '<p class="no-margin pacifico" style="position: absolute;right: 10px;top: 5px; text-transform: capitalize;">'.$obj->product_brand.'</p>';
echo '<p class="no-margin" style="position: absolute;right: 10px;top: 25px;"><a class="wl-button'.$obj->id.'"><i class="icon-gift"></i></a></p>';
echo '</div>';
echo '<p class="desc">'.substr($obj->product_desc, 0, 160) . '...</p>';
echo '<input type="hidden" name="product_qty" value="1" />';
echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
echo '</div>';
My Jquery Code how to make it dynamic and individual for eacht artivle?:
$(".wl-button").click(function() {
var wlproduct = $('#product').text();
var wlproducturl = $('#producturl').attr('href');
$.ajax({
type : "POST",
url : "../assets/wlscript.php",
data : { wlproduct : wlproduct, wlproducturl : wlproducturl },
success : function(data) {
$('div#result').text('You added '+wlproducturl+' '+wlproduct+'\'s to your wishlist.');
}
});
});
Here an example of how you can do to find the data you need to add your article.
First the HTML example :
<div class="products">
<form>
<p>
<!-- Fist article -->
<span>Article 1</span>
<!-- A name construct so that I can easilly find in which iteration of the loop I am -->
<input type="hidden" name="article[0].id" value="1" />
<input type="hidden" name="article[0].name" value="article1" />
<button class="addButton">Add article</button>
</p>
<p>
<!-- Second article -->
<span>Article 2</span>
<input type="hidden" name="article[1].id" value="2" />
<input type="hidden" name="article[1].name" value="article2" />
<button class="addButton">Add article</button>
</p>
<!-- … others articles -->
</form>
</div>
And the Javascript part :
$(document).ready(function(){
$(".addButton").on("click", function(event){
event.preventDefault();
var button = $(this);
var parent = button.parent(); // We need to find the container in which to seach our fields.
var idArticle = parent.find("input[name$='.id']").val(); // Find the ID
var nameArticle = parent.find("input[name$='.name']").val(); // Find ather data
alert("Add article with id = " + idArticle + " and name = " + nameArticle);
// Next step is the ajax method to call the server with the correct data.
});
});
By working like that, you can then send to your server the data you need to add an article to your wishlist.
Here the link to the JS Fiddle example.
In this example, you can see how to work around the HTML content from the button to find the inputs.
You can find more about "tree traversal" with the jQuery API.

Categories