Play Framework 2.4: Getting the id of a button - java

I have the following form with repeating items:
#(adverts: List[models.AdvertModel])
#if(adverts.size() > 0 && adverts != null) {
#helper.form(action = routes.UserController.editAdvert()) {
#for( (advert, index) <- adverts zip (Stream from 0)) {
<div>#adverts.get(index).title</div>
<button type="submit" name="delete" id="delete_#index">delete</button>
}
}
and this controller:
public Result editAdvert() {
String[] indices = request().body().asFormUrlEncoded().get("delete");
if (indices != null) {
// delete advert
}
return ok();
}
I would like to be able to delete adverts according to their ids but with the current code my array contains a String "delete" instead of i.e. "delete_0".
How do I get the index of the clicked button?

I finally got it:
tldr:
add value="delete_#index" to the button.
longer answer:
The value returned by request().body().asFormUrlEncoded().get("delete")
is saved in the value attribute of the button with name="delete" in the scala template.
Therefore, by adding a value="delete_#index" to the button, we will get a String such as delete_0.
As #danielnixon commented, this is not a play-specific behaviour, but simply how html forms work.

Related

How to parse specific data from JSON file to a html dropdown menu

JSON FILE
Hi, in the json file i have shown above there is over 30 matchdays and i was wondering how would i be able to parse the data from the JSON file to a html file and have the options in a dropdown menu to be able to filter by matchdays or filter by teams, is it possible to do this or am I overthinking it, i have the file parsing the data and showing all results from the json file into a table as shown below
html file showing all matchdays
i was wondering is there a way i can filter these results by specific team or matchdays ? any help appreciated thanks
html file taking in the json data
Below code snippet would help you to finish your work.
var json = '{"name":"EnglishPremierLeague2015","rounds":[{"name":"Matchday1:","matches":[{"date":"2015-08-08","team1":{"key":"manutd","name":"ManchesterUnite","code":"MUN"},"team2":{"key":"tottenham","name":"TottenhamHotspu","code":"TOT"},"scorer":1,"score2":0}]},{"name":"Matchday2:","matches":[{"date":"2015-08-09","team1":{"key":"India","name":"IndianCricketTeam","code":"IND"},"team2":{"key":"England","name":"EnglandCricketTeam","code":"ENG"},"scorer":1,"score2":0}]}]}';
var data = JSON.parse(json);
// Filter by Match Day
var filter = $(data.rounds).filter(function () {
return this.name == "Matchday1:";
})
// Test Case :)
if (filter.length == 1) {
console.log("Filter working")
}
var filterbyTeam = $(data.rounds).filter(function () {
return this.matches.filter(function (e) {
return e.team1.key == "India" || e.team2.key == "India";
}).length >= 1;
})
// Test Case :)
if (filterbyTeam.length == 1) {
console.log("Filter working")
}
This code will get the JSON array with the filter that you can use further to show your HTML.
Note: You need to pass filter text according to your requirement. You can change the attribute as well to filter specific data.
Hope this will help :)

How to redirect if form is not submitted

I have form for registration (for example:www.register.com), once the user fills the form and clicks on submit, he will be redirected to another page (for example: www.thanku.com).
This is all working fine but how can I redirect to www.register.com when a user directly enters (without submission) the www.thanku.com?
on Page thanku.com, first check if user submitted any post request
e.g
if (!isset($_POST['submit'])
{
header('Location: http://www.register.com/');
exit;
}
You can use Submit button to send any value:
<input type="Submit" name="SubmitButton" value="1">
And then just check if the variable is set:
if( !isset($_POST['SubmitButton']) ) {//button not clicked
//your redirect code
}
This is exactly what you need.
if(isset($_POST['submit'])) {
if(!$answer1 && !$answer2 && !$answer3) {
header('Location: http://www.register.com/');
} else {
// Your code is here
}
}

Determine if a user likes a facebook page [duplicate]

I think I'm going crazy. I can't get it to work.
I simply want to check if a user has liked my page with javascript in an iFrame app.
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
This returns: False
But I'm a fan of my page so shouldn't it return true?!
I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}
You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
string true string false json
formatted response of error if token
or page_id are not valid
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}
You can do it in JavaScript like so (Building off of #dwarfy's response to a similar question):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
div#container_notlike, div#container_like {
display: none;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : 'http(s)://YOUR_APP_DOMAIN/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
var page_id = "YOUR_PAGE_ID";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div id="container_notlike">
YOU DON'T LIKE ME :(
</div>
<div id="container_like">
YOU LIKE ME :)
</div>
</body>
</html>
Where the channel.html file on your server just contains the line:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.
Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.
The basic code is rather simple:
FB.api("me/likes/SOME_ID", function(response) {
if ( response.data.length === 1 ) { //there should only be a single value inside "data"
console.log('You like it');
} else {
console.log("You don't like it");
}
});
ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:
FB.login(function(response) {
//do whatever you need to do after a (un)successfull login
}, { scope: 'user_likes' });
i use jquery to send the data when the user press the like button.
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example:
url:
http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file.
in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.

Delete item from Cart -Spring MVC

I am developing a small application using spring mvc where I need to have option to delete each item from cart (in case customer feels he donot need after adding to cart).
I have got a "delete" button below each item item.(The items added are in a list).My pupose is when I click delete button against a particular item only that item should be removed from the cart.
I have written some code but it is remove lastest added items from cart and not required one.
I know my mistake but not able to proceed further.Here is what I implemented.
This is jsp :
<c:forEach items="${cart}" var="nextMovie">
<li>
<h2>${nextMovie.title}</h2>
</li>
<h2>Price</h2>
<h2>${nextMovie.price}</h2>
<c:set var="totalPrice" value="${0}" />
<c:forEach var="nextMovie" items="${cart}">
<c:set var="totalPrice" value="${totalPrice + nextMovie.price}"/>
</c:forEach>
<form method='post' action='<c:url value="removeFromCart.do"/>'>
<input type='image' src='Delete.png'/>
<input type='hidden' name='id' value='${nextMovie.id}'/>
</form>
</c:forEach>
This is my controller:
#RequestMapping("/removeFromCart")
public ModelAndView removeFromCart(HttpSession session) {
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
if (cart == null) {
cart = new ShoppingCart();
}
List<Movie> allMovies = cart.getAllItems();
for(int i= 0;i<allMovies.size();i++)
{
allMovies.remove(i);
}
return new ModelAndView("/cartContents.jsp", "cart", allMovies);
}
Please suggest me how I will be able to delete the element again the delete button from the list.
Thanks
Maruthi
[HttpPost]
[Route("~/CartDetail/DeleteCartDetail")]
public ActionResult DeleteCartDetail(CartDetailModel model)
{
var response = _cartDetailService.DeleteCartItem(model.Id);
return Json(new
{
success = response.Success,
message = response.Message
});
}
}
I am importing my data from service DeleteCartItem
Here is service code
public BaseResponse DeleteCartItem(int cartDetailId)
{
var response = new BaseResponse();
try
{
var itemCart = _context.CartDetails.FirstOrDefault(x => x.Id == cartDetailId);
if (itemCart == null)
{
response.Message = "This item does not exist in the cart.";
return response;
}
_context.CartDetails.Remove(itemCart);
_context.SaveChanges();
response.Success = true;
}
catch (Exception exception)
{
response.Message = "Some error occured : " + exception.ToString();
}
return response;
}
Your JSP has nested <c:forEach> tags, with both containing the same items expression. Either you don't need 2 of them of else you need to close the first one before starting the second.
Your application has some problems:
First, your problem is because you are using the same var attribute name, for your both foreach tags. The first tag defines an attribute named nextMovie in its scope, the second foreach which is nested within first, defines the same attribute name, and then iterates, so when its iteration completes, nextMovie will be last element in the list, so ${nextMovie.id} will be last element's id.
Second,
List<Movie> allMovies = cart.getAllItems();
for (int i= 0;i<allMovies.size();i++) {
allMovies.remove(i);
}
is equivalent of allMovies.clear(), isn't it? So you are removing all items form list, what else do you need?
Third, next problem is you have an object of type ShoppingCart in your session which is named cart, and you add an object of type List<Movie> to your model with the same name; although when EL processor tries to resolve a name request has a more priority than session, but believe me it is much better to rename one.
Forth, why are you calculating 'totalPrice' in each iteration? And what is its use?

Dijit form fields not parsing on dojo.place after a dojo.destroy

I have a table in my form called table0 that has several dijit form controls in it. I also have an add and remove button to add a new table and remove the last table. Each new table will have an id incremented by 1. So the first click of add gives table1, 2nd click table2, etc. Each click of remove will remove the last table.
Here is the add function:
function getNewTable() {
dojo.query('#addTable').onclick(function() {
var tableNode = dojo.byId('table'+count);
count++;
dojo.xhrGet({url: 'addTable.html',
handleAs: "text",
preventCache: true,
content:{fieldId:count} ,
load: function(data) {
var newTable = dojo.place(data, tableNode, 'after');
dojo.parser.parse(newTable);
},
error: function(error) {
var newTable = dojo.place("AJAX error: " + error, deductNode, 'after');
dojo.parser.parse(newTable);
}
});
});
}
The remove function is :
function removetable() {
dojo.query('#removeTable').onclick(function() {
if (count != 0) {
var tableNode = dojo.byId('table'+count);
count--;
dojo.xhrGet({url: 'removeTable.html',
handleAs: "text",
preventCache: true,
content: {fieldId:count},
load: function(data) {
dojo.destroy(tableNode);
},
error: function(error) {
var newTable = dojo.place("AJAX error: " + error, tableNode, 'after');
dojo.parser.parse(newTable);
}
});
}
});
}
The count variable is declared globally.
The functions work correctly.
The problem I am having is when you remove a tableNode and then add a table node the node at that specific index will not execute dojo.parser.parse(newTable).
I put some output statements in my code to debug and all the references are correct.
So it works fine as long as you do not place a node with an id that has been destroyed.
Example: click add, table1 id is created, dojo parses it fine, all is well. click remove, table1 is destroyed, still ok. click add again, table1 is created, dojo does not parse this node.
Am I doing something wrong?
Looks like I did not destroy the dijit widgets correctly.
I added this inside the load callback of the remove function:
dojo.forEach(dijit.findWidgets(dojo.byId(deductNode)), function(w) {
w.destroyRecursive();
});
dojo.destroy(deductNode);
I assumed destroying the dom node with dojo.destroy would also remove the dijit widgets.
This is working correctly now.

Categories