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');
});
});
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.
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.
I know this is almost duplicated, a lot of people asked that and a lot answered them by PHP Form but I really didn't find anything for my problem.
I have a page called platforms.php and this page has a group of image-links which are: Windows,Mac, Android and iOS.
So what I want is when somebody clicks the Windows link (as an example) they go to a page called download.php and the page should say You are using Windows!.
Please not that I don't want to create a page for every link, I want it to be one page only.
Thanks in advance!
Make URL like that
<a href = "http://example.com/download.php?device=window" >Window</a>
<a href = "http://example.com//download.php?device=mac" >Mac</a>
On your page download.php
if(isset($_GET['device'])) {
$device = $_GET['device'];
}
if ($device == 'window' ) {
// window message here
} elseif ($device == 'mac' ) {
// mac message here
}
send an extra parameter in your url and then in the same single page use the condition like:
let the parameter name be 'pagetype'.
download.php
if ($_REQUEST['pagetype'] == 'windows')
{
//your output for windows
}
else if ($_REQUEST['pagetype'] == 'mac')
{
//your output for mac
}
else if(..)
{
.
.
.
Note:
You can replace $_REQUEST, with $_GET or $_POST, depending on method you use to post data to this page
You can have an HTML link and send the data through GET parameters. Something like (in platforms.php):
<a href="download.php?os=Windows >Windows</a>
<a href="download.php?os=Mac >Mac</a>
<a href="download.php?os=Android >Android</a>
<a href="download.php?os=iOs >iOs</a>
And then in downloads.php, getting the variable "os" and do whatever you want with it:
if ( isset($_GET['os'] ) ) {
echo "You are using " . $_GET['os'];
}
you can add image like
<img src="window.jpg"/>
<img src="ios.jpg"/>
and on download.php page you can check
$value = $_GET['key'];
if(value== 'window')
if(value== 'ios')
etc
hope this is what you want.
Beginning developer here, making a website using wordpress as a platform. I would like the user to be able to click an upvote button and upvote a post without refreshing the page. I figure I should probably use javascript to highlight the button once clicked as well as change the vote number. However, I am having trouble figuring out how to run a php script (to update the database) without refreshing the page.
Thanks in advance,
sample upvote php for posts add this to your functions file....
add_action('wp_ajax_upvote', 'upvote');
add_action('wp_ajax_nopriv_upvote', 'upvote');
function upvote() {
$postid= $_POST['id'];
$direction = $_POST['direction'];
$votes= get_post_meta($postid, '_votes', true);
if($direction='down') {
$votes--;
} else {
$votes++;
}
update_post_meta($postid, '_votes', $votes);
echo $votes;
exit();
}
The above needs security like any form submit of $_POST variables. Dont leave these out in your code!!
jQuery Code
jQuery(document).ready(function($){
$('.arrow').click(function(){ //if your upvote has class arrow?
//you need someway of passing postid to here!
//if you want up / downvote -- logic needed here, if not remove direction from below!
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'upvote',
id: id,
direction: direction //remove if not needed
},
success: function (output) { //do something with returned data
console.log(output);
jQuery('#postupvote').text(output); //write to correct id - maybe use postid in the id of the vote count on the page e.g. id="vote23" jQuery('#vote'+postid)
}
});
});
})
google wordpress ajax for more information
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.