Preapring for a Facebook competition while I have spare time, the Publish function with facebook has a once posted javascript function that you can define.
What I am looking to do is call a function to write a value unto a php form which will then be posted and submitting data into a database. I have tested to the extent that I know the idea is sound just calling a basic alert, I am just not sure how to get from calling the function to writing the value into the form.
This value I need to be able to call on in the page that the data is being posted to, to base an "if function" off, basically if "True/Yes" then I need it to process another php script in addition to the data its posting to the database
What I have now is:
<script type="text/javascript">
function isShared()
{
alert("Yes");
}
</script>
<input class="fieldbox" name='shared' type='hidden' value="value of 'display_alert()'"/>
I know it cannot be an alert, but this is pretty much where my current javascript skills leave me stranded.
<script type="text/javascript">
function isShared()
{
document.getElementById('xshared').value = 'Yes';
}
</script>
<input class="fieldbox" id="xshared" name="shared" type="hidden" value="" />
This will add the value Yes To the hidden field once isShared is called.
Are you looking to have the form automatically posted without the user clicking anything but the share button? The only reason I ask is that it sounds like what you are looking for is AJAX, to post data to the database silently without the need of the user to navigate away from their current page.
I'm still not 100% clear on what you're asking, but are you just looking to emit a server-side PHP variable into client-side JavaScript code? Something like this?:
<?php
// some code, etc.
$myVariable = "foo"; // some value
// more code, etc.
?>
<script type="text/javascript">
var myVariable = '<?php echo $myVariable; ?>';
// more JavaScript code, etc.
</script>
This would emit to the page as:
<script type="text/javascript">
var myVariable = 'foo';
// more JavaScript code, etc.
</script>
Basically anywhere that you need the literal value from the PHP variable, you'd write:
<?php echo $myVariable; ?>
I am not clear how exactly you are aiming to post the form data but you can set the input value using jquery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
$('#input1').val($('#input1').val() + 'more text');
<input id="input1" class="fieldbox" name='shared' type='hidden' value=""/>
Related
I would like to pass the value of a variable from one page to another without using a session variable or a cookie, how could I do? Besides this we say that the page must pass the value to another is a page that does not interact with the user as he has only the task of informing him that after a few seconds will be redirected to the next page, to do this I used a Javascript function. I thought then enter the variable value within a field "hidden" But it is not possible to push a button submit do not know how to send data to another page using a form. Could you give me some advice? I am posting my code below:
<?php
if (!mysql_query($sql,$conn)) {
die('Error: ' . mysql_error($conn));
} else {
$PartitaIva = $_POST['PartitaIVA']; echo $PartitaIva;
?>
<form name="passaggiopartitaiva" action="inserimentodati_refaziendale.php" method="post">
<input type="hidden" name="PartitaIva" value="<?= $PartitaIva ?>">
</form>
<p> Modulo inserito a sistema, verrai reindirizzato alla pagina principale </p>
<script>
window.setTimeout ("location.href=('inserimentodati_refaziendale.php')", 1000);
</script>
<?php } ?>
How about setting a timer at load, once your timer runs out, it will submit your form and the user will never know. Try something like this:
$(document).ready(function() {
setTimeout(function() {
$("form").submit();
}, 5000);
});
You can either use some like what CodeGodie posted:
$(document).ready(function() {
setTimeout(function() {
$("form").submit();
}, 5000);
});
or
window.setTimeout ("location.href=('inserimentodati_refaziendale.php?varName=<?= $PartitaIva ?>')", 1000);
And then you could just use $_GET["varName"] on the "inserimentodati_refaziendale" page.
But either way, what is the purpose of doing this? and why do you NOT want to use sessions?
If you're attempting to submit the form after a certain amount of time elapses, you should give the form a name attribute (which you already did, passaggiopartitaiva) and then change:
location.href=('inserimentodati_refaziendale.php')
To:
document.passaggiopartitaiva.submit();
Then the values of your <input> tags will actually be submited, assuming you gave those tags name attributes.
And it would be better to put javascript either in a separate file or in the <head> than to just throw it wherever like you're doing.
If you're using JQuery (which doesn't seem to be the case) then see CodeGodie's answer for a cleaner way to do the Javascript than what you've done.
I have a JavaScript function (which users on this forum graciously helped me construct) that passes variables via POST to a PHP file with a query for inserting the data to a MySQL database.
The function is invoked "onchange" for a series of 2000+ rows that are spit out from a MySQL database. I use the ID of the row to give each form field a unique name/id, like this:
echo "=<select name='$AdvertisersSQLResult[id]geolocation' id='$AdvertisersSQLResult[id]geolocation' onchange = 'insertAdvertiser()'>";
The JavaScript function looks like this:
function insertAdvertiser() {
var data = $('#<?php echo $AdvertisersSQLResult[id]?>dataid,#<?php echo $AdvertisersSQLResult[id]?>industry,#<?php echo $AdvertisersSQLResult[id]?>geolocation').serialize();
$.post('/database/InsertAdvertiserRelationship2.php', data);
return false;
}
As you can see, I'm attempting to pass PHP variables as part of the form id values. However, this doesn't work, as the function is written to the page once (in the section) without any variables yet populated.
In other words, I'd like to have this JavaScript function utilize whatever PHP variable is being passed to it dynamically. I've looked at other threads about passing a PHP variable to a JavaScript function, but I can't find any reference to how this can be done dynamically, such that the JavaScript function changes to use a different PHP variable each time (if that makes sense).
Thanks for any help...
Well yes because you'd need a seperate insertAdvertiser() method for every advertiser on the system.
A better way to do it would be to do this:
Javascript:
// This line turns your PHP array into a Javascript object
var advertisers = <?php echo json_encode($AdvertiserSQLResult); ?>;
function insertAdvertiser(id) {
$.post('/database/InsertAdvertiserRelationship2.php', advertisers[id]);
}
// Try not to use attributes to bind events, use handlers like this instead.
$(document).ready(function() {
$('select').on('change', function() {
// Reads the advertiser id from the data attribute
insertAdvertiser($(this).data('advertiserid'));
});
});
HTML:
<select data-advertiserid="<?php echo $AdvertiserSQLResult['id']; ?> class="advertiser-select">...</select>
I wrote this as I went along so apologies if I've overlooked something.
See:
jQuery Data
jQuery .on()
You can make a global JavaScript variable and use it in your scripts.
<script type="text/javascript">
myVariable = <?php echo $x; ?>;
</script>
You can store your variables someplace and then access them via JavaScript.
<input type="hidden" class="myVariable" value="<?php echo $x; ?>"
<script type="text/javascript">
var myVar = $('.myVariable').val();
</script>
After you have your data in JavaScript you can do what ever you want to do with it.
I'm having this little problem with internet explorer and ajax.
So first I used just php, and everything, worked, but because I don't want to reload the page, I use ajax.
So I have a form with a checkbox. When someone clicks on the checkbox, my ajaex is called and the input is changed in the db. In firefox there is no problem, but It doesn't work in internet explorer.
Here's a part of my code:
<script language="javascript" type="text/javascript">
function changefield($doss, $display){
$.get("update.php",{dossier: $doss, CSQ_DISPLAY:$display});
alert("test");
}
</script>
echo '<form id="'.$r ['BC_DOSSIER'].'" method="get" action="">
<input type="checkbox" name="CSQ_DISPLAY" '.$checked .' onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this.checked)">
</form>';
It seems that in explorer, I only get the alert when the checkbox was checked. (Problem because it first reads the db if it must be checked or not, so you can change it later).
Does someone know where I went wrong?
Thank you very much in advance for the answers.
I would prefer to define it like this, I hate using onclick in my HTML:
edit FIXED (registered to change instead of click)
edit Wrapped in $(document).ready()
edit Added a click event as well
<?php
echo '<input class="ajax_check" id="check_'.htmlspecialchars($r['BC_DOSSIER']).'" type="checkbox" name="CSQ_DISPLAY" '.$checked .' />';
?>
<script type="text/javascript">
$(document).ready(function() {
$('input.ajax_check').click(function() {
this.blur();
});
$('input.ajax_check').change(function() {
var dossierId = this.id.slice(6);
var isChecked = (this.checked) ? 1 : 0; // better to explicitly convert bool to int for HTTP requests
$.get('update.php',{
dossier: dossierId,
CSQ_DISPLAY: isChecked
});
alert('test');
});
});
</script>
This will register that handler to all inputs with the className 'ajax_check', without leaving a function cluttering up the window object, and without messing up your HTML. Try it out and see if it fixes the problem - it may not as it does basically the same thing, but it's a better way of doing it IMHO. If you still have a problem, come back to me and we'll debug it.
Note that using this approach, it is important that the <script> is executed after the DOM is ready, so it should either be defined in the body after the checkbox or (better) wrapped inside $(window).load() or (best) $(document).ready().
In your code fallback function value wont passed for IE.
<input type="checkbox" name="CSQ_DISPLAY" '.$checked .' onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this.checked)">
i.e) in above code onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this.checked)" this.checked will not work for IE, so you can pass as this and get the value in four function, this will work for all the browsers. e.g) like this
<input type="checkbox" name="CSQ_DISPLAY" '.$checked .' onchange="changefield(\''.$r ['BC_DOSSIER'].'\',this)">
and get the checked attribute inside the function.
I hope this will work.
How do I use POST using jQuery/Javascript to send to another page and redirect to that page?
Sending variables using GET...
In Javascript
window.location = 'receivepage.php?variable='+testVariable;
When it is receive by PHP...
$var = $_GET['variable'];
How do I do that ^ , using $_POST?
I already tried...
$.post(
'receivepage.php', {
i: i
}, function(){
window.location = 'receivepage.php';
}
);
but it seems to lose the variable when it reaches PHP
Doing $.post is trying to post the information via ajax, and THEN redirecting to your page, so when you finally get there, the attribute "i" won't be received.
You could do someothing like this:
HTML
<form method="post" target="receivepage.php" id="myform">
<input type="hidden" name="i" value="blah" />
</form>
JS
<script type="text/javascript">
$("#myform").submit();
</script>
Does that solve your problem?
Edit
If your value comes from JS, you can add it like this:
JS
<script type="text/javascript">
$('#myform input[name="i"]').val(i);
$("#myform").submit();
</script>
According to your example, "i" is defined on the window scope, making it global and accessible from this script.
In your post example, $_POST['i'], would be your variable.
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()">