I want to apply a plugin on a certain table that is being generated dynamically through a php script. This is the plugin : CLICK
Now from what i read in the comments i should You first need some form of server side component, say a PHP script, which generates the html table from the data in the database. Then pass the URL of this PHP script into a jQuery ajax call. In the "success" callback, set the innerHTML of some holding div to the response of the ajax call, then select this newly created DOM table element and put it into the plugin.
Hope that makes sense!
Here's what i got so far.
HTML
<div class="testin">
<script>
testin();
</script>
</div>
JS
function testin(){
var load = $.get('functions.php',{gameNo:"1",function:"testin"});
$(".testin").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".testin").html('failed to load');
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".testin").html(res);
});
load.done(function() {
console.log( "Completed" );
});
}
php
if($_GET['function']=="testin")
{
echo '<table class="template" style="display:none"><thead><tr><th>Game Name</th><th>Round</th><th>Player Name</th><th>Target Name</th><th>Shot Number Now</th><th>Shot Score So Far</th><th>Rank</th></tr></thead><tbody></tbody></table>';
$gamenumber = $_GET['gameNo'];
echo'<table border="1" class="actualTable"><tr><th>Game Name</th><th>Round</th><th>Player Name</th><th>Target Name</th><th>Shot Number Now</th><th>Shot Score So Far</th><th>Rank</th></tr>';
$sql = mysql_query("SELECT * FROM tbl_Round WHERE match_id='$gamenumber' ORDER BY round_name")
or die(mysql_error());
$i=1;
while($row = mysql_fetch_array($sql))
{
$tempSnumber = getcurrentshot($row['round_id'],$row['player_id']);
echo'<tr>';
echo'<td>'.$gamenumber.'</td>';
echo'<td>'.$row['round_name'].'</td>';
echo'<td>'.$row['player_id'].'</td>';
echo'<td>'.$row['target_name'].'</td>';
echo'<td>'.$tempSnumber.'</td>';
echo'<td>'.$row['round_score'].'</td>';
echo'<td>'.$i.'</td>';
echo'</tr>';
$i++;
}
echo'</table>';
}
The function fills the div just fine. I also create the template table in the php script.
Now my problem is how to invoke the plugin and what should i pass ass objects?
Invocation is like $(oldTableElement).rankingTableUpdate(newTableElement) but i'm confused due to the fact that it's being generated dynamically.
I'm new to JS so any help would be appreciated.
First off, I would put your javascript outside the div with class "testin".
Below you JS function you can add the jquery call like in the code below.
See this link for more info: http://api.jquery.com/on/
$(document).ready(function(){
$("table tr").on( "click", function() {
//your custom code goes here.
});
});
What this does is make sure then any element that matches the "table tr" will get an click handler, no matter when it gets created.
Related
I have a table for loading data and i wrote a code which assigns each table an href with javascript since the serverside enabled i can't assign each td a href. Therefore, each time page changes or search query invoked i need to assign href to client side table rows.
Here is what i put so far:
function assign_href_to_tables() {
console.log("Run assign_href_to_tables");
// access all td variables when serverside enabled.
$('#table').on( 'order.dt', function () {
var table_rows = $('#table').find('tbody tr');
console.log(table_rows)
// scan through table rows and assign onclick event to each row.
table_rows.each(function(index, element) {
$(this).click(function() {
var id = $(this).find('td:nth-child(1)').text();
// reidrect to the edit page with the id of the clicked row
window.document.location = '/detail/' + id;
});
});
} );
}
I invoke the assign_href_to_tables function in initComplete e.g.:
"initComplete": function( settings, json ) {
assign_href_to_tables();
},
If i call the function on document ready it will affect only the first page. When page changes or search request queried href stops working.
I tried to follow this link but i did not understand it nor i could implement it.
As long as i understand, the problem arise initComplete does not wait for the table data to load. I don't know what is missing in my work. Thank you.
I am trying to load more data from a database with a jQuery .load, and it works perfectly, but after the first load, it ist'n bringing more data.
Also, for bringing the first content, which is brought on the first page load, i use a PHP foreach() loop, like this as a basic example:
<div class="grid-products">
<?php foreach($products as $product): ?>
<div class="grid-product">
<?php echo $product['name']; ?>
</div>
<?php endforeach; ?>
</div>
I am trying to load more data from my database on scroll, so the user don't have to click on a button. I am loading information from my database based on the method of this question, like this:
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
//do an ajax call
}
});
But as I don't know how to do the ajax call mentioned on the answer above I found, I decided to use a jquery .load passing also some POST method variables, which in this case would be productNewCount. First I set its value to 6, and when user reaches bottom of page, we sum plus six to its value, like this:
$(window).scroll(function() {
var productCount = 6;
if($(window).scrollTop() == $(document).height() - $(window).height()) {
productCount = productCount + 6;
$(".grid-products").load("load-products.php", {
productNewCount: productCount
});
}
});
This works great on first load, and so when this is executed, it loads on the <div class="grid-products"> the load-products.php file. Here, the variable $connection is calling my function to connect to the database, don't give too much importance to it.
This is load-products.php:
<?php
$connection = connect();
$product_new_count = $_POST['productNewCount'];
$sentence = $connection->prepare("
SELECT * FROM all_products ORDER BY date DESC LIMIT $product_new_count
");
$sentence->execute();
$products = $sentence;
?>
<?php foreach($products as $product): ?>
<div class="grid-product">
<?php echo $product['name']; ?>
</div>
<?php endforeach; ?>
In the sentence, we are calling to bring all the rows from the all_products table ordered through its date column, and limiting to bring only the rows product_new_count says, which its value is the productCount JS variable we brought on the main file, before its load.
I made sure there are still rows available to bring, so the reason why other rows arent being shown after first load isn't because there are no rows left. Also, terminal isnt showing any errors or warnings and there is also still available space to make scroll so the function can be called.
Can I bring more data through this .load method or should I use the AJAX call mentioned on the answer I found? If so how?
Every time you scroll productCount is set to 6, hence all your load request will be the same.
You can define productCount outside the event handler to increase the number of elements loaded each time.
var productCount = 6;
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
productCount = productCount + 6;
$(".grid-products").load("load-products.php", {
productNewCount: productCount
});
}
});
If you are trying to add to the existing content (not replace all of it) use $.post instead of load() and append the results.
load() replaces whatever is already existing inside the matching selector
$.post("load-products.php", {productNewCount: productCount}, function(html){
$(".grid-products").append(html)
})
I made a shopping cart for a website using PHP .GET Like this:
Every page starts with:
<?php session_start();
require("dbconnect.php");
if(!isset($_SESSION['cart'])) {
$cart = array();
$_SESSION['cart'] = $cart;
}
?>
Every product that is generated has the following check when generated on the website:
if(!in_array($id, $_SESSION['cart'])) {
echo '<img width="20px" style="margin-left: 175px; margin-top: -42px; float:left" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/voeg-toe.png" alt="Voeg product toe"/>';
}
else {
echo '<img width="20px" style="margin-left: 175px; margin-top: -42px; float:left" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/verwijderen.png" alt="Verwijder product"/> ';
}
What it does: if the product with ID $id is in the $_SESSION['cart'] the product will have a delete button which onclick deletes the product. When the product is not in the session cart the product will have an 'add' button which adds the product if you click on it.
This all works perfectly fine however, I want to change this PHP GETmethod to an AJAX GET function because the reloading of the page seems a bit amateurish.
So I searched on Google but all I found when searching for something like this is directly implementable AJAX code for Magento or WooCommerce. I tried to write my own AJAX function to execute the URL but I haven't managed so far. Can somebody give me a direction on how to do this? I am not asking for a direct solution but just for a direction on what way to do this.
Should I write an AJAX function which I add as onclick on a button to every product something like function cart(id) { that checks if the id is in the PHP cart or should I handle this way different? Do I still use the PHP Cart like how I made it right now or should I change that to a JavaScript array?
PS: I'm ok in PHP but a complete noob in JavaScript but I really want to learn some of it.
EDIT: Ok, so my first step to solve this is using jQuery.ajax(). But I could use both the jQuery $.get() and $.post() method. I know the differences between them in PHP but I'm not sure which one to use while using AJAX.
You can just use AJAX like you said.Based on the code you provided
if(!in_array($id, $_SESSION['cart'])) {
echo '<a class="add-to-cart-btn" data-id="'.$id.'" data-action="add"><img width="20px" style="margin-left: 175px; margin-top: -42px; float:left" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/voeg-toe.png" alt="Voeg product toe"/></a>';
}
else {
echo '<a class="add-to-cart-btn" data-id="'.$id.'" data-action="delete"><img width="20px" style="margin-left: 175px; margin-top: -42px; float:left" src="http://bgc-testomgeving.nl/sem/wp-content/themes/sem/images/verwijderen.png" alt="Verwijder product"/> </a>';
}
Then use jQuery to handle every click on anchor links having add-to-cart-btn class,get the id and the action you want (if it is not already in the cart add else delete), and use AJAX to send them to server.
$(".add-to-cart-btn").click(function(e) {
e.preventDefault();
var id=$(this).data('id');
var action=$(this).data('action');
var this_button=$(this);
$.ajax({
url: "/sem?action="+action+"&id="+id,
type: "GET",
success: function (data)
{
//you can check your returned data from php here
//and on success toggle data action (because user may click the button again...
this_button.data('action', action == 'add' ? 'delete' : 'add');
}
});
});
Of course the example is really basic.I have not tested it but something like this should do what you want.You should look up the documentation for ajax call so you can see all the options you have,handle errors etc.
I think your code could look something like this..
write a PHP page that returns the $_SESSION variable in JSON (javascript object notation).
Example URL: shopping_cart_items.php
<?php
session_start();
require("dbconnect.php");
echo json_encode($_SESSION);
Then get the data with jQuery:
// Gets (JSON) a Javascript Object from the server
jQuery.getJSON("shopping_cart_items.php",function(items_in_shopping_cart){
// Loops through all the <a> elements with class shopping_cart_elements
// (assuming your <a> elements have a distinctive attribute such as a class "shopping_cart_elements")
jQuery("a.shopping_cart_elements").each(function(index,dom_object){
// Gets the current <a> element id attribute
current_dom_obj_id = jQuery(dom_object).attr('id');
// Checks if current id belongs to the array current_dom_obj_id
if(items_in_shopping_cart.indexOf(current_dom_obj_id) != -1)
// Changes the 'href' attribute to'action=add'
jQuery(dom_object).attr('href','/sem?action=add&id='+id+ '#wpc-products');
else
// Changes the 'href' attribute to'action=delete'
jQuery(dom_object).attr('href','/sem?action=delete&id='+id+ '#wpc-products');
});
});
I am using a jquery carousel to display some images in a dynamically populated list. When the page is first opened it looks great but once the ajax replaces the contents of the div containing carousel content all of the formatting etc is lost.
I understand that this is because the ajax content is newly created and didn't exist when the carousel script did it job but I'm not sure how I can get it to apply the formatting to the new content?
This is the ajax call displaying the newly created data
$(function(){
var audit_id = $('#auditID').val();
var btnUpload=$('#upload');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: '../ajax/upload_standard_ajax.php?audit_id='+audit_id,
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|JPG)$/.test(ext))){
status.text('Only jpg files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(response){
status.text('');
//if(response==="success"){
$.ajax({
url: 'ajax/create_audit_standard_carosel.php',
type:'POST',
data: 'audit_id='+audit_id,
success: function(response){
$('#selected_standards').html(response);
}, // End of success function of ajax form
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
}); // End of ajax call
}
});
});
The html used to trigger the ajax call
<a href="#" class="upload_stuff ipad_hide">
<div id="upload">
<span class="upload_btn"> </span>
</div>
</a>
<span id="status" ></span>
The ajax response
$output .='<ul id="standards_list" class="touchcarousel-container">';
while($row = mysqli_fetch_assoc($result)){
$output .='<li class="touchcarousel-item">';
$output .='<img src="'.$row['imageLocation'].'" width="200" >';
$output .='</li>';
}
$output .='</ul>';
I've tried it just having it all on one line and I've also tried leaving the ul intact on the original page and just outputing the li element. I've also tried using json and just echo for the resonse
I can apply the formatting by refreshing the screen but it kind of defeats the object of using ajax
My reputation is too low so I can't comment, but first, what do you mean by formatting? Do you mean CSS styles? It would help if you showed the markup for the element that is represented by #selected_standards.
If you mean "CSS formatting", I suspect that when you do:
$("#selected_standards").html(response);
you are overwriting the contents of #selected_standards and thus losing the CSS formatting.
Grab the current value of the classes assigned to #selected_standards (or its children, depends on your document structure) and then re-attach those classes to the elements that had them before.
You can do something like
var previousClasses = $("#selected_standards").attr("class");
// your existing code to insert HTML
$("#selected_standards").attr("class", previousClasses);
I wanted to create a drop down at a
certain position based on a users
click and
I wanted this to come in the form of a drop down also
the content in the drop down would be dynamically genereated through
ajax..
im using jquery-tools tooltip to do this but am facing some problem...
the ajax content is loading only after the second click ..
THIS IS THE CODE TO CREATE AN ARRAY of TOOLTIP OBJECTS
$(document).ready(function(){
var show = false;
var tips = new Array();
$(".replie").each(function(){
$(this).tooltip({ effect: 'fade', events: {widget:'click,'},position:"bottom right",onBeforeShow:function() {
this.getTrigger().fadeTo("slow", 0.8);
}})
tips.push($(this).tooltip(0));
});
AND THIS IS THE CODE TO CONTROL THE TOOLTIPS BEHAVIOR AND LOAD AJAX CONTENT
$(".replie").click(function(evt){
if(!evt){
evt=window.event;
}
var row =evt.target.parentNode.id[2];
var aid=evt.target.id;
var uid= <?php echo $uid ?>;
var tip;
$("#tip"+row).load("reply.php?uid="+uid+"&aid="+aid,function(){
$(this).hide()
});
if(tips[row].isShown)
{
tips[row].hide();
}
else
{
tips[row].show();
}
});
HOW DO I LOAD THE CONTENT AND THEN SHOW THE TOOLTIP .. ?
Use jQuery.ajax() function instead of jQuery.load() function. You can set a callback function on complete or success event. Inside that handler, trigger the tooltip function.
This is the documentation of jQuery.ajax(): http://api.jquery.com/jQuery.ajax/