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.
Related
I've looked at a lot of StackOverflow answers but can't find an answer that is working. This seems like it should be so simple.
I have a PHP single page web app. It has a nav bar that loads pages as includes. Clicking the nav bar invokes a jQuery function to load a different include and inject a class into a div. This works in the nav.
In one of the includes, I have an HTML link:
<div class="page-content">
<a class='btn-primary'>See Examples</a>
</div>
This is the jQuery I want it to execute:
$(".btn-primary").click(function() {
alert('you clicked me');
$('.page').attr('class', 'page examples');
// REPLACE THE CURRENT INCLUDE
$('.page-content').load('includes/page-examples.php');
window.scrollTo(0, 0);
});
But the link does not execute the function. Changing it to a div does not work. Clicking will not even execute the alert.
I've tried to put the link in php echo or php print, but it makes no difference. I've checked all my naming and there isn't a typo.
What is the best way to make it work?
----- EDIT -----
The jQuery is being called from a js file called from the index.php head tag, and is in the DOM ready statement. It looks like the DOM is ready before the include with the link loads. If I remove the link's js from the js file and put it in the include with the link, then the link works, but this will create a problem as other internal links are added to the site in other includes.
What is the best way to fix ?
It sounds like your javascript click binding $(".btn-primary").click(...); is executed on DOM-ready.
But at that time the .btn-primary is not yet in the DOM as it only gets inserted into the DOM after you include it (if I understood it right).
Therefore the binding never happens and after your first include gets loaded the click binding code is never executed again and therefore the .btn-primary element has no onClick event.
You need to run your javascript snippet after that .btn-primary element gets inserted in the DOM, eg. like this:
$('.page-content').load('includes/first-include.php', function(){
$(".btn-primary").click(function() {
whatever...
});
});
First step
Check if you are importing jQuery library (it seems obvious, but we
can forget to import the library sometimes or the library URL is wrong
and the browser cannot recognize it as well). And remember you need import jQuery before the function you wrote.
Second step
If you need to inject a class into some element using jQuery, the easiest way to do this is:
Instead...
$('.page').attr('class', 'page examples');
Change to...
$('.page').addClass('examples');
In this example above, you can omit the 'page' and let only 'examples', because the class ".page" is already there.
Another thing, this will only work if the element with ".page" class already exists in your HTML.
Third step:
Add a callback to .load function and see if it worked properly:
$('.page-content').load('includes/page-examples.php', function(){
alert("Nice, my content was loaded!");
// You can put this action here, so it will execute after the content is loaded
window.scrollTo(0, 0);
});
So basically my question is very simple, I have two buttons, I for page forward, one for page backwards, If one of those is pushed, a javascript function is called inside an onClick Event. Javascript then gets the variables of the page and then redirects to the next page, the only problem is, that I need to pass those variables to PHP in order to put them into the Database. So for that I make a load of cookies to pass the variables.
However, I was wondering if something like this would work :
<form>
<a onClick="nexpage();" onSubmit="phpScript.php"> <img src = "previous button.jpg"/> </a>
</form>
The idea behind this is that I want to store the variables in a PHP script, which will put them in a display:none; <div> and then for javascript to get the variables out. This instead of using cookies.
So is it possible to run a PHP script to get the variables and when the script is finished to get them, Javascript kicks in to redirect to the next page...
The reason I don't test this at this moment, is that my code is 100% complete, I don't want any sudden changes that maybe won't work at all. Yes I know back-up this and that, but I thought just asking here, maybe someone will know the answer!
Sincerly,
Harmen Brinkman
You can also use onClick = "this.form.submit(); return false;".
There is no any event like onSubmit for link, instead form do have onSubmit event.
Normal Way as OP asked.
<form action = "phpScript.php" method = "POST">
you can use document.getElementById("my_form").submit();
#Dipesh Parmar – Good point. You could also do:
window.onload=function() {
document.getElementById('my-form').onsubmit=function() {
// do what you want with the form
// AJAX POST CALL TO PHP PAGE
// Should be triggered on form submit
alert('hi');
// You must return false to prevent the default form behavior
return false;
}
});
Inspiration by Capture a form submit in JavaScript
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.
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.
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.