I am trying to do a next/previous button on my calendar to show the next/previous month.
Ideally, the best thing would be not to refresh the page, but in the first place I don't mind having to refresh the page.
I have got a calendar($m,$y) function in php that let me change the value of my calendar directly in the url. For exemple (it's an image) :
http://localhost/VELO/index1.php?mois=3&year=2019
So basically, in this exemple, I would like my previous button to change the url to ".../index1.php?mois=2&year=2019"
I tried the following code (and many others) from one of the most answered question about this subject but it didn't worked :
<script>
function getQueryVariable(variable) {
var query = url.substring(1);
var vars = query.split('&');
for (var i=0; i<vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
var url = 'http://localhost/VELO/index1.php?mois=3&year=2019'
var mois = getQueryVariable(url, 'mois');
var year = getQueryVariable(url, 'year');
var params = { 'mois':2, 'year':2019};
var new_url = 'http://localhost/VELO/index1.php?' + jQuery.param(params);
// With this in my <body> :
// <button type="button" class="precedent">Prev</button>
</script>
But I am getting the following error :
The requested URL /VELO/new_url was not found on this server
In summary, what I am asking is :
Is the code I am using not appliable in this case ?
Is there an other way to change my url with a button ? (can I use $_GET['month'] ?)
Is it possible to do this without refreshing the page ?
Have your JavaScript listen to an onclick event binded to a button. If you don't want to refresh page you can call that link using ajax. I would recommend using JQuery to help you accomplish this.
I found an answer to my question !
At first, I tried the solution degreerichi sent me but it wasn't working really well.
Here is the first code that is NOT WORKING :
<script> // NOT WORKING
$(function() {
$('.precedent').click(function(e){
e.preventDefault();
var targetUrl = "http://localhost/VELO/index1.php?mois=6";
window.history.pushState(null, null, targetUrl);
setCurrentPage(targetUrl);
});
});
</script>
My problem here (if anyone still want to solve/explain it) is that the url is changing but my calendar is not changing. For instance, when I click on my previous button I have this in my localhost (image). You can see that the url changed but the calendar isn't the one for June (mois=6).
So here is how I solved the problem :
<script> // WORKING
$(function() {
$('.precedent').click(function(e){
e.preventDefault();
var targetUrl = "http://localhost/VELO/index1.php?mois=6";
window.location = targetUrl;
});
});
</script>
In this case my calendar is updating as follow this image.
Related
I have built two functions which work separately (when the other is deleted) but do not work together. The overall aim is that when a person selects the number of results they want to see per page, this then reloads the page, and the value is put in the url and then retrieved using get in php; and then on the new page the selected value in the drop down menu to is the value what triggered the reload.
Jquery
$(document).ready(function(){
//the first section takes the value from the php script and then selects the option if it's not null - this works fine on it's own
var data = "<?php echo $rp;?>";
if (data){
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
//this too works fine on it's own but not with the above
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
Together, the first works fine, in that it re-selects the right value if, say, I put ?results=50 after sales.php but then the jQuery to trigger the reload doesn't work. What am I doing wrong?
Just to clarify. The first page is called "sales.php" and the drop down menu has the currently selected value of "10", with 25 and 50 being other options. When I click on another number the jquery doesn't work. However should I type into the url the ending "?result=50", for example, it does work; and the drop down menu now shows 50; when i click on ten, the url updates, and the drop down shows ten also; the problem then is they seem to conflict only at the start, as it were.
It would seem the problem may concern how jquery deals with php. Take for example the following first example which works, and then the second which doesn't:
1)
$(document).ready(function(){
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
2) This change function however will not trigger a reload of the page because of the inclusion of the php defined jquery variable.
$(document).ready(function(){
var data = "<?php echo $rp;?>";
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
});
This achieves what I want (I don't know if the php posed a problem or not). The function is from here - Get url parameter jquery Or How to Get Query String Values In js.
Also, I'm surprised nobody more experienced than me didn't point out what also seems to have made a difference; the "first" function in the original post needs to in fact be second.
So the below will reload a new page, when a user clicks on an option in a select menu with pre-defined options for how many results they want to see per page; this value will then show in the url, and, importantly, the current select value of the select menu will now be this value also; this is important so that if the user goes back to the original number of views, the change() function works still.
$(document).ready(function(){
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
var data = getUrlParameter('results');
$('#bo2').change(function(){
var opt = $(this).val();
var url = "sales.php?results=";
var newurl = url + opt;
window.location.replace(newurl);
});
if (data)
{
$("#bo2 option[value="+data+"]").attr('selected', 'selected');
}
});
I have a translation plugin that utilizes Google's free website translation tool. I don't use their API, but only provide some creative options in how the tool is used on the website.
How it works: User clicks on flag or drop-down that fires event, then adds ?lang variable to the end of url after translation. User is able to change the url directly by modifying the ?lang url variable in the address bar.
This is tricky, especially because right now I'm using client-side functionality to do the work. I am using location.href to refresh the page, which also adds back the lang variable to the url after navigating to new page.
My problem is when user clicks on link to new page, this is what happens:
User clicks on new page link
Page refreshes to the new url WITHOUT the lang variable.
jQuery kicks in and refreshes page a 2nd time to add the url variable.
New page is now shown to user with the requested url variable.
This is 2 refreshes! Obviously not efficient.
I'm seeing that it might be best to change this to server side refresh instead, using PHP. I need some guidance on how jQuery and PHP will interact, if someone could show me an simple example.
Here is the jQuery code I have now for a single language case, when user changes url directly in the browser.
<script type="text/javascript">
jQuery(document).ready(function($) {
$.cookie("language_name", "Afrikaans");
$.cookie("flag_url", "<?php echo home_url(); ?>/wp-content/plugins/google-language-translator-premium/images/flags24/Afrikaans.png");
var language_name = $.cookie("language_name");
var lang = GetURLParameter('lang');
var googtrans = $.cookie("googtrans");
var lang_prefix = $('a.af').attr("class").split(" ")[2];
if (lang == null && language_name == 'Afrikaans') {location.href = document.location.href.split("?")[0] + "?lang=" + lang_prefix;}
function GetURLParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
if (googtrans != '/en/af') {
doGoogleLanguageTranslator('en|af');
}
});
</script>
<?php
if (empty($_GET['lang'])) {
header('Location: $_SERVER['REQUEST_URI'].'?'.$_SERVER['QUERY_STRING'].'&lang=en');
die;
}
?>
This could have a bit more logic to it, but it is the basic idea. This code would have to be as close to the top of the page as possible, because headers are only allowed to be sent before any output is printed on the page.
You can use JavaScript to append the lang parameter to every link on page load. You'll need logic to ignore external links and add ?lang or &lang based on the preexistence of a query string. And of course, it wouldn't do anything unless lang was already specified in the current URL.
You could modify your existing code to something like this:
...
if (lang) {
jQuery("a").each(function () {
// Logic here
});
}
else if (language_name == 'Afrikaans') {
location.href = document.location.href.split("?")[0] + "?lang=" + lang_prefix;
}
...
Take a look at Jquery : Append querystring to all links for examples of how to append the query string parameter.
I am currently trying to retrieve some data from book search sites and populate a personal database with that data. My idea is to inject the necessary jQuery on the page, so that when I see a title I think I'd like to return to in future, I can then just click a cheeckbox, make necessary additional comments, which I then hope to submit by AJAX to a PHP script which then populates my MySQL database for me with the appropriate title.
Do look at this example for a library catalogue:
// for every book entry, append checkboxes
$('.document-frame').append('<p>Choose:?<input type="checkbox" class="Jcustom_c" /></p><p>Serendepity?:<input type="checkbox" class="Jserep" /></p><p>Include snippet?:<input type="checkbox" class="Jsnippet" /></p>');
// append a Submit button at the bottom of the page, and a blank div for feedback upon success in POST-ing the necessary data
$('#resultPage').append('<input id="Justin" class="Jcustom" type="submit"/><div id="Jfeedback"></div>');
// whenever my checkbox is checked, retrieve / "scrape" the necessary book data
$('.Jcustom_c').change(function() {
if ($(this).is(':checked'))
{
var title = $(this).parent().parent().find('.title a').text();
var author = $(this).parent().parent().find('.authors a').text();
var publishd = $(this).parent().parent().find('.publisher').text();
var status = $(this).parent().parent().find('.metadata .summary').text();
var img_link = $(this).parent().parent().find('img.artwork').attr("src")
// create an XML string from that data. Escape "<" and ">", otherwise when we append the string to the browser for feedback, the browser will not render them correctly.
var appended = '<div class="Jappended"><item><title>' + title + '</title><author>' + author + '</author><publisher_n_edn>' + publishd + '</publisher_n_edn><status>' + status + '</status><image>' + img_link + '</image><serep>N</serep></item></div>';
// show the string just below the book title. Hence if I "pick" the book from the catalogue, the XML string will show up to confirm my the fact that I "picked" it.
$(this).parent().parent().append(appended);
}
// if I uncheck the box, I remove the XML string
else {
$(this).parent().nextAll(".Jappended").remove(appended);
$(this).parent().prevAll(".Jappended").remove(appended);
}
});
And then I have the AJAX:
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
$(".Jappended").each(function() {
var placeh = $(this).text();
string = string + placeh;
$('.results_container').append(string);
})
// these come from <textarea> boxes I append to the end of the page just before the Submit button. (Above, I did not include the jQuery to append these boxes.)
var odp = $("#odp").val()
var mre = $("#motivation_revisit").val()
var mra = $("#motivation_rationale").val()
var stu = $(".hdr_block h5 span").text()
var string = string + "<odpath>" + odp + "</odpath><stused>" + stu + "</stused><motivation><revisit>" + mre + "</revisit><rationale>" + mra + "</rationale></motivation></itemset>"
var post_var = { xml_string : string, source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
$('#Jfeedback').html(data);
});
My problem is that I can't seem to get the AJAX to work: When I click on my Submit button, I do not see the output I would expect when I used the exact same jQuery on an HTML file I called from localhost. This, which I called using http://localhost:8888/some_html.html worked:
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script>
$(document).ready( function() {
...
$('#Justin').click(function(e) {
e.preventDefault;
var string = "<itemset>";
/*
$(".Jappended").each(function() {
var post_var = { xml_string : "hello", source : "NUS" };
$.post('http://localhost:8888/db-ajax.php', post_var , function(data) {
// if (data == "Success") {
$('#Jfeedback').html(data);
// }
});
});
});
</script>
<body>
...
</body>
</html>
db-ajax.php is simply:
echo "Success";
I have read this post: jQuery cannot retrieve data from localhost, which mentions something about "JavaScript cannot currently make direct requests cross-domain due to the Same-origin Policy". Is this the reason why my code didn't work on the external page? If yes, what can I do to make the code work, or what other approaches can I adopt to achieve the same goal? I have mutliple book search sites that I am working on, and many of these do not have an API where I can extract data directly from.
Thank you in advance.
P.S.: I've also tried the suggestion by CG_DEV on How to use type: "POST" in jsonp ajax call, which says that $.post can be done with jsonp, which is the data type to use for cross-domain AJAX. Result: On Firebug I do see the POST request being made. But my function callback is not fired, and firebug doesn't register a Response body when at least "Success" should be returned.
you can set allow cross origin resource sharing
Follow two steps:
From server set this on response header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:*
//* if you want to allow it for all origin domain , or you can specify origin domains also to which you want to allow cors.
In client side add this on your page
$.support.cors = true;
Cons: It is not fully supported on ie < ie10.
I have a little question.
On my site i use for few jquery functions , they get some data and transfer by GET method to php helper. This is not work when i want to use the data in another php page. For example i have jquery that store id of the anchor:
$("#rightContent .users_list li a").live('click', function() {
var id = $(this).attr('id');
$.get("getHelper",{'userId':id},function(data){
$('#user_rightContent').html(data);
});
});
And in php file returned by "getHelper" i do:
if(isset($_GET['userId'])){
$id = $_GET['userId'];
//do something
);
The anchor of the live click lead to another page displayed by another php file where i want to use this id by using helper... This is work only if i stay on same page...
Can anybody help me in this problem?
thanks for advice
add return false at the end of live('click'....
live('click', function()
{
// code ...
return false;
}
or do that
live('click', function(e)
{
// code ...
e.preventDefault();
}
You're missing the extension on the filename.
Try it with:
$("#rightContent .users_list li a").live('click', function() {
var id = $(this).attr('id');
$.get("getHelper.php",{'userId':id},function(data){
$('#user_rightContent').html(data);
});
});
I'm working with jqueries address change event and am hitting a roadblock when a user copies and pastes a URL in the browser. I need to fist load a portion of the page that contains a form. I could do this after every pagination call but it seems really ineffecient.
Here is my current code block:
$.address.change(function(e) {
var urlAux = e.value.split('=');
var page = urlAux[0];
var start = urlAux[1];
if (page == "/visits") {
$.address.title("Profile Views");
if (start) {
$('#start').val(start);
// ***** If a user has copied and pasted this URL with a start value then I first need to load visits.php in the main div tag. Is it possible to see if this is loaded or not?
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
}
else {
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () { });
}
}
My attempted work around was this:
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
There must be a better way...this is realoading the same portion of the page (visits.php) with every pagination event. Is there a better way to load URLs and not have them trigger an address change?
Using paul's work around from his comments, but instead of Regex'ing html content in the visits.php form this solution will look for data() attached to #mainID.
Paul's work around notes:
After a bit more hacking I came up with this solution that seems to do
the trick. I'm not sure how good it is but it seems to do the trick. I
now get the main div id and do a regex match on a unique string in the
form. If I don't see it I load the form and then load the results. Not
sure if this is good practice or not but it seems to solve my issue.
Methodology to use .data() instead of a regex search of visits.php's html:
/*check if we're missing visits.php by looking for data() flag*/
if( !($("#main").data()["hasVisitsPhp"]) ){
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
/* we've loaded visits.php, set the data flag on #main*/
$('#main').data("hasVisitsPhp","loaded");
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
}
try window.location.hash instead. Changing the whole href can/will trigger a whole-page reload, while changing just the hash by itself should at most cause the page to scroll.