back button scroll position - php

After I submit a form the position will return to the top of the window. Instead of going to the previous position.
Looking at using scrolltop to rememeber the positon or do you have a better idea?
I'm using stuff like PHP5, jQuery and MySQL.

First create an anchor in your page where you want the visitor to get to when they submit the form.
Then in your form action or redirect point to file with the anchor
e.g.
<div id="view_from_here" >.....
then
<form action="myfile.php#view_from_here" ....

Check this out:
<script type="text/javascript" src="der/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="der/jquery.cookie.js"></script>
<script type="text/javascript">
function get_position(){
var top_position = document.documentElement.scrollTop;
$.cookie('pos', top_position);
};
function set_position(){
var top_position = $.cookie('pos');
window.scrollTo(0,top_position)
$.cookie('pos', null);
};
</script>
</head>
<body onload="set_position();">
.
.
.
<form method="post" action="" onsubmit="return get_position();">
</form>

If you submit you Form via Ajax it won't change anything (maybe that is an option, if you redirect to the same page anyway). You can also save the position in a Cookie via JavaScript before submitting and retrieve and set the value when the new page is loaded (e.g. with jQuery scrollTo). Or you just set an anchor on your Form field (which is very likely to be the last position the user scrolled to) and scroll back to the form after submit.

Related

How to submit form without refresh, show output, reload form, rinse and repeat

I have a form that has drop down list options, an input box and a submit button. The select options are dynamically compiled. I place this form on my page by inserting;
<div id="dropdown">
<?php include("./listforward.php"); ?>
</div>
listforward.php contains;
...
<form id="changeforwardForm" method="post" action="changeforward.php" class="ajaxform">
...
</form>
changeforward.php does some work and gives a message;
<?php echo '<div style="color:red">'.$msg.'</div>'; ?>
After submit, this message is displayed near the top of the page
<div id="testDiv"></div>
and, the entire form is reloaded to show updated list options. The problem I have is that the message shows only once at the top from the first submission, and on the second submission it opens a blank page and shows it there.
I am aware that this has something to do with .live() or .on() but for the life of me I can not figure out how to apply it.
My external Javascript files
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
jQuery Form Plugin
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function(){
var options = {
target: '#testDiv', // target element(s) to be updated with server response
success: showResponse // post-submit callback
};
// bind form using 'ajaxForm'
$('.ajaxform').ajaxForm(options);
});
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
$("#dropdown").load("index.php #dropdown");
}
</script>
I also have another form on the same page (currently disabled). I would like to target the output of this form and have it display its message at #testDiv.
Any kick in the right direction would be much appreciated!
Regards Steven
you havn't shown all the code, but from what i can understand you use:
$('.ajaxform').ajaxForm(options);
});
to attach your function to the from submit.
Then as you said you reload the form so the function is not attached any more.
then when you resubmit it behaves like a regular submit.
you should reattach your method to the form after it is reloaded, i.e. run this again:
$('.ajaxform').ajaxForm(options);
});

php ajax refresh part of page on click

I want to be able to click on a link lower down my PHP page, it send a variable and outputs the result in a <div> tag at the top half of the page.
I've linked to latest jquery, and so far I have this in my <head>:
<script type="text/javascript">
$().ready(function() {
$("#result").load("crimes_result.php");
});
</script>
And in my <body>:
<div id="result"></div>
What I need though, is that the div to be shown and depending on the result of a variable sent by a link the user clicks lower down the page.
like crimes_result.php?id=4334 or crimes_result.php?id=54543
How can I finish my script so it does that?
NOTE: I'm useless in ajax/jquery/javascript
If I understand correctly, simply call .load() from a click event and pass it the href of the link:
HTML:
<a class="loadlink" href="crimes_result.php?id=4334">Click Me<a>
JS:
$(".loadlink").click( function(event) {
event.preventDefault();
$("#result").load($(this).attr("href"));
});
Example: http://jsfiddle.net/jtbowden/ueucL/1/

Refresh single page PHP element using button

I have a single page quote generator, it works by holding the quotes in a 2D array and generating a random number to pull from the matching value in the array using PHP every time that the page is refreshed, I want to change this and make it so that only the element is changed when you press a button, reducing the http requests to the server.
I have tried various "onClick" methods but they never seem to work, I'm assuming that this is something that I should use Javascript (Or any js libraries) for. The function that I want to run when the button is pressed is this:
<?php
$max = max(array_map('count', $arrCSV));
$num = rand(0,$max);
$quote = $arrCSV[0][$num] . "." ;
echo $quote;
?>
Any help is much, much appreciated.
Like, #Dr.Kameleon, this cannot be done with PHP alone.
Using jQuery, you can reload an element like this
$("#yourdiv").load("the/page/from/where/it/should/be/updated.php");
Attach it to the click event of the button
$("button").click(function() {
$("#yourdiv").load("the/page/from/where/it/should/be/updated.php");
});
JQuery's load method could do miracles there.
Here some working example.
Create html page:
<html>
<head>
<title>JS-ajax-PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
// Let's use jQuery library:
$(document).ready(function() {
// get element with id refresh, on click do function...
$('#refresh').click(function(evt){
// get element with id report, load content to element
$('#report').load('/time.php');
evt.preventDefault();
})
});
</script>
</head>
<body>
<button id="refresh">Обновить</button>
<div id="report"> </div>
</body>
</html>
and php file time.php:
<?php
echo date("Y-m-d H:i:s");
Enjoy.

Trying to display a calendar using jquery ui

I am using the framework codeigniter and trying to use jquery for the purpose of displaying and allowing the user to chose a time period in which he would like to preform his search. I have the date and the text field displayed but when I click on the text field I don't get any calendar to chose a date from.
This is my view:
<html>
<head>
<script type="text/javascript" src="<?php echo $jquery?>"></script>
<script type="text/javascript">
$(function() {
$( "#datepicker" ).ui-datepicker();
});
</script>
</head>
<body>
<div class="demo">
<p>Date: <input id="datepicker" type="text"></p>
</div><!-- End demo -->
<div style="display: none;" class="demo-description">
<p>The datepicker is tied to a standard form input field. Focus on the input (click, or use the tab key) to open an interactive calendar in a small overlay. Choose a date, click elsewhere on the page (blur the input), or hit the Esc key to close. If a date is chosen, feedback is shown as the input's value.</p>
</div><!-- End demo-description -->
www.msn.ca
<?php echo form_open('search/submit'); ?>
</body>
</html>
It's been taken from the sample code: http://jqueryui.com/demos/datepicker/
FYI I am using jQuery UI 1.8.16
Not sure what's wrong here.
If anyone thinks the controller is relevant then here it is:
<?php
class calendarController extends CI_Controller{
public function index()
{
$this->load->helper('url');
$data['jquery'] = base_url("jquery.js");
$this->load->view("jqueryView", $data);
}
}
?>
I do not see links to jQuery JS and CSS files on you page. Try something like this:
<link href="Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.7.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.8.16.min.js" type="text/javascript"></script>
You can place them anywhere on your page. Better at the end so that your pages shows faster. Use datepicker() inside jQuery load function, like in your code to make sure that nothing is broken
You're building your url wrong.
Should be:
$data['jquery'] = base_url().'jquery.js';
which gives in your view: http://www.yoursite.com/jquery.js.
I have some doubt on the actual true position of that script. Change it accordingly to your folder structure, just keep in mind that base_url() returns your url like this, with the trailing slash:
http://www.yoursite.com/
Also, you you're not loading jQuery UI, so add that too (same way as above)
Another thing, your input lacks the name attribute, you need it in case you want it to be fetched by php. AND, it's outside the form, so it won't work. This is just a note, maybe you don't want to use it that way, but just in case...
Shouldn't you place your datepicker initialization inside the jquery ready event handler ?
Like so:
$(document).ready(function(){
$( "#datepicker" ).datepicker();
});

Access a JavaScript variable from PHP

I need to access a JavaScript variable with PHP. Here's a stripped-down version of the code I'm currently trying, which isn't working:
<script type="text/javascript" charset="utf-8">
var test = "tester";
</script>
<?php
echo $_GET['test'];
?>
I'm a completely new to both JavaScript and PHP, so I would really appreciate any advice.
UPDATE: OK, I guess I simplified that too much. What I'm trying to do is create a form that will update a Twitter status when submitted. I've got the form working OK, but I want to also add geolocation data. Since I'm using Javascript (specifically, the Google Geolocation API) to get the location, how do I access that information with PHP when I'm submitting the form?
The short answer is you can't.
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
You're doing a $_GET, which is used to retrieve form values:
The built-in $_GET function is used to collect values in a form with method="get".
In other words, if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
As JavaScript is a client-side language and PHP is a server-side language you would need to physically push the variable to the PHP script, by either including the variable on the page load of the PHP script (script.php?var=test), which really has nothing to do with JavaScript, or by passing the variable to the PHP via an AJAX/AHAH call each time the variable is changed.
If you did want to go down the second path, you'd be looking at XMLHttpRequest, or my preference, jQuerys Ajax calls: http://docs.jquery.com/Ajax
_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). You need to rethink. You could make a php variable $test, and do something like:
<?php
$test = "tester";
?>
<script type="text/javascript" charset="utf-8">
var test = "<?php echo $test?>";
</script>
<?php
echo $test;
?>
Of course, I don't know why you want this, so I'm not sure the best solution.
EDIT: As others have noted, if the JavaScript variable is really generated on the client, you will need AJAX or a form to send it to the server.
If showing data to the user, do a redirect:
<script language="JavaScript">
var tester = "foobar";
document.location="http://www.host.org/myphp.php?test=" + tester;
</script>
or an iframe:
<script language="JavaScript">
var tester = "foobar";
document.write("<iframe src=\"http://www.host.org/myphp.php?test=" + tester + "\"></iframe>");
</script>
If you don't need user output, create an iframe with width=0 and height=0.
try adding this to your js function:
var outputvar = document.getElementById("your_div_id_inside_html_form");
outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';
Later in html:
<div id="id_you_choosed_for_outputvar"></div>
this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!.
This solution is working fine for me.
In your specific geolocation case you can try adding the following to function showPosition(position):
var outputlon = document.getElementById("lon1");
outputlon.innerHTML = '<input id=lon value='+lon+'>';
var outputlat = document.getElementById("lat1");
outputlat.innerHTML = '<input id=lat value='+lat+'>';
later add these div to your html form:
<div id=lat1></div>
<div id=lon1></div>
In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.
Hope this will help.
Well the problem with the GET is that the user is able to change the value by himself if he has some knowledges. I wrote this so that PHP is able to retrive the timezone from Javascript:
// -- index.php
<?php
if (!isset($_COOKIE['timezone'])) {
?>
<html>
<script language="javascript">
var d = new Date();
var timezoneOffset = d.getTimezoneOffset() / 60;
// the cookie expired in 3 hours
d.setTime(d.getTime()+(3*60*60*1000));
var expires = "; expires="+d.toGMTString();
document.cookie = "timezone=" + timezoneOffset + expires + "; path=/";
document.location.href="index.php"
</script>
</html>
<?php
} else {
?>
<html>
<head>
<body>
<?php
if(isset($_COOKIE['timezone'])){
dump_var($_COOKIE['timezone']);
}
}
?>
JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.
I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?
<script type="text/javascript">
function gotzpl(){
var query = window.location.search.substring(1);
if(query){
}else{
var timez = Intl.DateTimeFormat().resolvedOptions().timeZone;
if(timez != 'undefined'){
window.location = "https://sks.com/searches.php?tzi="+timez;
}
}
}
</script>
<?php
// now retrieve value from URL and use it in PHP;
// This way you can get script value in PHP
$istzg = $_GET['tzi'];
?>
<body onload="gotzpl()">

Categories