favorite button dynamic changing the name - javascript

on each post page has a button to "like" how can I check if the post was liked and change the button name, for example, "liked" and if not, by clicking the button would be done, but everything in the background, I have very shallow knowledge of javascript, but I know I'll need ajax for it. already set up a small script in php / mysql that returns a json { "favorite": 1} when the post is already liked or changes to liked, and its natural state is { "favorite": 0}
Because you can only like the post being logged into the site, the user id will be set by session, and the id of the post will be sent using the POST method
Ex:
Favorite
... Sorry for my bad english

set the status on the server I am assuming the status is in the $favorite var
<a id="1234" href="site.com/post/like"
class="like <?PHP echo $favorite?"liked":""; ?>">Favorite</a>
call when clicked
like this
$(function() {
$(".like").on("click",function() {
$.post("likeornot.php?id="+this.id,function(data) {
$(this).toggleClass("liked",data.favorite==1);
// you can set the html of the link here too
});
});

Related

go back to the previous page after changing the data in for in php

i am trying to redirect the page to previous page after edit the form..
i have these two url's for example
http://localhost/******/viewclientadmin.php?id=14
and
http://localhost/****/clientadminedit.php?id=106
so client after edit the form i want them to redirect to the viewclientadmin page
i already tried like this
if($DB->execute($chk_qry,$parms)) {
header("location:javascript://history.go(-1)");
}
but it's not going back..it staying on same page..
can you please help me out..how to do that..
thanks in advance...
Store your url in session like this and call that variable in another page in header
In your viewclientadmin.php page add these two lines
$page = "viewclientadmin.php?id=$id";
$_SESSION['page'] = $page;
And in your clientadminedit.php page add like this
if($DB->execute($chk_qry,$parms)) {
header("Location: " . $_SESSION['page']);
}
it will work...try
You can use
if($DB->execute($chk_qry,$parms)) {
header("Location: localhost***.php?$qry");
}
Instead of history.go by this way you will get your id on viewclientadmin and using that Id you will be able to fetch data from db and assign to your form.

JavaScript/Ajax to Dynamically Update WTForms Select Field

OK. I know this has been tackled many times but I can't find an answer with a useful example of javascript to use.
Say I have this form:
class MyForm(Form):
category = SelectField("Category")
issue = SelectField("Issue")
What I need is for whatever is selected in 'category' at runtime to determine what the user sees in the issue dropdown without a POST of any kind ocurring. I know how to dynamically create the choices in the view from my database query. I even have gone so far as to create a dictionary of "issue choices" based off of category choices.
I just can't for the life of me figure out the javascript I need so that on select of something from the category drop down determines whats in the issue dropdown.
I found the info I needed by looking at the example at Flask jQuery AJAX Example -
- it is a minimal working example, almost a
GIST or a book chapter.
I came up with an example very close to jsbueno's implementation. You can find the Gist here. The .py file is a standalone example.
In your html template use jquery to register an ajax request when you click the select field. If the request is a success the html for the select field gets updated with the new select options (send as a response from the server). Look at the actual HTML generated by the template to see how the select field looks like.
<form action="" method="post" id="selectDevice" name="device">
Nummber of Devices: {{ form.selectAmount(size=1) }}
Select device: {{form.deviceAddress() }}
</form>
<script type="text/javascript" charset="utf-8">
$("#deviceAddress").click(function(){
$.ajax({
url: '/selectform',
type: 'POST',
data: $('#selectDevice').serialize(),
success: function(selectOptions){
$("#deviceAddress").empty();
for (var i = 0; i < selectOptions.length; i++){
$("#deviceAddress").append(
$("<option></option>")
.attr("value", selectOptions[i][0])
.text(selectOptions[i][1])
);
}
}
});
});
</script>
On the server side, use a route for the ajax post request.`As example this route changes the options depending on another form field (the information got send over with the data tag in the ajax request). In WTForms the select field options is a list of tuples containing an ID and name, I kept this the same on the python side.
#app.route('/selectform', methods=['POST'])
def updateselect():
deviceAmount = int(request.form.get('selectAmount'))
choices = [('device{}'.format(i), i) for i in range(deviceAmount)]
response = make_response(json.dumps(choices))
response.content_type = 'application/jsons'
return response`
Only one remark: the ajax request is performed on dropping down and on collapsing. The last part is not necessary of course, there is probably a way to structure the jquery so it only requests on dropdown.

Disable AJAX button after nth click

Given I have a model Post which can have up to n Comments (the number is controlled by the Backend) and I have a view which allows to add a Comment via a AJAX request. What is the best way to tell the view upon the nth request to disable the Add-Comment-Form?
The nth request is successfull so status code should still be 200/201 but the backend already "knows" that the nth + 1 call will invalidate the Post, so i want to somehow tell this to the view so it can take action before the user experiences the (catched) error upon nth + 1 submit.
By now the backend renders html which is then simply attached to a div in the DOM, with JSON I might add an additional field but then would move the templating to the view again.
If someone has an idea for an elegant solution?
Try having your server render javascript value for comment count and max comments. Then you can increment the count value in your success function as well as perhaps render the html comment.
Something like
var commentCount = *value from server*;
var maxComments =*value from server*;
$('#mybutton').click(function(){
$.ajax({
// your code here
})
. success(function (response) {
// process response
commentCount ++;
if( commentCount >= maxComments)
$('#mybutton). prop('disabled', true);
});
Just hide the "Add comment" button by JavaScript, when it will be "nth + 1". Or remove eventListener from button and change caption to smth like "You reached max comments".
Keep a track of the number of clicks. After the n th click, you can change the disabled attribute of your button to true.
$(".myButton").attr("disabled",true);

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

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