How to render specific view after clicking specific button. PHP HTML JS - javascript

I am making a page with soccer teams and leauges. Now i`m printing all Leagues that i want from the database.
League 1
League 2
League 3
etc.
As you can see each League has its own League_ID. In Database i also have a table of all teams, and each team has matched League (with League_ID). I also have a view, where i can print table of League that i want. This function in php looks like this.
public function leauge_table(){
$tables = $this->scoreTableRepository
->getScoreTable(1);
//TODO how to change this "1" static to generated
//TODO when pressing link
return $this->render('leauge_table', ['table' => $tables]);
And as you can see, when i go to this page i will always see the score table from leauge that has id=1.
And the question is how can i make that when i press for example at "League 2" i will open page but with table matching to League_ID = 2. Shall it be <button></button> or <a></a> in HTML. And how to pass there League_ID so my php back will see which table should render.
Thank you really for help.
PS
Or maybe do i have to make a seperate view for each leauge score table? And then just simply make buttons direct to these views with simple JS code. But would like to avoid it if it`s possible.

It can be a link or a button. A link with the league ID as a parameter in the URL is the simplest approach though, if you're new to the concept. e.g.
League 1
The ID would then be available in the php script via $_GET["id], once the link is clicked.

In your SoccerTeam page add a button in a form with the following :
<form action="youpage.php" method="post">
<input name="leagueId" type="hidden" value="<?php echo $leagueId;?>" >
</form>
And in order to process that information, since we passed an id, we can retrieve it with $_POST['leagueId'] and because it's a POST request it wont be visible in the url:
$leagueId = $_POST['leagueId'];

Related

After refreshing the page product adding automatically in cart

I am trying to make the code for a shopping cart, which is working. However, when I refresh the page it's adding a product to my cart automatically.
For example, I have 3 products on my website, which are Apple, Banana, Orange.
I click on Apple and it's added to my cart with QTY 1 and the URL is showing
`mydomain.com/my-cart?action=addcart&p_id=FylvGt6Yyb6n%2BzTXcJHwjBawOY%2Fw3QSZxF7rdUJLqhA%3D#`
Now if I refresh the page then it's adding another Apple to my cart (QTY 2). Then if I refresh the page again it adds another Apple (QTY 3) and so on. I don't know why this is happing. It's adding to SESSION.
Would you help me in this?
Below Is my cart code.
$action = isset($_GET['action'])?$_GET['action']:"";
$p_id=$conn->real_escape_string($_GET['p_id']);
$decrypted_p_id = decryptIt($p_id);
//Add to cart
if($action=='addcart') {
//Finding the product by code
$query = "SELECT p_unique_id, p_images,p_name, p_currentprice FROM products WHERE p_id=?";
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param("i", $decrypted_p_id);
$stmt->execute();
$stmt->bind_result($p_unique_id,$p_images, $p_name, $p_currentprice);
$stmt->fetch();
}
$currentQty = $_SESSION['products'][$decrypted_p_id]['qty']+1; //Incrementing the product qty in cart
$_SESSION['products'][$decrypted_p_id] =array(
'qty'=>$currentQty,
'p_unique_id'=>$p_unique_id,
'p_images'=>$p_images,
'p_name'=>$p_name,
'p_currentprice'=>$p_currentprice
);
$product='';
// header("Location:cart.php");
}
Displaying product
<?php if(!empty($_SESSION['products'])):
foreach($_SESSION['products'] as $key=>$product):?>
/*some code here*/
endforeach;?>
<?php endif;?>
Edited code here Suggested by ADyson
if (isset($_POST['submit'])) {
$action=$conn->real_escape_string($_POST['action']);
$decrypted_p_id=$conn->real_escape_string($_POST['p_id']);
// whole code here
i found this code:
$currentQty = $_SESSION['products'][$decrypted_p_id]['qty']+1;
this code always run when u reload the page,
give some condition if you want to add manually
If you simply click refresh on the exact same page then action=addcart etc. is still in the URL. Therefore inevitably it runs that action again when the page loads, and adds the items to the cart again.
An "add" action like that would be better done as a POST request, partly for semantic reasons (it's "sending" data rather than "get"ting it) and partly to avoid annoyances like this. Ideally a GET request should not cause any change of state in the application.
Instead of
Add to cart
you can do something like:
<form action="my-cart" method="POST">
<button type="submit">Add to cart</button>
<input type="hidden" name="action" value="addcart"/>
<input type="hidden" name="p_id" value="<?php echo $p_user_id;?>"/>
</form>
You can use some CSS to make the button appear more like your old hyperlink, if you wish.
Then, in your PHP cart code, simply replace all references to $_GET with $_POST instead, to read the values from the POST request.
This will have the advantage that the variables are not saved into the URL and therefore if someone tries to refresh the URL it will not automatically repeat the same action based on those variables.
You could also look into sending the data to add cart items via AJAX, so that it doesn't require a postback at all and usually results in a smoother user experience - if you look at most shopping websites now, that is generally what they do.

How to Update MySQL with PHP and AJAX without REFRESHING the PAGE

Ok here is my question
I have MySQL with the following order:
ids - radio - link - time - artist - title - disliked
ids is the ID of the Media
from page LISTEN.php I have random selection of video from the Database.
I have already created in LISTED.php to SHOW THE ID of the Video also the Artist and Title.
**I need to have a button on LISTEN.php where when somebody clicks it for example the name of the button - > Dislike
so if someone clicks it AJAX or SOMEHOW not to refresh the page but in the same time when the DISLIKE button is clicked to Update in the MySQL (once again without refreshing the page) to Disliked - 1, (when this button is pressed again for the same video to update to 2 / 3 / 4 and so on. Right now all of my videos are 0.
I need to be able to View not LIKED videos, for example
select * from RANDOM where DISLIKED is Higher number then >0**
I am not a very good in PHP so please help me, one more time the PAGE SHOULD NOT REFRESH.
Your help would be greatly appreciated.
Ajax in jQuery works like this:
var myData=1;
$.ajax({
type:'POST',//type of ajax
url:'mypage.php',//where the request is going
data:myData,//the variable you want to send
beforeSend:function(xhr){//as a standard, I add this to validate stuff
if(someThingWrong===true)xhr.abort//aborts xhttpRequest
},
success:function(result){
//result is your result from the xhttpRequest.
}
});
This will not refresh your page but send a 'POST' to the url specified. On your specified page you want to do whatever it is you want to do and say return a result. In my example I'll do something simple:
if($_POST['myData']===1)return True;
That's the basics of an AJAX request using jQuery.
EDIT!
initiating an AJAX script:
I'm only guess as I don't know your elements within your html nor your scripts what so ever! So you'll have to make adjustments!
$('button.dislike').click(function(){
$.ajax({
type:'POST',
url:'disliked.php',
data:{dislike:$(this).attr('id')},
success:function(result){
$(this).prev('span').append(result);
}
});
});
PHP:
don't use mysql, it's now been depreciated and is considered bad practise, I also don't know why're using sprintf on the query? :S
$DBH=new mysqli('location','username','password','database');
$get=$DBH->prepare("SELECT dislike FROM random WHERE ids=?");
$get->bind_param('i',$_POST['dislike']);
$get->execute();
$get->bind_result($count);
$get->close();
$update=$DBH->prepare('UPDATE random SET dislike=? WHERE ids=?');
$update->bind_param('ii',++$count,$_POST['dislike']);//if you get an error here, reverse the operator to $count++.
$update->execute();
$update->close();
return String $count++;
This will only work if there in your HTML there is a series of buttons with ID's matching those in your database. So
$get=$DBH->prepare('SELECT ids FROM random');
$get->execute();
$get->bind_result($ids);
while($get->fetch()){
echo"<button class='dislike' id='".$ids."'>Dislike this?</button>";
}
Hope you get the general idea of how I'm managing your dislike button system XD lol

How to make all the fields visible in the new Task form of Tasks List in SharePoint?

I have created a Tasks List in SharePoint. When I try to add a new Task, it opens a form with few visible fields like TaskName, StartDate, DueDate, Description, AssignedTo. When I click on 'ShowMore', then it is showing all the remaining fields like %complete, TaskStatus, Priority, Comments, ExpectedDueDate.
Issue: I want all the fields to be visible from the start without clicking on 'ShowMore', because some people might get confused with this option and may skip filling these fields. Can someone please kindly suggest how to achieve this. Any help is greatly appreciated. Thank you!
Unfortunately there is no such setting that allows to configure fields visibility in tasks form AFIK.
But task form could be customized in order to display all the fields as demonstrated below.
Since it is a SharePoint 2013 environment, the following approach is suggested:
Create rendering template to display all the fields in New & Edit forms
Update Task web part in New & Edit forms pages
Template file
The following example demonstrates how to display all the fields of Task form:
(function () {
function preTaskFormRenderer(renderCtx) {
rlfiShowMore();
}
function registerRenderer()
{
var ctxForm = {};
ctxForm.Templates = {};
ctxForm.OnPreRender = preTaskFormRenderer;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctxForm);
}
ExecuteOrDelayUntilScriptLoaded(registerRenderer, 'clienttemplates.js');
})();
How to apply changes
Upload the specified script (lets name it TaskForm.js) into SharePoint Site Assets library
Open New Form page in edit mode and go to Tasks web part properties
Specify JS Link property located under Miscellaneous group: ~sitecollection/SiteAssets/TaskForm.js (see pic. 1)
Save changes and repeat steps 2-4 for Edit form
I prefer other methods to the JavaScript workaround to really solve the problem:
1. You can change the list form assigned to the local Task content type, for example via PowerShell:
$web = Get-SPWeb http://YourSharePointSite
$list = $web.Lists["Tasks"]
$ct = $list.ContentTypes[0]
$ct.DisplayFormTemplateName = "ListForm"
$ct.NewFormTemplateName = "ListForm"
$ct.EditFormTemplateName = "ListForm"
$ct.Update()
You can set the list form assigned to the ListFormWebPart via SharePoint Designer
Create your own control template and add the ShowExpanded="true" attribute to the TaskListFieldIterator control
Pass the Expanded=1 in the request query string like NewForm.aspx?Expanded=1
Change the default column order of the local Task content type
All of these have the effect of displaying all the fields without the "Show More" button. You can read more about these methods here:
http://pholpar.wordpress.com/2014/11/01/no-more-show-more-in-tasks-lists/

Get random data from database,

I have a little problem, I've got this database with these fields.
Table Data{
ID
Name,
Text,
Location,
imagepath
}
And now I want the put these values into my fields, the data is just strings.
<h3><!-- Text value here --> - <!-- Name value here --></h3>
<p> <!-- Location data here --> </p>
And I also got this JS script that generates new fields, when the user clicks on a button.
$('.Next').click(function(e) {
e.preventDefault();
Slide.appendSlide('<!-- HTML DATA HERE NAME AND TEXT & LOCATION VALUES -->')});
I want the ID to be random, and I don't want the user to get the same data twice.
How should i approach this? I've tried a getdata.php but failed.
Thank you so much! Happy holidays!
Honestly i would look at saving the page id to $_session['visited']. Then each time they view a page append that to the session variable comma separated
$_session['visited'] .= ",".$page_id;
Then your sql will be.
EDITED
Ok so let make this code safe
$ph = explode(",",$_session['visited']);
foreach($ph as $check){
if (!isnumeric($check)){
echo "Not numeric, possible injection";
exit;
}
}
$parmcount=count($ph);
$inclause=implode(',',array_fill(0,$parmcount,'?'))
$sql='SELECT * FROM table WHERE ID NOT IN (%s)';
$preparesql=sprintf($sql,$inclause);
$st=$db->prepare($preparesql);
$st->execute($parms);
Or alternative just save all viewed ids as an array in the first place.

JQTouch: passing data between 'views'

Hi I have been playing around with jqtouch today and I'm just wondering how to manage data.
I tried looking around but couldn't see much documentation.
If I had a list of links for say products? And I click on one i can navigate to the product 'view'. How to I pass variables like you would a $_GET variable to select THAT product?
Or even if I set the id of the link to the id of the record and use JS to grab the ID and somehow pass it to the next view?
Any help with this would be most appreciated!
NOTE: I also want to use it with the offline extension so I'm not sure get ajax would work
Regards,
Billy
You can use the referrer property for the data object. The link would look like:
Product #1
where the HTML ID would correspond to the product ID. Then in the "pageAnimationEnd" event you can retrieve the product details like this:
$('#view').bind('pageAnimationEnd', function (e, info) {
// get the id of the calling href
var id = $(this).data('referrer')[0].id;
$.getJSON('/products/' + id, function (data) {
// do something with the data
});
});
You could look at the demo to see how it does form submission, i.e. AJAX > POST Form Example. Essentially, you create a form and a jQT-style submit button:
<form id="ajax_demo" action="ajax_demo.php" method="POST" class="form">
...
<a class="submit whiteButton" href="#">Submit</a>
</form>
Then in your receiving page (i.e. ajax_demo.php), you can access the form fields, e.g. PHP's $_GET or JavaScript's location.search.
Another way is to store the data in the DOM with jQuery:
// in global level
$('body').data('ajax_demo', "some data for the page");
// in page/view level
$('#ajax_demo').data('key', 'value');

Categories