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.
Related
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=""/>
I use Facebook JavaScript SDK.
I want to know how to post the Javascript variables to another page with GET or POST or any other way.
For example i have:
userInfo = document.getElementById('user-info');
How to post it to new page ?
location.href="http://www.walla.com/?info=" + info.id;
Not working
Better use ajax for this ..
here is an example.
<script type="text/javascript">
$(document).ready(function() {
$('#submit-btn').click(function() {
$.ajax({
type:'POST', //POST or GET depending if you want to use _GET or _POST in php
url:'your-page.php', //Effectively the form action, where it goes to.
data:$('#txtName').val(), //The data to send to the page (Also look up form serialise)
success:function(e) {
// On success this fill fire, depends on the return you will use in your page.
}
});
return false;
});
});
</script>
<form>
<input type="text" id="txtName" />
<input type="submit" id="submit-btn" value="Send" />
</form>
Hope it works for u.
That looks okay. You should be able to obtain info.id via $_GET['info'] from PHP.
However, that's assuming userInfo is a simple string.
If it isn't, you may have to convert it to string first. One way to do that is through JSON as JSON is decodable at PHP's side using json_decode().
I'm trying to figure out how I can pass data from page-list.php to page.php using jQuery .post() and .click().
Code in <head> of page-list.php:
<script type="text/javascript">
$(document).ready(function(){
$('button.link').click(function () {
$.post("page.php", {pageID: "1"} );
}
});
</script>
Code in <body> of page-list.php:
<button class="btn link">LINK</button>
When I click LINK, nothing happens.
I'm also not sure how to call the posted data on page.php. Should I create a variable in PHP like this?
$pageID = ($_POST['pageID']);
And then call it in the body like this?
echo $pageID;
If I understand correctly what you are trying to do is $.post() a variable to "page.php" and then redirecting to "page.php".
If that is what you are trying to do it just won't work. $_POST requests are independent of each other, i.e. using $.post, accessing $_POST['pageID'] will result in whatever value you sent but won't display anything because the browser was not sent to the new page with the variables; but redirecting and trying to access the same variable will result in "null".
It is that same reason that when you use a log in system and refresh the page right afterwards the browser confirms that you want to send the information again.
Using $_GET might be more of what you need. Another option would be to use and form to post the variables.
I hope that helps.
For one thing you are missing a couple of characters.
<script type="text/javascript">
$(document).ready(function(){
$('button.link').click(function () {
$.post("page.php", {pageID: "1"} );
}); // missing end of statement.
});
</script>
Hello I have the next code into my website:
<input type="text" id="name" name="name" width="25px"/>
Add User
I need that when I click "newUser" the value of the name is saved into my mysql database without refreshing the page.
Any exemple of how to do this?
If you don't want to use a <form> and a submit button which would be the absolutely correct way to do this, you will need to use javascript and AJAX:
Subscribe for the onclick event of the anchor
Send an AJAX request to the server passing the value of the name entered in the textbox
Cancel the default action of the link
Add User
and the insert function could be defined in a separate javascript file:
function insert() {
var name = document.getElementById('name').value;
// TODO: send an AJAX request to the server
return false;
}
http://api.jquery.com/jQuery.ajax/
$('#newUser').click(function(ev){
$.ajax(...);
ev.preventDefault();
});
This can be done on the client side with jquery's ajax libraries to create the refreshless submit.
Here's an example of some html and javascript
<html>
<head>
<script type="text/javascript" src="jq/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
function adduser()
{
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "adduser.php",
data: data,
dataType: "html",
});
}
</script>
</head>
<body>
<form id="adduserform" name="adduserform">
<fieldset>
<input type="text" id="name" name="name" width="25px"/>
</fieldset>
</form>
Add User
</body>
</html>
On the php side just code like you would if you were submitting a form via post.
I haven't had time to try it, but I hope it works :)
Like the others have suggested, look on the jquery site for more info.
You can do an Ajax call with JQuery that will send the name to the server. In your PHP code you will be able to create the Insert Query in your user table.
You can use JavaScript for that. Take a look at jQuery ajax: http://api.jquery.com/jQuery.ajax/
note: next time try googling, or at least provide what you have tried
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()">