If I click on a link, it's supposed to load data from the database that corresponds to that link and display the data into a div, but when I click, nothing happens. Based on my original question which had so many comments, I decided to start fresh: Using a href onclick to update div without reloading page?
My code:
the page that displays the links and data:
<a href="#" class="query-link" data-id="1" >text</a><br>
<a href="#" class="query-link" data-id="2" >text 2</a>
javascript file:
jQuery(document).ready(function() {
jQuery('a.query-link').on('click', function(e){
//Prevent the link from working as an anchor tag
e.preventDefault();
//Declare 'this' outside of AJAX because of asynchronous nature of call
that = jQuery(this);
//Make AJAX call to the PHP file/database query
jQuery.ajax({
url:'http://dirtypoliticsph.com/chart-submission/templatecode.php',
type:'POST',
data:{id:jQuery(this).data('id')},
success:function(data){
jQuery('#myStyle').append(data);
}
});
});
});
templatecode.php (the file that calls the database):
if(isset($_GET['id']))
{
$results = $mysqli->query("SELECT * FROM PresidentialCandidate WHERE ID=".$_GET['id']);
if( $results->num_rows > 0 )
{
$row = mysqli_fetch_array($results,MYSQLI_ASSOC);
//Instead of just echoing out the ID, you need to build the result/data that you want in the div right here. The success function of the AJAX call will append whatever you echo out here
echo $row['id'];
}
}
Try:
data:{id:jQuery(this).attr('data-id')},
You need to fetch the 'data-id' attribute of the element:
<a href="#" class="query-link" data-id="1" >text</a><br>
You said that you want to load data from database that corresponds to that link, but I don't see any selectors referring to the anchor tag as the response from the server. Add the following after your jQuery('#myStyle').append(data); :
jQuery('.query-link').append(data);
and use $_POST in your templatecode . By the way since those anchors use the same class name, so both of them will be affected.
Related
how is it possible to achieve this:
http://jennamolby.com/how-to-display-dynamic-content-on-a-page-using-url-parameters/
using php?
let's say that I have the following a url:
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager?article=my-article
to get there I have a link in pages-folder/works.php :
link
which should open content-manager.php in which inside a div I should load my-article.php
EDITED:
I have an index file in which a load into the div.container all the pages I need, so in this case my works.php file is loaded int the div.container using using:
<?php
$page = $_GET['page'];
if(!empty($page)){
$page .= '.php';
include($page);
}
else {
include('pages/home.php');
}
since I also needed to update the url without reloading the page I use this script:
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Page: page, Url: url };
history.pushState(obj, obj.Page, obj.Url);
}
}
$('ul.menu li a').on('click', function(){
var page = $(this).attr('href');
var pageUrl = page.split("/");
pageUrl = pageUrl[1];
$('.container').load(page + '.php', function(){
//fadeout old content
//fadein new content
});
ChangeUrl('Page1', '?page=' + page);
return false;
})
once I have my works.php loaded into the div.container I have the above mentioned link which should lead me to: pages-folder/works-folder/content-manager.php
it is in this page where I'd like to load my-article.php inside the main div of content-manager.php
I thought that adding the ?article= variable would have worked using the same system as above:
$article = $_GET['article'];
if(!empty($article)){
$article .= '.php';
include($article);
}
else {
...
}
but it doesn't...
how can I achieve this?
Why you don't just add you article as a query param ?
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager&article=my-article
and make a link like this
link
This is just an exemple to understand what you want to do, don't use this kind of code in production, he is vulnerably to CSRF attack
EDIT: with echo it's better sorry
I haven't answered your question per se but this is the sort of code you are looking for:
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
Explanation
How does $_GET work?
$_GET is a super global variable - meaning it can be accessed from anywhere.
It is a an associative array of variables passed to the current script via the URL parameters.
These are specified following a question mark (?) in the URL. To specify multiple parameters you must use the ampersand (&) character between each one.
$_GET must be specified at the end of the URL after everything else.
http://www.example.com/thisPage.php?page=a
http://www.example.com/thisPage.php?page=a&theme=light
The first URL will produce a $_GET with one element which can be accessed as: $_GET["page"] and would return a string of one character a.
The second will produce:
$_GET["page"]; // returns "a"
$_GET["theme"]; // returns "light"
Notice that for each parameter a new key-value pair is created.
I wrote a comprehensive explanation of superglobals on SO Documentation, but that has since been deprecated. RIP my hard work :P
Showing differing content
As you can see from my answer above. You can use simple if statements to check what the value is.
Firstly, ensure that $_GET isset and then check the value.
I have converted the value of the array to lowercase since "A" is not the same as "a".
The example you linked to really over-complicates things. There is honestly no need for all that regular expressions, and it also relies on JavaScript which is not necessarily a good idea.
With my example at the top, there is no difference between user experience as PHP is server sided thus all the content is worked out and then served to the user.
One step further
Using this you can go that extra step and have an event listener and combine it with AJAX.
Altering my initial example you can have the following.
I have used the jQuery library as it is a lot easier to implement.
<div id="test">
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
</div>
function myAJAX() {
$("a").on("click", function(e) {
e.preventDefault();
// get the clicked page number
if (this.href.indexOf("&") > -1) {
var d = this.href.substring(this.href.indexOf("page=") + "page=".length, this.href.indexOf("&"))
} else {
var d = this.href.substr(this.href.indexOf("page=") + "page=".length)
}
$.ajax({
method: "GET",
url: "t.php",
data: "page=" + d,
success: function(data, textStatus, jqXHR) {
// change the content of the #test div
$("#test").html($($.parseHTML(data)).filter("#test")[0]);
myAJAX();
}
});
});
}
myAJAX();
Notice that the HTML is not being wrapped in <div id="test"> which is so that the JavaScript can find that element and change it in the function.
$("#test").html($($.parseHTML(data)).filter("#test")[0]); is the line that is fetching the HTML and changing it with the data from the page you tried to click on.
I also call the function inside itself so that it will reattach on the anchor links. If you remove this line then the page will redirect as normal.
The good thing about this implementation is that if your user does not have JavaScript then the page will act as normal and there will be a normal reload of the site.
No need for any extra work on your part.
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);
EDIT:
Adding the following to the code below:
alert(LogoutURL);
shows the URL is coming across to the JS variable incorrectly. Is seems to be "encoded" once passed to the JS var.
I know this from executing in my PHP the following:
<?php echo wp_logout_url('/') ?>
as this writes the correct URL to the page. Any help is appreciated. Thanks
I am sure this one is straightforward but I have not been able to find how to do this. Maybe I have asked the question wrong... I am trying to insert the "logout with no confirmation" link in WordPress but the URL I pass the menu does not resolve correctly. The menu is part of a theme so I cannot easily modify it.
As such I am using a combination of JS and PHP to generate the link for the current logged in user, by changing the "href" in the "a" item containing "Logout" text, to the output of "wp_logout_url" as follows:
<script type="text/javascript">
jQuery( document ).ready(function() {
/*** change Logout URL if logged in ***/
var LogoutURL = "<?php echo wp_logout_url('/') ?>";
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; }).attr("href", LogoutURL);
My resolved menu code:
<li id="menu-item-5516" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-5516">
Logout
</li>
When the JS inserts the resolved URL it seems to add "amp;" to it in places where it found "&". I even tried without success to use "encodeURI()" function.
How can I pass the URL to the HREF "as is"?
The issue seems to be that wp_logout_url is correctly changing & to &, and then jQuery must be again changing & to & resulting in &.
The hacky solution is to simply do
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; })
.attr("href", LogoutURL.split("&").join("&"));
Also, if you parent li elements id doesn't change, it would be far more efficient to do
$("#menu-item-5516").find("a").attr("href", ...);
Rather than run a filter on all of the a elements. If not I would still find a better way to select that element, checking every link in the document is overkill.
Note: You SHOULD have one amp; after every & in a link. That is CORRECT. If you DON'T want that, you can do
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; })
.attr("href", LogoutURL.split("&").join("&"));
Well this did it... still not sure why this is required. Am I pulling into the JS the url incorrectly?
var LogoutURL = "<?php echo wp_logout_url('/') ?>";
jQuery('a').filter(function(index) { return jQuery(this).text() === "Logout"; }).attr("href", LogoutURL.replace(/&/g, "&"));
This is my solution to place a logout link in my menu's list item with class "logout". The link now carries me through to the login page without the "oops ... do you really want to logout?":
PHP - replacing & with &:
$logouturl = str_replace('&','&',wp_logout_url(home_url() . "/wp-login.php?loggedout=true"));
jQuery - replacing href in li.logout a:
logoutUrl = '<?php echo $logouturl; ?>';
jQuery('li.logout a').attr('href',logoutUrl);
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.