AJAX and JS for LIKE Button - php

I'm trying to learn how make an AJAX script
for a LIKE button, on my website. I have the following questions:
if i'm sending 1 variable.... id.. I do this
data: "action=vote_up&id="+(this).attr("id")",
is this syntactically correct if i'm sending two variables id and id1 ?
data: "action=vote_up&id="+(this).attr("id")&id1="+(this).attr("id1")",
2) What goes into the href attribute? The php page or the AJAX?
<img scr="like.png">
3) which is run first.. The php page or the AJAX.
4) Is it mandatory for me to use jQuery or Pure Javascript for running AJAX
thanks for your time and patience. I most appreciate it.

1) Yes, you could simple undestand it as a PHP-Get request to a script, so multiple vars are possible, like Adam mentioned.
2) For backwards compatibility you should just link to a PHP/whatever-Script that provides the same functionality but doesn't rely on javascript (Not everyone has js enabled). In your javascript you just disable the defult click actione ( see: http://api.jquery.com/event.preventDefault/ ) otherwise it you only want to allow the like funktionality if js is enabled than you could just link to the page anchor '#'.
3) The page runs first. It is progressed by the server and than sent to your browser. In the browser the recieved javascript will start its action.
4) Everything you are using in jquery is based on simple javascript functions, but jquery is much more comfortable ;) The equivalent to the ajax method of jquery is XMLHttpRequest ( http://www.w3schools.com/xml/xml_http.asp )

Here is a idea, hope it helps.
If handle_vote.php is the URL responsible for the handle the up vote, you must do two things:
the a href is the URL with the query string for the up vote, your data, is this case. It must be generated for you server application. It will be used in case of no javascript.
you should put you event to handle the up vote in the a onclick event, to send the ajax request, and use the preventDefault jQuery function to avoid the default event. In this case, a href will never be used, the js will suppress the link click.
A code sample will be almost like this, in you php page:
<a class="like" href="handle_vote.php?action=vote_up&id=<?php echo $post_id; ?>"><img src="like.png"></a>
And it as your jQuery script:
$(function() {
$('a.like').on('click', function(e) {
e.preventDefault();
$.get($(this).attr("href"));
});
});
You can personalize as you like, it is only the idea of how to do it.

<img scr="like.png"> put onclick event on that link, and make AJAX request` to increment count, on success response update count clicks on button. And you forgot about one thing, you should save the state of that button. Because one user can go to your site and click 1000 times on it.

Related

Unable to understand <A HREF> tag and javascript call

I have a php application in which the web page displayed to the user. The page has some links "Edit", "Rename", etc.
When the user clicks on the link a dialogbox prompts. The dialogbox is nothing but a HTML <div> form that gets instantly displayed when the user clicks on the "Rename" or "Edit" link.
When I looked at the html source code (i.e. view -> source in Internet Explorer) I found the following Javascript and HTML code
<a class="update renameButton" href="javascript:void(0);">Rename</a>
I'm unable to understand how the dialogbox gets promted with the above code.
I expected the code to be something like the following:
<a class="update" onclick='rename();' href="javascript:void(0);">Rename</a>
Can someone help me understand this?
Some JavaScript loaded from a <script> element probably binds an event handler function to the element.
The event handler is most likely bound to the element elsewhere (from an included JavaScript file perhaps). For example:
document.getElementsByClassName("update")[0].addEventListener("click", function () {
// Do something on click of the first `.update` element
}, false);
you should not setup event listeners in html anymore like with onclick.
the page registers an event listener to the Object. e.g. with a library like jQuery.
You are absolutely correct! That is very natural to expect such a thing except that there are other ways to bind an event to an object as well.
If you check the JavaScript code on the page I am sure you will find perhaps something that looks like $('a.renameButton').click(function(){}); (if the site is using jQuery) or something similar that binds the onclick event of that particular tag to perform some specific actions.

javascript/php - record click destination before redirect

Say I have the link:
google
Is there any way I can record the click (with php/sql)? For example an onclick event to load ajax? Would the ajax run before the page redirects? I want to avoid:
google
You could change your link to:
TEST
And then use the function:
function recordClick(t) {
//Insert AJAX here. t contains the URL
document.location = t;
}
You could then wait for the AJAX request to complete before using the document.location part. However I would suggest simply using a separate file to log clicks like you have already suggested because it is an immediate action that doesn't require JS to be on, and that provides immediate feedback.

Ajax redirect based on the fragment?

consider I have an array with some urls:
$array[0]='mywebsite/pagea';
$array[1]='mywebsite/pageb';
$array[2]='mywebsite/pagec';
//> please note this is the PHP array, but I can output as a javascript array without problems
I will output them in my link.php
Is there a way with jQuery to read that fragment (idX) and then redirect to the corrispondent url?
Edit
Thinking about compatibily (browsers without javascript) now let's consdier I have this kind of link:
pagea
pageb
pagec
For browser without javascript the link will work as normal, for every else i will do like
$('.intercept').onClick( function (){
//> append the hashtag to the current url
//> make the right redirect after some interval (ie this.href)
//> how? xD
});
At this point i have only to check if the url was opened with an hashtag and make the right redirect.
I misread your original question. Sorry.
Assuming $array is a javascript array or object.
$('a').click(function(){
var url = $(this).attr('href'),
id= parseInt(url.split('#id')[1]);
window.location = $array[id];
});
If you want to trigger the redirect even if someone visits the page with a hash, you want to use a hashchange event. The jQuery bbq plugin makes this easy to do cross browser with its hashchange event.
It is a pretty lightweight plugin so I doubt there's going to be much advantage to coding up something on your own that will work cross browser and you would likely end up with similar code to the bbq plugin.

Handling clicks for jQuery AJAX (with PHP)

Not sure how to phrase this question exactly, but I'll give it a shot. (If you have a suggestion for how to phrase it better so others can find it, tell me and I'll edit it).
I want to know the best practices for handling clicks on a page that are then processed using AJAX. I have been temporarily using code that looks like this in the HTML:
Click me!
And in jQuery I handle the clicks by binding click to the href.
Of course, I know that you should not be making this known to the user.
So how should I be handling these clicks?
You should make your HTML so that it works if Javascript is off. Don't mix content with functionality, so inline Javascript is usually not a good solution.
So, in your case:
Meaningful description!
Then you can add a class (or check the text inside, or something else) to handle it on the Javascript side.
Make sure to use event.preventDefault() to stop the page from changing if Javascript is enabled.
So the jQuery would be
// Target only anchors with class "ajax"
$("a.ajax").click(function(event) {
// Handle AJAX etc here.
// ...
event.preventDefault(); // <== Don't navigate away from page
});
I'm not very sure to understand your question too xD
You can handle a click by doing something like
$("a").click(function() {
// do some stuff
});
Does this answer to your question ?
Edit :
Ok.
You just need to do something like this :
<a href='link' onClick='return MyClass.myFunction()'>keyword </a>
If I good remember, you return FALSE in JS to stay on the same page (and do some process with Ajax). If if JS is not activated, PHP will be used ;-)
I usually have the href link to a static php page, and then use javascript to change the link href to the ajax processing page, then you can reference it in the ajax call.

How to use Post method without a Form

I am that kind that spends more time looking for bugs in web projects and correct them, but I still have one question about the use of the GET and POST method
To summarize , I often use the GET method for queries that may be coming from links or simple buttons example :
Click me
and for forms (signup,login, or comment) I use the post method. but the question is:
sometimes (Multi-steps signup for e.g), I may need to pass the info collected from the form in page 1 to a page 2 (where the user can find a captcha for e.g). in order to send them to the database if the captcha test is Okey. But the question is , how to pass those info to a next page via a POST method without using a hidden form?
Do I need to recreate a POST method from scratch with a socket?
thank you
You can use JavaScript (jQuery):
First u need to load jQuery ( using google as host or you download it):
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
Then...
<script type="text/javascript">
$(document).ready(function() {
$('#Link').click(function() {
$.post("example.php", { n: "203000"} );
});
});
</script>
<a id="Link" href="#">Click me</a>
Edit:
after that save it in the SESSION in example.php
$ _SESSION['N'] = (int) $_POST['n'];
When this value will be stored on the server side. And tied to the client session, until he closes browser or that it set the time for that session on the server side runs out.
Edit2:
There is also another possibility to post requst, yes ..
But I do not like this method myself ...
And here is the form used, something the OP did not want.
<form name="myform" action="example.php" method="POST">
<input type="hidden" name="n" value="203000">
<a id="Link" onclick="document.myform.submit()" href="#">Click me</a>
</form>
Use sessions to store the data until you submit them:
http://de.php.net/manual/en/intro.session.php.
Using sessions has a big advantage,
once you have verified the data you can store it.
Always keep in mind that users may manipulate POST requests!
If the problem is to pass info between pages like in a multi-step form you should use session (if you are using PHP).
By the way for send a POST request without form you need to use CURL like in this example
The statement is a HTML language statement used by a browser to initiate a POST/GET data relation. The Browser is the execution environment.
You can use other languages (and their execution environment) like Java, Java Script, C#, etc. to initiate HTTP POST/GET data relations.
Sorry if I'm not understanding you correctly, but from what I'm reading, you want to access form data entered on page 1 (using a form with a post method) on page 2? If so, use the $_POST autoglobal array. For example, $nameOnPage2 = $_POST['nameFromPage1']. You don't have to create a form on the second page for this.

Categories